- Introduction
- A Basic C Program Using Global Variables
- A Basic C Program Using a Function to Set Data Values
- An Object-Oriented Implementation Using C++
- What's the Point of Accessor Methods?
- An Object-Oriented Implementation Using C# .NET (The Future Is Now)
- Conclusion
A Basic C Program Using a Function to Set Data Values
An early attempt to address this code-quality issue created a single function to be called whenever a variable like age was set. Take a look at the code in Listing 2. This function is a major step forward because, in theory, age can be set in only a single location. Debugging is easier since you only need to look in one place—at least initially. Programmers are instructed that to modify age they must call the setAge() function.
Listing 2C program with accessor method.
// License02.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> // Function Prototypes void driversLicense(); int setAge(int); // Global Variable int age = 0; int main() { driversLicense(); printf("age = %d\n", age); system("pause"); return 0; } // driversLicense.c // void driversLicense() { setAge(16); } // setAge.c // int setAge(int a) { age = a; return age; }
The fundamental problem with this approach is that it works on the honor system—in short, compliance is voluntary. In many organizations, these directives are published in internal coding guidelines and procedures. Enforcement comes by way of code reviews and management oversight. Unfortunately, a rogue programmer can ignore the rules and still access age directly.
The use of the function setAge() is an early form of what would come to be known as an accessor method (or mutator). This concept was deemed to be so important that languages were eventually designed to eliminate the voluntary adherence and make them mandatory (as part of a class). Modern OO languages have accessors built in, while C++ provides the mechanism for creating accessor methods even though they're not enforced.