Monday, March 30, 2015

Why you should control Visibility of Class and Interface in Java

Why you should control Visibility of Class and Interface in Java

One of the important aspect of software development is maintenance, and  it's proven by experience that a software which keeps visibility of its component low is more maintainable than the one who exposes its component more. You won't realize it upfront, but you will miss it badly, while redesigning your application. Since maintaining backward compatibility is must have requirement for many app, you end up patching and repeating same mistakes. You can not do much because lots of other applications are tightly integrated with your class and interfaces. Java has always put encapsulation on priority, provided support of access modifiers from very beginning. It provides three ways to control visibility of any Type e.g. class or interface, by making them public, package-private or private. What happened to protected, can't we use protected with class or interface. No you can't, you can only use two access modifier with types, protected is not a legal modifier for class and interface. Also a top level class (a class whose name is same as of Java source file which contains it)  can be either public or package private (without any access modifier), it can not be private. Only a nested class can be private, public or package-private.  A public class is accessible to everyone, and it is most visible, try to keep only key interfaces public, never let your implementation go public until you think it's complete and mature. On the other hand private Type is least visible, and only nested class or interface can be private in Java. Since it's least visible, you have full control of this class to alter its behaviour with experiences, new technologies, tools and redesign. A clever midway is package-private visibility, which is also default visibility, there is no such keyword as package-private, instead if you don't provide any access modifier than Java assumes that it package-private, and subsequently make it visible only on same package. If your classes and interfaces are shared only between other class in same package, make them package-private. Since client cannot access them, they are also relative safe to change.

No comments:

Post a Comment