- 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
An Object-Oriented Implementation Using C# .NET (The Future Is Now)
Creating accessor methods in C# and Java would look very similar to the C++ code. Not surprising, since C# and Java are both descendants of C++.
The concepts of accessor methods I've presented to this point are common to all object-oriented languages. At the beginning of this article, I pointed out that such concepts are constantly evolving. As languages move into new territory, the new features are not initially standardized—at least until the industry adopts the new features.
To illustrate this point, let's examine Microsoft's .NET implementation of C#, where accessor methods have been incorporated directly into the .NET architecture. This is a very good example of how object-oriented languages have built quality design practices directly into their compilers. In many ways, the .NET accessor methods are actually part of the class properties. Take a look at Listing 5 to see how C# accomplishes this result.
Listing 5C# implementation.
// CSLicense01.cs : Defines the entry point for the console application. // using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSLicense01 { class Program { static void Main(string[] args) { License joe = new License { Age = 0 }; joe.Age = 16; Console.WriteLine("age = " + joe.Age); Console.WriteLine("Hit Any Key To Continue"); Console.ReadLine(); //Pause return; } } class License { private int age; public int Age { get { return age; } set { age = value; } } public License() { age = 0; } }; }
The code in Listing 5 is simply intended to whet your appetite; we won't go into any further detail here. My point in showing the code is to demonstrate that you must be cognizant of ever-changing coding practices. As I mentioned earlier, this industry is moving in many new directions regarding accessor methods and even encapsulation itself. The entire concept of encapsulation (considered sacrosanct for years) is being revisited.
Consider the following line of code from the main() entry point in Listing 5:
joe.Age = 16;
For many years, we've taught that this type of syntax is bad, since it implies that a programmer can directly update the value of a variable. Basically, using an equal sign to set a variable appears to break encapsulation. Yet this is the approach the .NET architecture takes, and in fact it doesn't really break encapsulation—it just initially appears that way to an untrained eye.
Even the use of global variables (which have been anathema for years) is being reconsidered. That's what's great about being a programmer: The technology is always changing. I hope that this article will encourage you to explore these new issues.