ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

Accessor methods vs public variables

<< < (2/2)

f0dder:
Ok, so you never use public attributes in classes unless speed is absolutely vital?
-mnemonic (June 13, 2009, 04:55 AM)
--- End quote ---
You never use publicly accessible attributes, period. And forget the speed argument, compilers are pretty decent at inlining the calls so they end up with exactly the same machine code as direct access.

Heck, you should even use accessor methods in the class methods as well... for simple stuff it doesn't really matter, but for more complex code it allows you to introduce caching instead of re-computation etc.

mnemonic:
Heck, you should even use accessor methods in the class methods as well... for simple stuff it doesn't really matter, but for more complex code it allows you to introduce caching instead of re-computation etc.
-f0dder (June 13, 2009, 08:51 AM)
--- End quote ---

Can you explain what you mean by this? 

MilesAhead:
Other than the "rules" arguments, there's the benefit that you can change the implementation without breaking code that's the client of the class.  IOW, if you use a Property to get a bitmap, the client won't break if you later decide to load the bitmap from a file instead of a resource that's compiled in.  Gives you some flexibility.

Plus the benefit of being able to "screen" the values that would modify the variable. A simple example might be a number used as a divisor.  If the value used in the attempted modification is zero, some other action rather than CPU trap is advisable.

Navigation

[0] Message Index

[*] Previous page

Go to full version