Programming is hard by Stephan Schmidt

The only thing that really matters in software development.

Catchy title? I mean it. After 25 years of programming, the only thing that really matters in software development is if a company understands the project triangle. That from the three variables scope, time and resources you can only define two. There are two kinds of companies. Those that understand this and those that don’t. Everything they do flows from there. This is what really matters about software development.

Update: There are a lot of other factors, probably people being one of the most important (think “Peopleware”). Without understanding the Scope-Time-Resources triangle your development won’t work. It just can’t. You can screw up by chosing the wrong architecture, or methodology, or screw up during requirement engineering or with the wrong language for the problem.

But from my point of view this triangle is like gravity. If you ignore gravity, all else will fail.

Unboxing as a Java Interview Question

Sometimes I ask an unboxing question during Java interviews. “What can happen with unboxing? See this code:”

Integer i1;
...
// do some things with i1;
...
int i2 = i1;

The thing that can happen is that i1 is NULL which will result in a NullPointerException being thrown.

“What is the problem with the NPE here?” There are several ones. The big one is that developers search for dereferencing variables (think “.”) when seeing a NPE. The line

int i2 = i1;

does not have a dot, the trained eye of a Java developer has problems to see the NPE there (if he didn’t encounter the bug before).

“What would you have done instead, if you would have been the Sun developer designing the unboxing feature?”

Possible answers are:

  • Set i1 to the default value if i2 is null, 0 in this case (null being the default value for Integer)
  • Throw an IllegalArgumentException
  • Throw a ClassCastException
  • Throw an AutoUnboxingException (my favorite)

It’s more about discussing design and programming decisions than getting the right answer from the candidate. With questions like this you can see how defensive a programmer can think, how he writes maintainable code and how good his micro-architecture design skills are. Often there is a dialog between the candidate and me about good design, error handling, exception handling and error messages.

What would you do?

Thanks for listening.

As ever, please do share your thoughts and additional tips in the comments below, or on your own blog (I have trackbacks enabled)

Update: This code will throw an NPE too - obviously - but from reading the isSomething() line in a large app it might not be that obvious.

public class Test {

	public static void main(String[] args) {
		if (isSomething()) {
			System.out.println("Something!");
		}
	}

	public static Boolean isSomething() {
		return null;
	}
}

Akismet has protected your site from 100,152 spam comments.

The title says it all. Thanks.

Update: One month later: “Akismet has protected your site from 126,559 spam comments.” 27.000 spam comments in 1 month.

Bending Java: More readable code with methods that do nothing?

From the category “Bending Java near it’s Breaking Point” or “What a stupid but interesting idea”. I like to explore ideas in Java that are inside the language spec but outside of common usage or style guides. I think Java has a lot more to give than what people did the last ten years. Before dumping Java perhaps we should reconsider some of the “common wisdoms” about how to do things in Java.

My last post on beautiful Java, and why to never use String ;-) got me flamed like I haven’t been flamed since alt.amiga.advocacy times. The idea was to provide wrappers around String like Name to achieve several things: Have better typed method signatures, have a fluent interface and to better convey meaning.

Customer customer = new Customer( name("Stephan") );
...
Customer(Name name) {
...
}
...
public Name name(String value) {
...
}

The flames were mostly about creating lots of small objects, which people claimed are unnecessary and unmaintainable.

An alternative implementation would be:

Customer customer = new Customer( name("Stephan") );
...
Customer(String name) {
...
}
...
public String name(String value) {
 return value;
}

This implementation doesn’t achieve the same things as the solution before, but there is no new object necessary, only a new method.

But still the line Customer customer = new Customer( name("Stephan") ); is more readable than Customer customer = new Customer( "stephan" );. The Hotspot JIT should optimize the method calls away so there is no performance penalty.

A better idea? Or still too repulsive.

Thanks for listening.

As ever, please do share your thoughts and additional tips in the comments below, or on your own blog (I have trackbacks enabled). This line is shamelessly take from Daniel Tenner, who writes a really excellent blog.

300 readers milestone - thanks again

After my 200 reader milestone in January, we’ve reached the 300 (317) reader milestone. Thanks to all the regular readers of this blog for listening. I know 300 is still not as many readers as others have, and it might drop below 300 the next day, but I’m still thankful for everyone of you (including those with comments who prove me wrong - as happened in the last posts - or whose comments make an interesting reading :-)

Links on Open Sourcing?

I’m working on a paper on Open Sourcing and - though I have quite some knowledge on the topic - cannot find a lot of relevant papers, posts or articles. Most hits are about open source not open sourcing and “open sourcing” doesn’t find relevant things. Any ideas? Any papers? Any links? Thanks :-)

Never, never, never use String in Java (or at least less often :-)

Never, never, never use (unwrapped) String or long or int. Why? Those primitive types have no semantic meaning. They are hard to understand, hard to maintain, and hard to extend. I’ve been evangelizing this concept for some time, the essay “Object calisthenics” finally prompted be to write this post. Suppose we have an example of a cinema ticket booking service.

Update: If you just want to drop a comment telling me how revolting you find the idea, well, just don’t. I appreciate your comment, but sit back, think some time about it and move on coding. When you read someone else code with String id and you wonder what on earth the id is, come back and read this post.

Compare

public void bookTicket(
  String name,
  String firstName,
  String film,
  int count,
  String cinema);

with (and I know one would introduce an Order object for real code):

public void bookTicket(
  Name name,
  FirstName firstName,
  Film film,
  Count count,
  Cinema cinema);

The second one is much easier to understand, especially when your IDE is one that tells you during autocompletion of a method call bookTicket(String arg0, String arg1, String arg2, int arg3, String arg4) versus bookTicket(Name arg0, FirstName arg1, Film arg2, Count arg3, Cinema arg4). The second one is also much easier to read.

Compare

void book(String orderId);

with

void book(OrderId order);

In the first case the developer seeing the code wonders a.) where to get an orderId and b.) what an orderId really is, "1212", "ABC-123" or "12-34-45-SCHWEINEBACKE". In the second case he can search for the usage of the OrderId class, how it is used, read the javadoc and only pass validated and correct order ids into an application. You might think an orderId is just an orderId, easy to find. Legacy systems will change the id, the naming and semantics in often inconsistent ways. I’ve seen systems that name an order ID in serveral ways as “orderId”, “AuftragsId”, “id” and several other names and all meaning the same thing!

It’s easier to have a class with semantics than a domain-less String. Developers cannot as easily mess up. If you rely on static typing and use a startic type language (both object and reference) then maximize your benefits and create more classes. In the future an OrderId class can also easily be changed to hold long instead of an int, hold validation or id generation logic. It’s much harder to extend the initial String based version.

Implementation with a fluent interface

The classes should be implemented as simple Domain classes, sometimes as immutable value objects, which just wrap String and attach some semantic meaning to the String.

public class Name {
   public Name(String name) {
      ...
   }
   public static Name name(String name) {
     return new Name(name);
   }
}

One would wonder if the solution is too noisy. Assuming

new Customer(new FirstName("Stephan"), new Name("Schmidt"));

is certainly noiser than a String argument:

new Customer("Stephan", "Schmidt");

The first is easier to understand though, and with static methods can be changed to

new Customer(firstName("Stephan"), name("Schmidt"));

This also solves the problems that with many arguments developers from reading the code don’t understand what each parameter means, especially in longer (refactor to parameter object!) parameter lists. This is another approach to Fluent Interface builders.

My last post on how to use generics with immutable objects could also be extended with value objects instead of primitives.

new Point(10,10);
new Point(x(10), y(10));

where x(10) and y(10) create Xpos and Ypos value objects.

Domain objects vs. primitivs in interview questions

One of the interview questions I like is to ask people about an interface for a price search. I usually give them

... searchByPrice(...)

and let candidates fill in the missing parts. Some will write

Vector searchByPrice(double start, double end)

which is bad code from several points of view (using double for money, no domain objects, untyped Vector).

Others with more domain based thinking write

List<Product> searchByPriceRange(Price start, Price end)

or even us the Range pattern by Fowler:

List<Product> searchByPriceRange(PriceRange priceToSearch)

The last solution is easy to extend and understand. Answering this question often starts an interesting discussion on interface design, maintainablity and domain modelling. Whatever you think about this interview question, don’t forget to once and for all: Do not use double for money.

Thanks for listening and don’t use String, int and long (or double for money).

Update:

If you find the usage of Classes instead of Strings repulsive, look at another example, zip code. Most people I’ve seen in lots of code use a primitive for zip code which creates a lot of problems when going i18n.

Customer {
   String name;
   String street;
   String city;
   String zip;
}

(some will have used int for the zip code but get faster into trouble than the String users)

instead of

Customer {
   String name;
   Address address;
} 

Address {
   ZipCode code;
}

Still think Strings are a good idea in your code or “the simplest thing that could possibly work”?