I was going through the Docs for Groovy when I came across this little gem of Java (well, Groovy):
Can you guess what it does? It returns a 0 (Calendar.AM) if the current time is in the morning, and 1 (Calendar.PM) if it is in the evening. It also points out some reasons Java blows my mind.
First: We’re using a Calendar to find out if it is in the morning or night. I don’t know about you, but the calendar on my wall cannot tell me if it is AM or PM. It can’t even tell me the time. However in the Java world (in which also exists both Date and Time classes), a Calendar knows all, and can tell us what time it is.
Second: Calendar is a factory method, because Calendar objects have a pointer to some “time” that you give it (it defaults to the current system time). So we can’t just query a Calendar for some bit of information, because a Calendar isn’t really what you are probably thinking it is (a static reference to all things Date related), but instead a specific time. As such, in order to get the current time, we need to get a new instance of a Calendar that has not been initialized to any specific date.
Third: Now that we have an instance of the current Time Calendar, we’re going to call the method we use to find out if it’s AM or PM. This is helpfully named “get”, which is then passed the only marginally more usefully named constant from the Calendar class, “AM_PM”.
Now I’m not saying this is the worst implementation of this concept, in fact I can think of a few cases where structuring it as such might be very useful. However, from a code-readability point of view, contrast the code at the top with similar one liner from other languages.
Both use modules/classes named “Time”. Ruby explicitly indicates that you’re working with the current time, whereas python does not. I’ve used strftime for both to return the string “AM” or “PM”. Probably not the most elegent way to do it (I’d extend either’s time class to contain a new method to return whether it is AM or PM if I were to put this in production code) but certainly easier to understand.
I’m sure there are some Javanistas out there who can point out why the way Java does it is preferable or why the ruby/python way is not right, if so, comment.