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


5 Responses to “Simple Java naming trick: now and today”  

  1. Gravatar Icon 1 Eric

    +1

    I use this naming too.

  2. Gravatar Icon 2 Florian Kruesch

    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.

  3. Gravatar Icon 3 stephan

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

  4. Gravatar Icon 4 Florian Kruesch

    yep, and much more time :)

  5. Gravatar Icon 5 stephan

    Hehe.

Leave a Reply



RSS