Monday, March 31, 2008

Objects Need Access Modifiers

OOP is made possible by using this simple concept of a class as a cohesive aggregate of characteristics and behaviors, this is exactly what objects are in PHP 4—but one of the most important features of any OO language is the use of access modifiers. Access modifiers refine the object model by controlling how an object is used or reused. Simply put, access modifiers provide guidance about what you can and cannot do with an object. To get a sense of what this means, let’s use an example from procedural programming.

Let’s define a subroutine as a function that is never invoked directly but that is only called by other functions. Now suppose you are a procedural programmer with a library of functions and subroutines that is used by several other programmers. The ability to flag subroutines as secondary would be helpful in instructing others how to use your library, but the only way to do this is through documentation. However, in OOP, access modifiers not only indicate the primacy of certain functions over others, they enforce it programmatically. They implement language constraints to ensure that “subroutines” are never called directly. Properly constructed classes are self-documenting and self-regulating.

In the situation just described, the need to document a code library arises because it is used in a collaborative environment, the exact same circumstance accounts for the existence of access modifiers. One of the assumptions of OOP is that it is conducted within an interactive context with access modifiers defining the ways of interacting. This is one of the important differences between OOP and procedural programming. Access modifiers provide the rules for using a class and this syntactically defined “etiquette” is commonly referred to as an interface. By providing an interface, there is less need to rely on documentation and on user programmers “doing the right thing.”

Documenting code libraries is important because libraries get reusedl, access modifiers matter for exactly the same reason-they facilitate reuse.

No comments: