Thursday, April 30, 2015

Rethink OO programming: encapsulation

Encapsulation is a important feature in OO programming.  What is encapsulation?  Here is explanation in wiki.

One important feature is that encapsulation can hide some data members and function members. The The purpose of hiding is to protect object integrity so caller will not accidentally modify the object state and corrupt the object. It is not a mechanism to protect secret information. I highlight the word "accidentally".   Hiding does not prevent you from access these hidden members intentionally. In java private members can be accessed or modified by reflection.  They can be modified  or replaced through instrument. This is how many mock frameworks works.   This principle sounds good, but there are other better ways to do it.

Here are one piece of code I have in one of my project:
static Field field;
static {
try {
field = DynamicClassWriter.class.getDeclaredField("parentClass");
field.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}


Do you see the problem? The class designer never thought other developers need accessing it. This is one side effect of encapsulation: over-hide.  Many object members are hidden without any thought. It become very difficult for library user when there is time library user really needs modifying the data member.

We could do this: prefix any object member we want to hide with "__". When developer saw "__" prefix, it is like a warning "use it as your own risk". IDE can treat any member with "__" prefix as it treats private member right now.  Compiler can also give a warning if "__" members are accessed externally.  At the same time, developer can access "__" member at his own risk.  Isn't this a better approach?

If you are reading this post, add your comment. I'd like to know what you think on this topic.



2 comments:

  1. Computer programming will be a great support from online. this like interesting tips will clear the doubt of experienced person.For a clear writing work on any computer field function just visit here.

    ReplyDelete