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

(1/2) > >>

mnemonic:
How do you decide on whether an attribute of a class is public or has an accessor method?

For example, a Cody class could be written in two ways (I'm not including variables that you create / modify with get / set methods):


--- Code: C# ---class Cody {        public string colour = white;        public int age = 10;}

--- Code: C# ---class Cody {        private string colour = white;        private int age = 10;         public void setColour(string colourIn) {                this.colour = colourIn;        }         public string getColour() {                return this.colour;        }         public void setAge(int ageIn) {                this.age = ageIn;        }         public int getAge() {                return this.age;        }}
Do you just create accessor methods (is that the correct term?) for those attributes that are likely to be complex or may need transformation, or do you create them for everything and leave nothing public?

mouser:
Modern programming practices tell you to always use accessors when manipulating or retrieving variables from outside of the class itself.
In general, a class should not allow anyone to mess with its insides directly.

This makes good common sense as well -- an object/class should be able to implement whatever gatekeeper or background functions that it wants to, with complete confidence that it knows when people are reading its values or changing them, and has the opportunity to intercept such requests if it needs to.

The only exception to this would be if you were working with code that absolutely had to be as fast as possible and you couldn't be sure the compiler was going to optimize the accessor access code.

mnemonic:
Ok, so you never use public attributes in classes unless speed is absolutely vital?

mouser:
Ok, so you never use public attributes in classes unless speed is absolutely vital?
--- End quote ---

if your question is:

so one never uses public attributes in classes unless speed is absolutely vital?
--- End quote ---
then the answer is: correct.

if your question is:

so you never use public attributes in classes unless speed is absolutely vital?
--- End quote ---
then the answer is: no comment.

 ;)

mnemonic:
Don't worry, what happens in Donationcoder stays in Donationcoder  ;)

Thanks for the answers  :Thmbsup:

Navigation

[0] Message Index

[#] Next page

Go to full version