Code Monkeyism

Programming is hard by Stephan Schmidt

Simple Java naming trick: now and today

When browsing and reading code, I often find this:

Date currentDate = new Date();

Someone needs a current date. The line is unclear what the developer really wanted to achieve. Does he want the current date or the current time? The Date class in Java is ambiguous: “The class Date represents a specific instant in time, with millisecond precision. ” and therefore should probably be called Time with Date only representing a day (the better named Time class resides in java.sql, ugh, one of the ugly decisions in Java).

Better name your variables with more meaning. Make your intentions clearer and use Calendar, which is more useful when working with dates[1]:

Calendar today = today();
Date now = now();

The implementation looks like this (use static imports) [2]:

public static Calendar today() {
	return Calendar.getInstance();
}

public static Date now() {
	return new Date();
}

Please, make your code more understandable for all the developers who follow you.

[1] You probably want to use Joda Time
[2] I know, Calendar stores the time also

About the author: Stephan Schmidt is currently a team manager at ImmobilienScout24 in Berlin. Stephan has been working as a head of development and CTO. He has used a lot of different technologies in the last 20 years including Java, Rails and Python. Stephans main field of interest is maintainablity and productivity in software development. Want to know more? All views are only his own.

If you did like this article but you don't want to subscribe to new articles with your reader, you can follow me on Twitter or subscribe to new posts with your email:

Comments

Eric

+1

I use this naming too.

I’m currently reading the DDD book by Eric Evans for the second time. Have you seen that he provides a time and money library? Beeing able to clearly express a concept in code is a great and rare skill.

stephan

No, but I’ll take a look, everyone needs money :-)

yep, and much more time :)

stephan

Hehe.

Leave a Reply