- The Class Hierarchy
- Creating a New Class
- Declaration and Instantiation
- Constructors and Destructors
- Garbage Collection
- Inheritance
- Object Operators
- Adding and Overriding Methods
- Calling the Overridden Method
- Overloading
- Casting
- Oddities
- Encapsulation
- Access Scope: Public, Private, Protected
- Setting Properties with Methods
- Default and Optional Parameters
- Declaring Variables Static and Const
- Revisiting the StringParser Module
- Example: Creating a Properties Class
- Data-Oriented Classes and Visual Basic Data Types
- Advanced Techniques
Setting Properties with Methods
One thing that advocates of pure object-oriented programming often recommend is that you should avoid setting properties directly. Instead, you should use a method (sometimes called getter and setter methods).
It should be noted that there is a slight performance hit from using getter and setter methods because there's an extra step involved. I doubt that it is enough to make a substantial difference in most applications, but if you really want to convince yourself that it's okay to set your properties directly, I suppose that's about as good a reason as I can find.
The rationale behind this is our friend encapsulation. Being able to set properties directly is sort of like walking into the kitchen of the fast-food restaurant and making your own hamburger. It's not really safe to do that. In programming terms it's because the underlying mechanism that establishes the value for the property might change, or a subclass might want to set the value of the property in a different way. You obviously can't override the setting of properties.
Generally speaking, I think it's good advice to avoid directly accessing properties. That doesn't mean that it's bad to do otherwise. It's just that I've found, in practice, that the classes that use getter and setter methods tend to be easier to maintain over time. Your mileage may vary, as they say.