Search code examples
encapsulationaccessor

should I use accessors or not?


I have programmed for about 2-3 years now and actually I am developing a game in actionscript atm. I have a character class which have some fields like name, level, experience, damage, defence and so on. right now I have made them protected so the deriving classes can see them, and I have used getters and setters to encapsulate them, so other classes only can see the getters. However in actionscript it seems that you can't make accessors protected, so they must be public. But why should I use accessors at all if anybody can just see them and edit them anyway? Should I just skip the encapsulation and just go with public fields and encapsulate the ones who need to do some other statements when set. For instance if I increase the experience field it should check for a level up while increasing.

I like accessors in c# because they make the coding easier as you can't see private/protected accessors in other classes.

It would be nice to have some more experienced programmers opinion on accessors.


Solution

  • Accessors are a great convention, but I suppose you don't have to follow that.

    The advantage of using them is you have a better API, that is, it's pretty obvious what the IncreaseLevel() function does.

    Also, you have the flexibility to notify other parts of your code. For instance, if every time you increase a level, you want a certain animation to take place, it could take place in the IncreaseLevel() function. All in all, I recommend it.