Monday, March 29, 2010

Private Data, Getters, Setters, and the Like

I'm not sure that I'm getting the rationale for class-level private declarations. Given that public "getters" and "setters" can access and even alter private data, what's the use of the private declaration in the first place?

Making data members private allows us to control access to them. First, most (probably) classes don't have setters and getters. Second, setters and getters can be instrumented so that accesses and changes can be tracked, logged, etc. This instrumentation can be useful for debugging. If a private field is getting set to a bad value, one just has to put debug code in the setter rather than hunting down every line that modifies the field.

Another reason, probably at least as important, is for maintenance, upgrades, etc. If I implement a structure with a private array today but later decide it should be a set or a list, I don't have to worry that the change will ripple through client code, breaking the installed base.

Finally, a class interface should have a specification, or a contract. If private data is being modified outside the class, it's not possible for the class to enforce the contract, and debugging the class spreads out from the class itself to the entire system. This complicates development and maintenance.

[suggested by a colleague an hour after I posted the above]
Setters can validate data, making sure it's in the correct range, consistent with other values, etc., before setting the field.

No comments: