Sunday, September 07, 2014

EJ-40 Design Method Signatures Carefully

Ref: Effective Java by Joshua Bloch

Considering following disciplines will help make your API easier to learn and use and less prone to errors.
  • Choose method names carefully.
  • Don't go overboard in providing convenience methods: Every method should "pull its weight." Too many methods make a class difficult to learn, use, document, test and maintain.
  • Avoid long parameter list: Aim for four parameters or fewer. Long sequences of identically typed parameters are especially harmful.
  • Prefer two-element enum types to boolean parameters: It makes your code easier to read and to write.
public enum TemperatureScale {FAHRENHEIT, CELCIUS }

Not only does Thermometer.newInstance(TemperatureScale.CELCIUS) make a lot more sence than Thermometer.newInstance(true) but you can add KELVIN to in a future release without adding a new static factory method.

No comments: