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.




REALbasic Cross-Platform Application Development
REALbasic Cross-Platform Application Development
ISBN: 0672328135
EAN: 2147483647
Year: 2004
Pages: 149

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net