Quotes for developers

“Perfection is reached, not when there is no longer anything to add, but when there is no longer anything to take away. ”
– Antoine de Saint-Exupéry

 

“For a long time it puzzled me how something so expensive, so leading edge, could be so useless, and then it occurred to me that a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a perfect match.”

– Bill Bryson

 

“Walking on water and developing software from a specification are easy if both are frozen.”
– Edward V. Berard

 

“I object to doing things that computers can do.”
– Olin Shivers

 

Read many more there: http://www.softwarequotes.com/

Code comments gone wrong

Adding code comments is supposed to be good practice, but here is why it often fails:

  • Code is the single authoritative source of truth in a program !
  • There is no way to ensure that code comments are correct at all times (not always updated as code changes).
  • Comments are written in human language which can be prone to misinterpretation.

First put your good intentions into writing simple and readable code.

Write self descriptive code ! Your code should be read like sentences. Avoid smart shortcuts and tricks because they break the reading. Expect the reader to have solid programming knowledge but no knowledge about the purpose of your code. If code is too compact add extra code steps to document it, for example:

...
final Person dummyPerson = new Person("Joe", "Bloggs");
return dummyPerson;

Instead of using a comment:

...
// Return dummy person.
return new Person("Joe", "Blogs");

Ok ok, this example was a bit silly but you got the idea.

Using long names is considered bad practice, I disagree. Prefer using long explicit names over short meaningless names which require code comments. Sometimes long names are really annoying, for example when they keep appearing everywhere in some algorithm, in that case you could use a comment.

Consider using more columns:

The default max of 80 columns is terrible, use a wide screen  and use 120 columns or more, the code will be more readable because long lines will not wrap anymore and you can use longer more explicit names.

Use assertions to document pre and post conditions instead of lengthy comments.

public List<String> listFiles(final String folderUrl) {
  assert folderUrl!= null;
  assert folderUrl.endsWith("/");
  ...
}

If you write an API a good documentation is necessary but for internal code I think comments should not replace good naming and code clarity. I use code comments when the code is not really self documenting. Comments should convey what code cannot. They should explain the reasons for a specific design decision, they should explain what code is supposed to achieve and why.

Learn how to use the Javadoc, it not only looks better, it can also help automatically update some documentation. When referring to code try using the link tag. Your IDE may automatically update the linked method and class names during renaming which ensures that some of your documentation stays up to date.

/**
* Use the link tag: {@link SomeClass#someMethod}
*/

Links:

Eclipse Indigo: static code analysis about static and why you should care

Eclipse Indigo comes with new optional static analysis ‘warnings’ which automatically detect methods that could be static.

Eclipse Indigo 'method could be static'

Eclipse Indigo 'method could be static'

To activate the warnings associated with this feature go to Windows->Preferences->Java->Compiler->Errors/Warnings->Code Style (or just search for ‘warn’, see screenshot) and click on the Ignore drop down box and select Warning. I have not tested the ‘potentially be static’, maybe I will turn it on when there are no warnings left to fix from the first one.

Reasons for the addition of this feature:

Static methods:

  • limit scope to static variables and passed parameters, thus avoid potential side effects
  • do not require an instance to be called
  • may not be part of a specific class and moved to a more appropriate place (tool/utility)
  • increased performance

Static methods are one step towards ‘pure functions’, here is the definition of a pure function: “The only result of invoking a pure function is the return value”. To learn more about pure functions, read this post about pure functions.

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

Antoine de Saint-Exupéry (French writer)

Adding the static keyword means removing (reducing) scope and potential mistakes (present and future). Bear in mind that a bunch of static methods are enough in some cases. This is why I am happy about this feature and you should too, so be sure to turn it on if you happen to be using Indigo. Have a look at the other warnings, some interesting ones are ignored by default.

Related:

Book review: The Pragmatic Programmer

This is one of the few books written by programmers for programmers that is not technical in essence. The book is more high-level, it does not talk much about code. This also gives this book a longer lifespan than its technical counterparts.

Some of the described concepts could apply to other domains, hence the book  cover analogy (wood working). This is what makes the book really shine, it will teach you some ideas that can be applied everywhere, not only when programming. The common factors can, in my opinion, be reduced to fundamental design issues or the human psyche. The book features many cross section references, this highlights that everything is related. Somehow we always felt that everything was related, didn’t we ?

Because it is not very technical it easier to digest, I found it easy to read, and read again. I recommend this book to everyone, especially to beginners and perhaps even to non-programmers who work in an IT environment. For the experienced ones this book, may in 2010, be a little disappointing, but you should give it a try.

Related posts

Why every Java field should have been final by default.

Introduction

Note to clarify the post: by default I mean having to write something like ‘var’ to have the current behavior (fields can be reassigned), so that if you write nothing the field is automatically final. You still have the choice about being able to reassign or not by using some kind of keyword like ‘var’. I hope it is clearer now !

We all like freedom, but what is freedom when we talk about code ?

You have a lot of freedom with mutable fields, too much, why not let the compiler help you by telling it that your data is immutable ? Is it because you want more possibilities to write code that does not do what you want ?

You sure do not want to, and please do not tell me the final keywords make your code hard to read, it does the exact opposite: it tells the compiler and the reader that your data will never change and this is important information. Most of the time it forces you to write cleaner code that uses less ‘smart tricks’.

(Note: this post is NOT about the ‘other’ final keyword, the one used on classes and methods. It is also not about immutability in general, a much broader topic, but the given links will provide some lecture.)

Examples that illustrate why every Java field should have been final by default:

Example 1: Bad initialization in constructors.

public class UnidentifiedPerson {

 private String _firstName, _lastName;

 public UnidentifiedPerson(String firstName, String lastName) {
   _firstName = firstName;
   // Notice how the lastName is never set and the compiler does not complain !!!
 }
}

There is rarely a need for such code, most of the time you will find that making the fields final will force you to write better constructors.
This is especially true when you have many fields to initialize and when you refactor code.

Example 2: Changing data that is immutable by nature.

public class Person {

 private String _firstName, _lastName;

 public Person(String firstName, String lastName) {
   _firstName = firstName;
   _lastName = lastName;
 }

 public Person changeIdentity(String firstName, String lastName) {
   // It is so easy to change my name.
   _firstName = firstName;
   _lastName = lastName;
   return this;
 }

 @Override
 public String toString() {
   return _firstName + " " + _lastName;
 }

 public static void main(String[] args) {
   System.out.println(new Person("Christophe", "Roussy").changeIdentity("Bill", "Gates"));
 }
}

If you make the fields final the compiler will tell you something interesting:

public PersonFinal changeIdentity(String firstName, String lastName) {
 // The final field PersonFinal._firstName cannot be assigned.
 _firstName = firstName;
 // The final field PersonFinal._lastName cannot be assigned.
 _lastName = lastName;
 return this;
 }

Example 3: Hiding potentially useless code.

public class UselessAssignment {
 public static void main(String[] args) {
 int a, b;
 a = 1;
 b = a;
 a = b;
 // This kind of code is only possible with mutable fields, it will
 // eventually turn up because it can.

 final int fa, fb;
 fa = 1;
 fb = fa;
 fa = fb;
 // The final local variable fa may already have been assigned.
 }
}

When prefixing fields with the final keyword, some undesired code will emerge, it may even explain and solve some bugs.

When not to use final ?

There a only few cases where you want to use mutable fields, such as computing sums:

private static int computeSum(final List<Integer> values) {
   // Here it makes sense not to use final as you do WANT to change the value
   // of sum. Also note how I now use int for sum to avoid autoboxing.
   int sum = 0;
   for (final int value : values) {
     sum += value;
   }
   return sum;
 }

A good way to figure out if you want to remove the final keyword is to ask yourself: “Do I really want this variable to be mutable ?”.

It can sometimes be tricky not to use mutable fields when you are used to them, but on the long term you will discover that it is well worth the effort to help the compiler so it can help you and others. Also note that making a list final does not make the list fully immutable, you will not be able to reassign the list itself, but you will be able to add, remove and modify the contained elements. I have also read that the value of final fields can be changed using reflection (http://www.javaspecialists.eu/archive/Issue096.html), but this is not a concern unless you want to experiment.

Conclusion

It is illogical that the Java language did not do the opposite: every field immutable by default and mutable only when prefixed with some language keyword. Perhaps it comes from the C/C++ mutable flavour Java inherited.

Links:

  1. http://renaud.waldura.com/doc/java/final-keyword.shtml, The Final Word On the final Keyword
  2. http://jeremymanson.blogspot.com/2008/04/immutability-in-java.html, Immutability in Java.
  3. http://www.ibm.com/developerworks/java/library/j-jtp1029.html, Is that your final answer?
  4. http://www.ibm.com/developerworks/java/library/j-jtp02183.html, To mutate or not to mutate?

Composition versus Inheritance

In many cases you should favor composition over inheritance, I was willing to write an article about this, but I prefer to redirect you to an existing article:

Composition versus Inheritance
A Comparative Look at Two Fundamental Ways to Relate Classes
by Bill Venners

http://www.artima.com/designtechniques/compoinh.html

I recommend reading other articles on this site because they mostly address fundamental design issues:

http://www.artima.com/lejava

Java Calendar Puzzlers

As an extreme example of what not to do, consider the case of java.util.Calendar. Very few people understand its state-space — I certainly don’t — and it’s been a constant source of bugs for years.

Joshua Bloch talking about API design

In other words, whenever you see Calendar in use, perpare yourself for nasty bugs.

The following three puzzlers, inspired by the Java Puzzlers book concept, will hopefully surprise you and teach you.

Complete code can be found at the end of the article.

Puzzler 1

 final Calendar cal = Calendar.getInstance();
 cal.set(2010, 0, 0);
 System.out.println("1. " + cal.getTime());

 cal.set(2010, 1, 1);
 System.out.println("2. " + cal.getTime());

 cal.set(2010, 0, 1);
 System.out.println("3. " + cal.getTime());

 cal.set(2010, Calendar.FEBRUARY, 29);
 System.out.println("4. " + cal.getTime());

 cal.set(2009, Calendar.UNDECIMBER, 0);
 System.out.println("5. " + cal.getTime());

Can you guess the month and year for each one ?

Hey, guess before reading the solution !

The Disintegration of Persistence of Memory Salvador Dali

The Disintegration of Persistence of Memory Salvador Dali

Solution:

1. 31 December 2009

What happened, we asked for 2010, didn’t we ?

2. 01 February 2010

A bit better, we now have 2010, but still not january !

3. 01 January 2010

Ok that is what we expected for the first one.

4. 01 March 2010

We asked for FEBRUARY, but there is no february 29 in year 2010 (Learn about leap years). So the calendar added one day to february 28 and thus we end up in the next month.

5. 31 December 2009

This one resembles the first one, day zero is not valid, it means ‘remove one day’, because UNIDECEMBER is the 13th month, we end up in 13th month minus one day…

Lesson:

Calendar month are zero-indexed, while days are not. Calendar will not throw an error when passed parameters that are not coherent with what you specified (year, month, …).

Use existing Calendar constants as much as possible and think about leap years.

Puzzler 2

 final Calendar cal1 = Calendar.getInstance();
 final Calendar cal2 = Calendar.getInstance(Locale.US);
 System.out.println(cal1.getFirstDayOfWeek() == cal2.getFirstDayOfWeek());

True or false ?

Solution:

It depends…on your default locale. Calendar is a locale aware class, getInstance() will use the default locale and timezone.

Lesson:

Think about how the locale can impact your code, this is also valid for other classes.

If you know you only want a specific timezone and locale, enforce them by using alternative getInstance methods.

Puzzler 3

 final Calendar calendar1 = Calendar.getInstance();
 final int year = 2010;
 final int month = Calendar.APRIL;
 final int day = 14;
 calendar1.set(year, month, day);

 final int iterationCount = 1000;
 boolean isEqual = false;
 for (int i = 0; i < iterationCount; i++) {
   final Calendar calendar2 = Calendar.getInstance();
   calendar2.set(year, month, day);
   isEqual = calendar1.equals(calendar2);
 }

Solution:

It depends, on many things, try changing the iterationCount.

Calendar.getInstance() method returns more than just the current year, month and day. The hour, minutes and milliseconds are also set. So you may have code working on your machine but it will fail on another. What happens here is that the milliseconds changed, because getInstance returns the current time and time does change while your program is running. Such bugs can be extremely hard to track, if you are unlucky they may only show up from time to time depending on circumstances (CPU load).

Lesson:

To avoid such mistakes, either clone a calendar, or call the clear() method of Calendar before setting. When writing tests on methods using Calendars, rely on getTimeInMillis() instead of other getters, this is what the equals method relies on.

Conclusion:

The puzzlers have shown how counter-intuitive the Calendar class is, if your work involves a lot of time manipulation think about using Joda Time.

http://joda-time.sourceforge.net/


package javarizon;

import java.util.Calendar;
import java.util.Locale;

/**
 * <a href="https://javarizon.wordpress.com/2010/04/25/java-calendar-puzzlers/">
 * Java Calendar Puzzlers</a>
 *
 * @author Christophe Roussy
 */
public class CalendarPuzzlers {

 public static void puzzler1() {
 final Calendar cal = Calendar.getInstance();
 cal.set(2010, 0, 0);
 System.out.println("1. " + cal.getTime());

 cal.set(2010, 1, 1);
 System.out.println("2. " + cal.getTime());

 cal.set(2010, 0, 1);
 System.out.println("3. " + cal.getTime());

 cal.set(2010, Calendar.FEBRUARY, 29);
 System.out.println("4. " + cal.getTime());

 cal.set(2009, Calendar.UNDECIMBER, 0);
 System.out.println("5. " + cal.getTime());
 }

 public static void puzzler2() {
 final Calendar cal1 = Calendar.getInstance();
 final Calendar cal2 = Calendar.getInstance(Locale.US);
 System.out.println(cal1.getFirstDayOfWeek() == cal2.getFirstDayOfWeek());
 }

 public static void puzzler3() {
 final Calendar calendar1 = Calendar.getInstance();
 final int year = 2010;
 final int month = Calendar.APRIL;
 final int day = 14;
 // calendar1.clear();
 calendar1.set(year, month, day);

 final int iterationCount = 1000;
 boolean isEqual = false;
 for (int i = 0; i < iterationCount; i++) {
 final Calendar calendar2 = Calendar.getInstance();
 // calendar2.clear();
 calendar2.set(year, month, day);
 isEqual = calendar1.equals(calendar2);
 }
 System.out.println(isEqual);
 }

 public static void main(String[] args) {
 puzzler1();
 puzzler2();
 puzzler3();
 }
}

Eclipse line shortcuts

You can only have one thing in your clipboard, right ?

So you end up having to paste somewhere temporarily to avoid overwriting your clipboard content…you lose time and you mess up your files with temporary pastes that you forget to clean up…

There are other ways. If you want to clone a block of lines and move it somewhere nearby, proceed this way:

  1. Select the block of lines by pressing Shift + Arrow up/down.
  2. Press Ctrl + Alt + Arrow down, this will clone the block of lines.
  3. Move the lines where you want them: Alt + Up/Down.

You may still think copy & paste is faster, but notice how these shortcuts are similar, if you put your fingers on Alt and Ctrl and the up/down arrows you can combine them very quickly. It gets even faster for a single line.

In addition to that I would recommend using Ctrl + D for quickly removing lines and Ctrl + Shift + C to comment/uncomment lines. There are many other shortcuts,  but it does not make much sense to list them without giving a use case, simply press Ctrl + Shift + L.

There are various Multi clipboard tools/plugins, but I do not like depending on those.

Conclusion

This is very similar to copy & pasting, but it allows you to keep your clipboard content where you would normally not. These shortcuts can prove very effective when combined.

Related posts

Book review: Effective Java, Second Edition

I bought this book (at Eyrolles) about one month ago and nearly went through all of it.

Book cover

Book cover

http://java.sun.com/docs/books/effective/

The author, Josh Bloch, is writing code from an API designer’s perspective. It is not easy to view everything from this perspective at first, but after reading most of it APIs will become more transparent when used and you will even save precious time when writing your own.

My favorite chapters are:

  • 4. Classes and interfaces
  • 6. Enums and Annotations
  • 8. General Programming

Some chapters may not be crucial, like the one about serialization, but other chapters are worth reading for everyone.

Because you can read chapters in any order you will probably find this book easy to read. My approach is to read a chapter and apply what I have read, then I go on reading another one.

Conclusion

What struck me is that this book is a must read for intermediate java developers because it goes beyond mere Java syntax and gives some advice that is valid for any object-oriented language. You will keep coming back to it while programming, so keep it close.

Work towards the compiler

This is the first post !

You may think that you know what you are doing because it is your code after all, but if a mistake can be done it will be done (when refactoring or by someone else modifying your code).

This post illustrates how easy it is to write error prone code, but also how little effort it may take to reduce the danger.

Equals method:

Consider the following code sample:

package javarizon;

import java.util.ArrayList;
import java.util.List;

public class TypeSafeEquals {
 public static void main(String[] args) {
 final String one = "1";
 final int oneAsInt = 1;
 final Object object = "1";

 // Compiles...
 one.equals(oneAsInt);

 // First idea: It works, but if you pass an object by mistake it still
 // compiles. Have fun debugging !
 one.equals(String.valueOf(oneAsInt));
 one.equals(String.valueOf(object));

 // Better idea: It works, but will not compile if you use an object.
 one.equals(Integer.valueOf(oneAsInt).toString());
 one.equals(Integer.valueOf(object).toString());

 // Even better: it only takes an int.
 one.equals(Integer.toString(oneAsInt));
}
}

The first version is often used because it easy to come up with, but if you accidentally use a bad parameter, it will compile and not even break at runtime: it results in a bug that will be difficult to spot.

It might even work by chance in some cases (there are only two possible return values) depending on your application logic and data. Imagine you use such non-type safe code everywhere in your code, you or someone using your code is doomed to make a mistake at some point.

In the second version, the chances of committing a mistake were drastically reduced simply by using code that will accept less types, it does not compile when passed an object:

The method valueOf(String) in the type Integer is not applicable for the arguments (Object)

Consider using code completion on a method to quickly check what types it can take, if there are too many (especially evil Object) try looking for a more restrictive alternative. You could also write a static method that takes two Strings and uses equals internally, the only problem is that you have to do this for every possible type.

Conclusion:

Being careful is not enough, when properly helped the compiler is much more careful than you ever will. Always strive to maximize type-safety when writing code. Ensure the compiler is on your side by adapting your programming style to it.

I will try coming up with more examples in the future posts.