97 Things Every Programmer Should Know

(Chris Devlin) #1

(^64) 97 Things Every Programmer Should Know


Encapsulate Behavior, Not Just State ...................


Einar Landre


iNYSTEMS S THEORY, containment is one of the most useful constructs when
dealing with large and complex system structures. In the software industry,
the value of containment or encapsulation is well understood. Containment
is supported by programming language constructs such as subroutines and
functions, modules and packages, classes, and so on.


Modules and packages address the larger-scale needs for encapsulation, while
classes, subroutines, and functions address the more fine-grained aspects of
the matter. Over the years, I have discovered that classes seem to be one of the
hardest encapsulation constructs for developers to get right. It’s not uncom-
mon to find a class with a single 3,000-line main method, or a class with only
set and get methods for its primitive attributes. These examples demonstrate
that the developers involved have not fully understood object-oriented think-
ing, having failed to take advantage of the power of objects as modeling con-
structs. For developers familiar with the terms POJO (Plain Old Java Object)
and POCO (Plain Old C# Object or Plain Old CLR Object), this was the intent
in going back to the basics of OO as a modeling paradigm—the objects are
plain and simple, but not dumb.


An object encapsulates both state and behavior, where the behavior is defined
by the actual state. Consider a door object. It has four states: closed, open,
closing, opening. It provides two operations: open and close. Depending on

Free download pdf