Item 14: In public classes, use accessor methods, not public fields

class Point {
    public double x;
    public double y;
}

So, do you see what’s wrong with this code? Well, not much actually.

Item 14 in effective java is pretty simple to understand. In fact its just a by product of using common sense while writing code.

Problem with the above given class is that –

  1. The class is just a bunch of properties.
  2. The class simply fails to take advantage of the encapsulation features.

How can the problem be solved?

  1. Adding accessor methods in the given class, after changing the visibility of the fields to private.
  2. Also, add setters in case the class is supposed to be mutable.

So, Item 14 is as simple as this. But, please don’t be alarmed by the simplicity. The item is just a caution against using classes with public fields. Although I feel that it is a good idea to keep fields public for inner classes and those classes which are package-private(default scoped). Its the public classes you need to watch out for.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: