Write Programs for People First, Computers Second

There are several computer books that have become classics. One of these is Code Complete by Steve McConnell. The first edition was written in 1993. That goes back to when I started collecting a paycheck as a professional developer. And it precedes classics like the Gang of Four’s Design Patterns (1994), The Pragmatic Programmer: From Journeyman to Master (1999), Agile Software Development: Principles, Patterns, and Practices (2002) and Clean Code (2008). Some consider this book to be the first collection of coding practices.

In this book, McConnell stresses the importance of readable code.

codecomplete_readable

He notes that writing readable code is one of the things that separates the great coders from the rest.

A great coder [level 4] who doesn’t emphasize readability is probably stuck at Level 3, but even that isn’t usually the case. In my experience, the main reason people write unreadable code is that their code is bad. They don’t say to themselves “My code is bad, so I’ll make it hard to read.” They just don’t understand their code well enough to made it readable, which puts them at Level 1 or Level 2.

Even before Code Complete, the book Structure and Interpretation of Computer Programs, written by Abelson and Sussman, was published in 1985. The full text of the book is available online (link). The preface to the first edition (link) contains the oft repeated line:

programs must be written for people to read, and only incidentally for machines to execute.

Why is readability so important? Continue reading “Write Programs for People First, Computers Second”

Advertisements

(Mostly) XMLless Spring

I am working on a project using Spring. As a team we were using Spring’s Java configuration. But we also had an applicationContext.xml file. We wanted to remove the need for this file. This post captures the basic steps to accomplish that.

Our web.xml was using the standard approach to load Spring using the WebApplicationContext via the ContextLoaderListener.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

</web-app>

This setup requires, at a minimum, a component-scan element in our applicationContext.xml file so that Spring will look for the Java classes that include an @Configuration annotation.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
                        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

  <context:component-scan base-package="codesmell" />

</beans>

Assuming we had a simple class FooBar that was configured in a Java class, Config as follows:

@Configuration
public class Config {

    @Bean
    public FooBar doFooBar() {
        return new FooBar();
    }
    
}

Then when we run the application we would see the following (assuming the FooBar class writes out ‘foo bar!’ (see line 11) when it is created):

Nov 22, 2016 2:37:34 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Nov 22, 2016 2:37:34 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Nov 22, 2016 2:37:34 PM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Tue Nov 22 14:37:34 EST 2016]; root of context hierarchy
Nov 22, 2016 2:37:34 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
Nov 22, 2016 2:37:34 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
foo bar!

With a few additions to our web.xml file we can delete the applicationContext.xml file.

We will add the AnnotationConfigWebApplicationContext so that the WebApplicationContext will accept annotated classes. Then we will add a contextConfigLocation so that Spring will use our Java config class instead of the default of /WEB-INF/applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
  </context-param>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>codesmell.config.Config</param-value>
  </context-param>
</web-app>

Now we get this:

Nov 22, 2016 2:36:30 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Nov 22, 2016 2:36:31 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Nov 22, 2016 2:36:31 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Nov 22, 2016 2:36:31 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Tue Nov 22 14:36:31 EST 2016]; root of context hierarchy
Nov 22, 2016 2:36:31 PM org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
INFO: Successfully resolved class for [codesmell.config.Config]
Nov 22, 2016 2:36:31 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
foo bar!

Nested Fluent Builders with Java 8

In the last post we looked at how to create an object using a fluent API in order to remove the code smell of a constructor with a long parameter list. We wrote the fluent methods directly onto the Invoice POJO, but we saw this broke the principle of Command Query Separation. In this post we will apply the Builder pattern, with the primary purpose of exploring how to make a nested fluent API using Java 8 lamdas. For more information on this pattern see Item 2 in the second edition of Effective Java by Josh Bloch.

We will start by removing the static factory methods from our Invoice class and replace them with a public static inner class, InvoiceBuilder. We will also need to add a static method (builder) that allows an instance of the InvoiceBuilder to be returned to any object that wants to create an Invoice. Finally, we will want to make sure that the constructor is private to force the use of the builder method to create an Invoice.

public class Invoice {
	...

	/**
	 * static factory method for builder
	 */
	public static InvoiceBuilder builder() {
		return new Invoice.InvoiceBuilder();
	}

	/**
	 * force use of builder()
	 */
	private Invoice() {
	}

	public static class InvoiceBuilder {
		// more to come
	}
}

As a static inner class we do not have access to non-static variables on the outer class. But if we manage an instance of the Invoice from inside our InvoiceBuilder we can take advantage of being an inner class and access the private instance variables through that instance. Continue reading “Nested Fluent Builders with Java 8”

Fluent Object Creation

When we are tasked with creating a POJO we will often fire up our favorite editor, add the attributes, and generate the accessor methods.

Here is an example of an Invoice class. For simplicity sake only a few of its many attributes will be shown.

public class Invoice {

	private InvoiceActor invoiceSupplier;
	private InvoiceActor invoiceDestination;
	private String supplierDocumentId;
	private Date documentDate;
	private String trailerNumber;
	private List<InvoiceItem> items;
	...

Given this code we would then create an instance of our Invoice and use our setters to populate the values of the attributes.

InvoiceActor supplier = new InvoiceActor();
supplier.setActorName("101");
supplier.setActorType(InvoiceActorType.DC);
...

List<InvoiceItem> list = new ArrayList<InvoiceItem>();
InvoiceItem itemOne = new InvoiceItem("TK421", 10, 8);
list.add(itemOne);
...

Invoice inv = new Invoice();
inv.setSupplierDocumentId("5150");
inv.setTrailerNumber("2112");
inv.setInvoiceSupplier(supplier);
inv.setInvoiceDestination(reciever);
inv.setItems(list);

When creating our POJO, we could add a constructor to our class that accepts the values for the various attributes so that they are initialized when the object is created. It allows us to create the object with less code than what we see above. It can also allow us to insure that our object was in a valid state at the point it is created (see Constructor Initialization for more details). And if we were going to make our Invoice class an immutable object we would need to get rid of the setters so we would typically turn to a constructor with parameters as an alternative to populate the attributes. Continue reading “Fluent Object Creation”

Not Just Coding Zombies

Listened to this talk by Martin Fowler, of Agile Manifesto fame. In this talk he suggests that “we as developers should not be just code monkeys bashing out code.” We developers, he suggests, need to consider the responsibility that we have for the software that is going to be written and used.

And I think that we have a certain responsibility to say: where are we going to apply our talents? Because in the end we are responsible for using our talents to, hopefully, make the world somewhat of a better place.

… we should say “is what we are doing useful?”

This reminded me of the Spiderman quote : with great power comes great responsibility. And having just read the graphic novel Marvel Zombies, led to capturing the main idea of the talk in this graphic.

codingzombies2

Continue reading “Not Just Coding Zombies”

The Agile life has been good to me so far

With apologies to Joe Walsh and all my coworkers through the years here is a little ballad about work in the IT field on this Labor Day. Read/sung to the tune “Life’s been good to me so far”.

I use open source, it has no price
I contribute back, it works so nice
Why does commercial get used at all
Costs so much bang my head ‘gainst the wall

They say I’m crazy but I have a good time
I’m just looking for bugs at the scene of the crime
Life’s been good to me so far

Our velocity was one-eighty-five
but our release plan took a nose dive
Now we limit wip, our flow is great
I check the board to find out our fate

There is a deadline, my boss he can’t wait
I’ll call my sweet wife, I’m working late
And I got me no office, cube farms have no walls
Like coding cattle sittin’ in stalls

Lucky I’m sane writing code like I do
I can’t keep up there’s always somethin’ new
Life’s been good to me so far

I write some software, it’s agile clean code
If there’s no bugs we’ll deploy on some nodes
My product owner has not a clue
We’ll bail ’em out like we always do

My mind goes hazy codin’ for all this time
I keep on writin’ pays the bills so that’s why
Life’s been good to me so far