Tuesday, 19 November 2013

Encapsulation



Sometimes as a programmer, you don't want your fields and methods modified outside of their own class. Perhaps the best way to solve this, is through information hiding as we discussed in lecture, also known as encapsulation.

In Java, as I'm used to, this is done by declaring your fields with the private keyword. This prevents it from being seen and accessed from outside of the class. In Python we can do something similar by adding an underscore before the name, for example _size will protect it to some extent, however it is only protected by convention.

In order to gain access to these now private variables, we must write what are known as accessor and mutator methods. Accessors returning the value, and mutators changing the value.

The fun and interesting part of all this? Gaining access to these variables without accessors or mutators. There are ways of doing this, my personal favourite is with a technique known as introspection, or reflection.

Reflection allows you to examine and modify an object at runtime, many languages support this. Java for example has a reflection library available for importing and using. Python, as an interpreted language also supports reflection.

The powerful thing about reflection is that it allows you to examine classes, methods, interfaces, and fields at runtime without knowing their names before compilation. It also allows you to instantiate objects and invoke methods without necessarily knowing the names.

So, encapsulation has varying degrees of usefulness, all depending on who is using your code. It can stop many from modifying classes in unintended ways, but to the more knowledgeable programmer, there are always ways around encapsulation.

No comments:

Post a Comment