Top Posts of 2013: 10 Subtle Best Practices when Coding Java
This list here contains less common situations involving API / SPI design that many Java articles do not cover.
Join the DZone community and get the full member experience.
Join For Freethis is a list of 10 best practices that are more subtle than your average josh bloch effective java rule. while josh bloch’s list is very easy to learn and concerns everyday situations, this list here contains less common situations involving api / spi design that may have a big effect nontheless.
i have encountered these things while writing and maintaining jooq , an internal dsl modelling sql in java. being an internal dsl, jooq challenges java compilers and generics to the max, combining generics, varargs and overloading in a way that josh bloch probably wouldn’t recommend for the “average api”.
let me share with you 10 subtle best practices when coding java:
1. remember c++ destructors
remember c++ destructors ? no? then you might be lucky as you never had to debug through any code leaving memory leaks due to allocated memory not having been freed after an object was removed. thanks sun/oracle for implementing garbage collection!
but nonetheless, destructors have an interesting trait to them. it often makes sense to free memory in the inverse order of allocation. keep this in mind in java as well, when you’re operating with destructor-like semantics:
- when using @before and @after junit annotations
- when allocating, freeing jdbc resources
- when calling super methods
there are various other use cases. here’s a concrete example showing how you might implement some event listener spi:
@override
public void beforeevent(eventcontext e) {
super.beforeevent(e);
// super code before my code
}
@override
public void afterevent(eventcontext e) {
// super code after my code
super.afterevent(e);
}
another good example showing why this can be important is the infamous dining philosophers problem . more info about the dining philosophers can be seen in this awesome post:
http://adit.io/posts/2013-05-11-the-dining-philosophers-problem-with-ron-swanson.html
the rule : whenever you implement logic using before/after, allocate/free, take/return semantics, think about whether the after/free/return operation should perform stuff in the inverse order.
2. don’t trust your early spi evolution judgement
providing an spi to your consumers is an easy way to allow them to inject custom behaviour into your library / code. beware, though, that your spi evolution judgement may trick you into thinking that you’re (not) going to need that additional parameter . true, no functionality should be added early . but once you’ve published your spi and once you’ve decided following semantic versioning , you’ll really regret having added a silly, one-argument method to your spi when you realise that you might need another argument in some cases:
interface eventlistener {
// bad
void message(string message);
}
what if you also need a message id and a message source? api evolution will prevent you from adding that parameter easily, to the above type. granted, with java 8, you could add a defender method, to “defend” you bad early design decision:
interface eventlistener {
// bad
default void message(string message) {
message(message, null, null);
}
// better?
void message(
string message,
integer id,
messagesource source
);
}
note, unfortunately, the defender method cannot be made final .
but much better than polluting your spi with dozens of methods, use a context object (or argument object) just for this purpose.
interface messagecontext {
string message();
integer id();
messagesource source();
}
interface eventlistener {
// awesome!
void message(messagecontext context);
}
you can evolve the messagecontext api much more easily than the eventlistener spi as fewer users will have implemented it.
the rule : whenever you specify an spi, consider using context / parameter objects instead of writing methods with a fixed amount of parameters.
remark : it is often a good idea to also communicate results through a dedicated messageresult type, which can be constructed through a builder api. this will add even more spi evolution flexibility to your spi.
3. avoid returning anonymous, local, or inner classes
swing programmers probably have a couple of keyboard shortcuts to generate the code for their hundreds of anonymous classes. in many cases, creating them is nice as you can locally adhere to an interface, without going through the “hassle” of thinking about a full spi subtype lifecycle.
but you should not use anonymous, local, or inner classes too often for a simple reason: they keep a reference to the outer instance. and they will drag that outer instance to wherevery they go, e.g. to some scope outside of your local class if you’re not careful. this can be a major source for memory leaks, as your whole object graph will suddenly entangle in subtle ways.
the rule : whenever you write an anonymous, local or inner class, check if you can make it static or even a regular top-level class. avoid returning anonymous, local or inner class instances from methods to the outside scope.
remark : there has been some clever practice around double-curly braces for simple object instantiation:
new hashmap<string, string>() {{
put("1", "a");
put("2", "b");
}}
this leverages java’s instance initializer as specified by the jls §8.6 . looks nice (maybe a bit weird), but is really a bad idea. what would otherwise be a completely independent hashmap instance now keeps a reference to the outer instance, whatever that just happens to be. besides, you’ll create an additional class for the class loader to manage.
4. start writing sams now!
java 8 is knocking on the door. and with java 8 come lambdas , whether you like them or not. your api consumers may like them, though, and you better make sure that they can make use of them as often as possible. hence, unless your api accepts simple “scalar” types such as int
, long
, string
, date
, let your api accept sams as often as possible.
what’s a sam? a sam is a single abstract method [type]. also known as a functional interface , soon to be annotated with the @functionalinterface annotation . this goes well with rule number 2, where eventlistener is in fact a sam. the best sams are those with single arguments, as they will further simplify writing of a lambda. imagine writing
listeners.add(c -> system.out.println(c.message()));
instead of
listeners.add(new eventlistener() {
@override
public void message(messagecontext c) {
system.out.println(c.message()));
}
});
imagine xml processing through joox , which features a couple of sams:
$(document)
// find elements with an id
.find(c -> $(c).id() != null)
// find their child elements
.children(c -> $(c).tag().equals("order"))
// print all matches
.each(c -> system.out.println($(c)))
the rule : be nice with your api consumers and write sams / functional interfaces already now .
remarks : a couple of interesting blog posts about java 8 lambdas and improved collections api can be seen here:
- http://blog.informatech.cr/2013/04/10/java-optional-objects/
- http://blog.informatech.cr/2013/03/25/java-streams-api-preview/
- http://blog.informatech.cr/2013/03/24/java-streams-preview-vs-net-linq/
- http://blog.informatech.cr/2013/03/11/java-infinite-streams/
5. avoid returning null from api methods
i’ve blogged about java’s nulls once or twice. i’ve also blogged about java 8′s introduction of optional . these are interesting topics both from an academic and from a practical point of view.
while nulls and nullpointerexceptions will probably stay a major pain in java for a while, you can still design your api in a way that users will not run into any issues. try to avoid returning null from api methods whenever possible. your api consumers should be able to chain methods whenever applicable:
initialise(someargument).calculate(data).dispatch();
in the above snippet, none of the methods should ever return null. in fact, using null’s semantics (the absence of a value) should be rather exceptional in general. in libraries like jquery (or joox , a java port thereof), nulls are completely avoided as you’re always operating on iterable objects . whether you match something or not is irrelevant to the next method call.
nulls often arise also because of lazy initialisation. in many cases, lazy initialisation can be avoided too, without any significant performance impact. in fact, lazy initialisation should be used carefully, only. if large data structures are involved.
the rule : avoid returning nulls from methods whenever possible. use null only for the “uninitialised” or “absent” semantics.
6. never return null arrays or lists from api methods
while there are some cases when returning nulls from methods is ok, there is absolutely no use case of returning null arrays or null collections! let’s consider the hideous java.io.file.list()
method. it returns:
an array of strings naming the files and directories in the directory denoted by this abstract pathname. the array will be empty if the directory is empty. returns null if this abstract pathname does not denote a directory, or if an i/o error occurs.
hence, the correct way to deal with this method is
file directory = // ...
if (directory.isdirectory()) {
string[] list = directory.list();
if (list != null) {
for (string file : list) {
// ...
}
}
}
was that null check really necessary? most i/o operations produce ioexceptions, but this one returns null. null cannot hold any error message indicating why the i/o error occurred. so this is wrong in three ways:
- null does not help in finding the error
- null does not allow to distinguish i/o errors from the file instance not being a directory
- everyone will keep forgetting about null, here
in collection contexts, the notion of “absence” is best implemented by empty arrays or collections. having an “absent” array or collection is hardly ever useful, except again, for lazy initialisation.
the rule : arrays or collections should never be null.
7. avoid state, be functional
what’s nice about http is the fact that it is stateless. all relevant state is transferred in each request and in each response. this is essential to the naming of rest: representational state transfer . this is awesome when done in java as well. think of it in terms of rule number 2 when methods receive stateful parameter objects. things can be so much simpler if state is transferred in such objects, rather than manipulated from the outside. take jdbc, for instance. the following example fetches a cursor from a stored procedure:
callablestatement s =
connection.preparecall("{ ? = ... }");
// verbose manipulation of statement state:
s.registeroutparameter(1, cursor);
s.setstring(2, "abc");
s.execute();
resultset rs = s.getobject(1);
// verbose manipulation of result set state:
rs.next();
rs.next();
these are the things that make jdbc such an awkward api to deal with. each object is incredibly stateful and hard to manipulate. concretely, there are two major issues:
- it is very hard to correctly deal with stateful apis in multi-threaded environments
- it is very hard to make stateful resources globally available, as the state is not documented
theatrical poster for forrest gump, copyright © 1994 by paramount pictures . all rights reserved. it is believed that the above usage fulfils what is known as fair use
the rule : implement more of a functional style. pass state through method arguments. manipulate less object state.
8. short-circuit equals()
this is a low-hanging fruit. in large object graphs, you can gain significantly in terms of performance, if all your objects’ equals()
methods dirt-cheaply compare for identity first:
@override
public boolean equals(object other) {
if (this == other) return true;
// rest of equality logic...
}
note, other short-circuit checks may involve null checks, which should be there as well:
@override
public boolean equals(object other) {
if (this == other) return true;
if (other == null) return false;
// rest of equality logic...
}
the rule : short-circuit all your equals() methods to gain performance.
9. try to make methods final by default
some will disagree on this, as making things final by default is quite the opposite of what java developers are used to. but if you’re in full control of all source code, there’s absolutely nothing wrong with making methods final by default, because:
- if you do need to override a method (do you really?), you can still remove the final keyword
- you will never accidentally override any method anymore
this specifically applies for static methods, where “overriding” (actually, shadowing) hardly ever makes sense. i’ve come across a very bad example of shadowing static methods in apache tika , recently. consider:
tikainputstream extends taggedinputstream and shadows its static get() method with quite a different implementation.
unlike regular methods, static methods don’t override each other, as the call-site binds a static method invocation at compile-time. if you’re unlucky, you might just get the wrong method accidentally.
the rule : if you’re in full control of your api, try making as many methods as possible final by default.
10. avoid the method(t…) signature
there’s nothing wrong with the occasional “accept-all” varargs method that accepts an object...
argument:
void acceptall(object... all);
writing such a method brings a little javascript feeling to the java ecosystem. of course, you probably want to restrict the actual type to something more confined in a real-world situation, e.g. string...
. and because you don’t want to confine too much, you might think it is a good idea to replace object by a generic t:
void acceptall(t... all);
but it’s not. t can always be inferred to object. in fact, you might as well just not use generics with the above methods. more importantly, you may think that you can overload the above method, but you cannot:
void acceptall(t... all);
void acceptall(string message, t... all);
this looks as though you could optionally pass a string message to the method. but what happens to this call here?
acceptall("message", 123, "abc");
the compiler will infer <? extends serializable & comparable<?>>
for t
, which makes the call ambiguous!
so, whenever you have an “accept-all” signature (even if it is generic), you will never again be able to typesafely overload it. api consumers may just be lucky enough to “accidentally” have the compiler chose the “right” most specific method. but they may as well be tricked into using the “accept-all” method or they may not be able to call any method at all.
the rule : avoid “accept-all” signatures if you can. and if you cannot, never overload such a method.
conclusion
java is a beast. unlike other, fancier languages, it has evolved slowly to what it is today. and that’s probably a good thing, because already at the speed of development of java, there are hundreds of caveats, which can only be mastered through years of experience.
stay tuned for more top 10 lists on the subject!
Published at DZone with permission of Lukas Eder. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments