Wednesday, 24 August 2011

Common Java method names

Following on from my discussion on some common class name prefixes and suffixes I wanted to discuss some method name conventions. Again, this all relates to Java - other languages are entrely different.

Common method name patterns

For better or worse, Java is a pattern-based language. By that, I mean that a lot of what is considered to be best practice in Java works is by following standard patterns. I don't just mean the Gang of Four book here. I mean the myriad of other patterns. These are often "visual patterns" as much as code patterns. For exmaple, by laying our code out in a certain consistent way, we aid the developer that follows us.

To be clear, I'm not saying that a pattern-based/naming approach is better than new language features. Its just that in Java that is the best we have to deal with many issues. (Cut and Paste is a way of life in Java, and its not always bad.)

One of these patterns is method names. This approach in Java is heavily influenced by two things - the size and dominance of the naming choices in the JDK, and the design of Java-Beans. Back in 2006, I proposed some additional variants for immutable classes, popularized by Joda-Time. This list includes both, plus some new ones I've added from ThreeTen/JSR-310. It isn't intended to list every possible method name convention, just some of the more popular, and those with specific semantics.

get Gets something from an object, such as bean.getBar(). This is also used with a key to lookup a list by index or a map by key, such as list.get(index) or map.get(key).
isChecks if something is true or false about an object or a property of an object. Example foo.isValid().
checkChecks if something is true, throwing an exception if it is not true. Example foo.checkValid().
containsChecks if a collection contains the queried object, such as coll.contains(bar). This can be used on classes that wrap, or otherwise act as, a collection.
removeRemoves an element from a collection, such as coll.remove(bar). This can be used on classes that wrap, or otherwise act as, a collection.
clearClears the object, typically but not necessarily a collection, so that it is "empty".
putMutable putter. This mutates the target object replacing or adding some form of key-value pair. Examples are map.put(key,bar) and bean.putFoo(key,bar)
setMutable setter. This mutates the target object setting a property, such as bean.getBar(bar).
withImmutable "setter". Returns a copy of the original with one or more properties changed, such as result = original.withBar(bar).
toConverts this object to an independent object, generally of another type. This generally takes no arguments, but might if it is appropriate.
asConverts this object to another object where changes to the original are exposed in the result, such as Arrays.asList().
buildBuilds another object based on either the specified arguments, the state of the target object, or both.
add/subtractAdds/subracts a value to the quantity. This mutates the target quantity (a number, date, time, distance...) adding/subracting the "foo" property. This name is also separately used for adding elements to a collection.
plus/minusImmutable version of add/subract for a quantity. Returns a copy of the original with the value added/subtracted. This name does not seem to work as well for adding elements to an immutable collection.
appendSometimes used to by methods that add to the end of a list, such as in StringBuilder.
resetResets the object back to a suitable initial state ready to be re-used.
past tenseUsed on immutable classes to helpfully suggest to the caller that the method doesn't mutate the target, but must instead be assigned to another variable. Returns a copy of the target object with the method name applied. Examples are immutable.normalized(), immutable.multipliedBy(bar), immutable.dividedBy(bar) and immutable.negated()

And here are some static method names:

of Static factory method. Typically used with immutable classes where constructors are private (permitting caching). This is used by EnumSet and ThreeTen/JSR-310.
valueOf Longer form of of used by the JDK.
from Longer form of of. JSR-310 uses 'from' when performing a "loose" conversion between types, ie. one that has a reasonable chance of failure. By contrast 'of' is used when the conversion is almost certain to succeed.
parse Static factory method that creates an instance of the class by parsing a string. This could just be another of method, but I think the semantics are clearer with a dedicated name.

Are there any more common names that I've missed? Comments welcome...

Sunday, 21 August 2011

PrintCompilation JVM flag

While doing some performance checking on ThreeTen/JSR-310 I tried using the -XX:+PrintCompilation flag. In doing so, I discovered a certain lack of documentation due to a key Sun blog no longer being available. This blog mostly exists to recover that information from the internet archive.

The PrintCompilation flag exists to show basic information on when Hotspot compiles methods. Moazam Rajas wrote about the output format in his Sun blog, which was ported to Oracle. Unfortunately, only part of the original article was ported, losing the vital part. The internet archive appears to have the key part of original document:

But nevertheless, lets get back to the meat of the matter, the question on -XX:+PrintCompilation. I thought that a more detailed explanation of this flags output existed somewhere on the public internet, but maybe I just can't find it today. So I'll make a small attempt to explain the output.

The -XX:+PrintCompilation flag output looks something like this:

1  sb   java.lang.ClassLoader::loadClassInternal  (6 bytes) 	
2  b    java.lang.String::lastIndexOf  (12 bytes)
3  s!b  java.lang.ClassLoader::loadClass  (58 bytes)

Flags correspond to:

b    Blocking compiler (always set for client)	
*    Generating a native wrapper	
%    On stack replacement	
!    Method has exception handlers	
s    Synchronized method	

As Rajiv points on, once you find the offending method, you can tell the JVM to bypass it by creating a .hotspot_compiler file in your current working directory with an exclude statement. For example,

exclude java/lang/String indexOf

This would stop the java.lang.String.indexOf() method from being compiled.

Two other messages that appear are "made not entrant" and "made zombie". Again, finding out what they mean isn't easy, however an OTN forum discussion has a link to a comment by Cliff Click:

Zombie methods are methods whose code has been made invalid by class loading. Generally the server compiler makes aggressive inlining decisions of non-final methods. As long as the inlined method is never overridden the code is correct. When a subclass is loaded and the method overridden, the compiled code is broken for all future calls to it. The code gets declared "not entrant" (no future callers to the broken code), but sometimes existing callers can keep using the code. In the case of inlining, that's not good enough; existing callers' stack frames are "deoptimized" when they return to the code from nested calls (or just if they are running in the code). When no more stack frames hold PC's into the broken code it's declared a "zombie" - ready for removal once the GC gets around to it.

So, here is my updated table of flags:

b    Blocking compiler (always set for client)
*    Generating a native wrapper
%    On stack replacement (where the compiled code is running)
!    Method has exception handlers
s    Method declared as synchronized
n    Method declared as native
made non entrant    compilation was wrong/incomplete, no future callers will use this version
made zombie         code is not in use and ready for GC

If you've discovered anything else about -XX:+PrintCompilation then please add a comment!

Update 2011-09-26:
Kris Mok has done lots of investigation of the flag in far more detail than I have. Please read his notes which are very comprehensive and by JDK version!

Thursday, 18 August 2011

More Java prefixs and suffixes

As a follow up to my last post here are some more common Java prefixes/suffixes.

By the way, have you subscribed to the new blog location yet? http://blog.joda.org/feeds/posts/default


More common Java prefixes and suffixes

The last post focussed on class names in the presence of an interface. AbstractFoo BaseFoo, DefaultFoo and SimpleFoo were my choices, with BasicFoo, StandardFoo, GenericFoo, IFoo and FooImpl being ones I rejected. But there are lots of other common naming patterns used in Java.

The purpose of these naming patterns is to increase the readability of the codebase as a whole. This is very similar in concept to other coding standards like "no tabs" or "braces at end of line". Its also part of my belief in doing the best we can when writing long-lived code to help those in the future who will read, use and maintain the code.

So, here are some additional naming patterns:

Foo - The basic named concept should always have the best name (for this blog, it could be a class or interface).

FooUtils - A set of utilities that support usage of Foo. This is particularly common with interfaces, but does not have to be limited to them. In some cases, particularly in a hierarchy or group of classes, it can make sense to separate out common utilities, leaving just static factory methods on the main class. I'll note that a Javadoc annotation to mark a method as a factory is long overdue.

FooBuilder - An implementation of the builder pattern that is used to create an object in a fluent manner. This is especially useful for large, complex objects, particularly when the end result is immutable. Sadly in Java, a builder is quite a lot of effort to write well.

FooManager - I prefer manager to FooFactory because I generally find that a factory does more than just creation, for example registering a lookup. However, I tend to avoid explicit managers/factories. For classes, I would prefer to see the manager/factory as static methods on the class itself, so this would most often be used for interfaces. However, I tend to find that most of my interfaces either require the user to pick the concrete class or are injected by IoC.

DelegatingFoo - A class that exists as an abstract base to wrap a Foo and add some behaviour by delegation. Most of the time I would say that it is not worth creating the decorating abstract base class, and only having the concrete version as it makes each class simpler to understand in isolation.

FooProxy - A class that stands in for the complete set of data as part of a lazy loading strategy. I believe that this is sometimes used for the delegation case, but I find that confusing.

Fooable - This would be used for an interface where the implementations are in some way related to Foo. An example would be Identifier and Identifiable. In this case, the -able suffix implies that the implementing class "can be identified". In code terms that usually means a single getFoo() or toFoo() method.

Note that I haven't covered every last prefix/suffix - there are many more. Sometimes a computer name list or thesaurus is useful.

Some other possibilities are:

FooUtil - I find FooUtils to be a much nicer name.

Foos - I use FooUtils, as I would see the plural suffix as a JDK style, as in Collections.

FooFactory - As discussed above I find when I do need a separate factory it is usually more of a FooManager than just a factory.

ForwardingFoo - An alternative to DelegatingFoo notably used by Google Guava, mostly a matter of preference as to which to choose, but be consistent.

DecoratingFoo - Another alternative to DelegatingFoo.

I should just note that both this and the last post are quite Java focussed. Other languages have different "styles" of coding that naturally result in different naming patterns.

I should also note that most of the time class names should express what makes them distinctive. However, it is sometimes more useful to have a naming convention as it aids learning of the system.


Summary

Again, there are no cast-iron certainties in class naming or coding standards in general. However, it is useful to have a common starting point at least within one project.

Opinions welcome as always.

Wednesday, 17 August 2011

Implementations of interfaces - prefixes and suffixes

I recently asked a question on Twitter about how to use some common classes name prefixes/suffixes to go with an interface to see if there are best practices out there.

Common Java prefixes and suffixes

The design pattern of an interface together with one or more implementations is not always considered favourably these days. However, in certain circumstances it can be the right choice. One of these cases is the OpenGamma platform, my day job.

At OpenGamma, we are building a platform that will be implemented by different teams in different companies. Those implementations will typically not be under our control and frequently will exist already. Thus, the platform must impose the minimum design penalty for integration, which clearly implies an interface, as an abstract class imposes more constraints.

Within OpenGamma it is also necessary to provide certain standard classes that implement the interfaces. This might be for examples, or other functionality in a different part of the stack. Naming these classes that implement the standard interfaces was how I started the Twitter conversation.

As a result of the Twitter thoughts, other discussions and my own thoughts, this is where I got to:

  • Foo - The interface ultimately defines the concept, so it should have the best name.
  • AbstractFoo - An abstract implementation intended to be used as the base of a hierarchy of classes.
  • BaseFoo - An implementation intended to be used as the base of a hierarchy of classes, where the base class could be used on its own if necessary.
  • DefaultFoo - A "default" implementation that would be appropriate for the majority of typical use cases.
  • SimpleFoo - A "simple" implementation with no unexpected functionality, perhaps as an example or as a mock. A simple POJO would be a good "simple" implementation.
  • {Descriptive}Foo - Other implementations should describe what makes them unique.

Note that some of these "best practices" can be combined. For example, a Foo interface might have a BaseFoo implementation intended for subclassing with DefaultFoo as the standard and most commonly used one.

Some other suggestions were:

  • BasicFoo - This appears to be semantically equivalent to SimpleFoo, so its mostly a preference issue.
  • interface IFoo, class Foo - This naming convention is seen in some places, but is not generally thought of as good Java style.
  • FooImpl - This naming convention has some supporters, but generally seems clumsy.
  • StandardFoo - Similar to DefaultFoo, but less widely used
  • GenericFoo - Never seen this one myself

Two other thoughts on FooImpl. Firstly, it does group well in auto-complete (Foo ctrl+space). For method names I think that is useful, but it doesn't convince me here. Secondly, it was suggest that FooImpl should be used for IoC dependencies. This seems to me to be an indirect tie of application to IoC container, which I dislike.

Summary

There are no cast-iron definitions here, however those in the first list are probably a good place to start from when creating your own "best practices" or "coding standards".

Opinions welcome as always.

Tuesday, 16 August 2011

Blog moved from JRoller

This is the first new post at this blog's new location - blog.joda.org.

The new blog is backed by Blogger which has a much better setup than JRoller. Hopefully readers will find commenting less stressful from now on.

I have also managed to import the old posts and comments, based on previous migration experiences. I would write up my experiences, but I don't think there are many more people left on JRoller looking to migrate. Contact me scolebourne|joda|org if you want to know how I made the move.

At Blogger, I did have some initial problems with line endings. However, I found that this could be fixed as follows:

  • Set "Convert line breaks" to "No" in the Settings/Formatting tab.
  • Set "Edit HTML Line Breaks" to "Press Enter for line breaks" in the Post options (at the bottom of editing a post).
  • Set "Compose Settings" to "Show HTML literally" in the Post options (at the bottom of editing a post).

If you have any major issues with the formatting/colours in your browser, please let me know in the comments.

Monday, 1 August 2011

Joda-Time v2.0

Joda-Time version 2.0 is now released! Download. Release notes.

Firstly, Joda-Time 2.0 is NOT a re-write of Joda-Time. The major version number change signifies that there are some incompatibilities. However, these are as minor as I could make them.

A few methods on Chronology that were deprecated for years have been removed, but most other deprecated and classes methods remain as the benefits of removing them were lower than the damage caused.

The library has moved to JDK 1.5 compatibility, adding generics. Sadly, adding generics to Comparable in some cases caused issues for implementations. The choice was to aim for binary incompatibility at the expense of source incompatibility if the ReadableInstant or ReadableDuration interfaces were implemented directly. If you didn't implement these, or extended the supplied abstract class then you should have no problems. Similarly, ReadablePartial had Comparable added, but if you didn't implement it, or extended the supplied abstract class then again you should have no problems.

In summary, I hope there are no significant binary incompatibilities. If you do find a binary incompatibility that I didn't, I'd like to know, particularly if it affects another open source project. If it is in the next week or so, then perhaps the incompatibilty can be fixed and "jar hell" avoided.

There are a number of semantic changes as well in the corner cases. Again see the release notes.

  • Parsing a month-day without a year now selects year 2000 rather than 1970 (so the 29th of February can be parsed)
  • Edge cases with a week-based-year and a month are handled better
  • Methods that handle daylight savings time (DST) are more consistent, retaining the offset wherever possible during calculations or consistently choosing summer time if not
  • Some short time zone IDs have been changed
  • DateTimeZone factory taking an ID is now case sensitive

And of course there are some enhancements:

  • Static factories now() and parse() added to the main date-time classes
  • New classes YearMonth and MonthDay
  • API added to plugin to the Joda-Time clock
  • Period formatting in multiple langauges
  • Parsing of LocalDate/LocalTime/LocalDateTime directly supported (much better than previously)
  • Parsing of time-zone IDs and some support for parsing time-zone names (via the builder)
  • Better handling of 'Z' when parsing to mean +00:00
  • Reliable way to get the start of day for a DateTime - withStartOfDay()
  • Convenient way to handle DST, DateTime.withEarlierOffsetAtOverlap() .withLaterOffsetAtOverlap()
  • Provide direct conversion from LocalDate and LocalDateTime to java.util.Date
  • More constructors and methods for Duration
  • More constructors for DateTime
  • Support JDK 1.6 pluggable resource providers
  • More compatible with the Java Memory Model in JDK 1.5 and higher
  • Added support for Joda-Convert without adding a dependency

Hopefully, you can just drop Joda-Time into your application and you will not notice any change. However, you should definitely read the release notes first.

Finally, as I'm sure someone will ask, this doesn't affect ThreeTen/JSR-310. This release was necessary to finally release a lot of bugs and enhancements in Joda-Time.

PS. As a bonus, there is a re-release of the JSP tags library, as apparantly it wasn't in maven central correctly up until now.

PPS. For Hibernate 4.0 support, please use the usertype project.