Open minds leads to freedom

Communicating my thoughts on software development

Singleton in Java with Enum types

Posted by rnaufal on 7th September 2010

Java 1.5 introduced the concept of Enum types. They are type-safe constants, which implements equals(), hashCode() and cannot be extended. Each constant can have attributes and override an abstract method created on each Enum class.

Although Singletons are not encouraged, the best way to create it is using Enum types. Here is an example:

public enum Singleton {
    INSTANCE;

    public void sayHello() {
	   System.out.println("Hello World!");
    }
}

And then you call it this way:

Singleton.INSTANCE.sayHello();

Using Enums to create Singletons brings the serialization mechanism already bundled in the Enum type. This technique is described on the Effective Java Second Edition book by Joshua Block.

Tags: , , , , ,
Posted in Uncategorized | 1 Comment »

Joshua Block on How to Design a Good API & Why it Matters

Posted by rnaufal on 10th January 2009

In this talk (recorded at Javapolis), Joshua Block presents guidelines about how to design good APIs. I highlighted what i think are the most important parts of the talk:

  • Functionality should be easy to explain: If it’s hard to name, that’s generally a bad sign
  • Good names drive development
  • Be amenable to splitting and merging modules (If names are nasty, take a step back and make things easy to describe)
  • When in doubt, leave it out
  • You can always add, but tou cannot take it out
  • Implementation Should Not Impact API
  • Always omit implementation details
  • Inhibit freedom to change implementation
  • Don’t let implementation details “leak” into API (For example: Serializable, hash functions)
  • Minimize Accessibility of Everything (This maximizes information hiding)
  • Public classes should’nt have public fields
  • API should be easy to learn, read and use: It should be consistent, it’s a little language
  • Documentation matters (Example: Method contract between it and it’s clients)
  • Think of preconditions, postconditions, side-effects
  • Don’t Transliterate API’s
    • What’s the problem it solves?
    • What shoud abstractions did it use?
  • Don’t Make the Client Do Anything The Module Could do
  • Throw Exceptions to Indicate Exceptional Conditions

When you see the talk, post your comments here.

Tags: , , , ,
Posted in Uncategorized | 1 Comment »