Chapter 8. Good Citizenship

image with no caption

Good citizenship may seem like an odd topic in a discussion about how to improve code, but good citizenship refers to objects that are both aware of their own state and considerate of the state of others around them. Although this may seem simple, developers violate this principle all the time by coding on autopilot. This chapter looks at several different violators of good citizenship and ways to become more responsible citizens.

Breaking Encapsulation

One of the core tenets of object-oriented programming is encapsulation: protecting internal fields from outside meddling. Yet, I’ve seen lots of developers void the intent of encapsulation because they code on autopilot.

Here is a scenario. You create a new class, you create a bunch of private member variables for it, you tell the IDE to spit out properties (either get/set methods in Java or properties in C#), and then you engage your brain. Creating public properties for every private field completely destroys the intent of the property mechanism. You might as well make all the member variables public because the properties aren’t helping you at all (and, in fact, they are just making your code more dense for no good reason).

For example, let’s say you have a Customer class that has several address fields (such as the typical addressLine, city, state, zip). If you create mutating properties for each of these ...

Get The Productive Programmer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.