Design method signatures carefully – effective java

Methods are the core of every software project. The method is the actual verb of the program. It performs things. When writing a method we should consider design it in the standard way.

When we are defining a function/method we should consider the following important things:

  • Choose method names carefully. Names should always obey the standard naming conventions. It should be understandable and consistent with other names in the same package. Java library APIs can be seen as reference.
  • Too many methods make a class difficult to learn, use, document, test, and maintain. This is true for interfaces, where too many methods complicate life for implementors as well as users. Too many convenience (utility) methods for a class or interface are not standard.
  • It is always good to have four parameters or less. So, please avoid a long list of parameters. As we know that the long list of identically typed parameters is harmful.
  • If there is an appropriate interface to define a parameter, we should use it in favor of a class that implements the interface. For example, if a method takes HashMap then we should use type Map instead of HashMap. This will allow us to pass in a Hashtable, a HashMap, a TreeMap, a submap of a TreeMap, or any Map implementation yet to be written.
  • Prefer two-element enum types instead of boolean parameters. It makes the code easier to read and to write.
    public enum TemperatureScale { FAHRENHEIT, CELSIUS }
    // Here Thermometer.newInstance(TemperatureScale.CELSIUS) makes a lot more sense than Thermometer.newInstance(true), we can add KELVIN to TemperatureScale in a future without having to add a new static factory to Thermometer.

How to shortening overly long parameter lists?

  • One is to break the method up into multiple methods, each of which requires only a subset of the parameters.
  • A second technique for shortening long parameter lists is to create helper classes to hold groups of parameters. Typically these helper classes are static member classes. This technique is recommended if a frequently occurring sequence of parameters is seen to represent some distinct entity.
  • A third technique that combines aspects of the first two is to adapt the Builder pattern from object construction to method invocation.