|
One of the fundamental principles of object-oriented design is that the object suited for the task should perform that task. In other words, a class should implement the behavior only an object of that particular type is supposed to do. Any other required behavior should be implemented by another class best suited for that job. For example, let’s say that you define a hypothetical Tree class and you wish that it should be searchable. You can have methods to perform a search that tree. However, from an object-oriented perspective, a tree is a tree and it should only implement behavior a tree is supposed to have. It is not tree’s responsibility to implement the search algorithm. Imagine, however, that the search capability is required from the tree. How will you define the ability to search without implementing it in Tree class?
One of the solutions is to declare an inner class, say for
instance, BinarySearch. It will implement a search algorithm
inside the Tree class. Thus, the search functionality is taken out of from Tree
where it doesn't belong in the first place. Besides code clarity, there are
certain other advantages of decoupling the search algorithm from the Tree
class. The search algorithm is encapsulated in a class. Therefore, it
can be changed in future say from binary search to sequential-search, by simply
adding/replacing the inner class. An obvious question arises then why not to
declare a top-level class for implementing search? The reason is simple.
Searching within a Tree often requires knowledge of the tree's
internal data structures. Since inner class has access to all [§§§§§§]members and methods of the
enclosing class, it will be easier to implement the search algorithm.