Alex Rivera | Logout

Private vs. Public members in practice (how important is encapsulation?)

Asked 2008-09-19T04:44:32.293
22

One of the biggest advantages of object-oriented programming is encapsulation, and one of the "truths" we've (or, at least, I've) been taught is that members should always be made private and made available via accessor and mutator methods, thus ensuring the ability to verify and validate the changes.

I'm curious, though, how important this really is in practice. In particular, if you've got a more complicated member (such as a collection), it can be very tempting to just make it public rather than make a bunch of methods to get the collection's keys, add/remove items from the collection, etc.

Do you follow the rule in general? Does your answer change depending on whether it's code written for yourself vs. to be used by others? Are there more subtle reasons I'm missing for this obfuscation?

Edit
Report

4 Answers

1

C# Properties 'simulate' public fields. Looks pretty cool and the syntax really speeds up creating those get/set methods

answered 2008-09-19T04:55:43.263
1

Keep in mind the semantics of invoking methods on an object. A method invocation is a very high level abstraction that can be implemented my the compiler or the run time system in a variety of different ways.

If the object who's method you are invoking exists in the same process/ memory map then a method could well be optimized by a compiler or VM to directly access the data member. On the other hand if the object lives on another node in a distributed system then there is no way that you can directly access it's internal data members, but you can still invoke its methods my sending it a message.

By coding to interfaces you can write code that doesn't care where the target object exists or how it's methods are invoked or even if it's written in the same language.


In your example of an object that implements all the methods of a collection, then surely that object actually is a collection. so maybe this would be a case where inheritance would be better than encapsulation.

answered 2009-02-10T18:38:43.567
0

It's all about controlling what people can do with what you give them. The more controlling you are the more assumptions you can make.

Also, theorectically you can change the underlying implementation or something, but since for the most part it's:

private Foo foo;
public Foo getFoo() {}
public void setFoo(Foo foo) {}

It's a little hard to justify.

answered 2008-09-19T04:47:54.873
0

When I make objects meaningful they are easier to use and easier to maintain.

For example: Person.Hand.Grab(howquick, howmuch);

The trick is not to think of members as simple values but objects in themselves.

answered 2008-09-19T05:33:04.533

Your Answer