Encapsulation or public attributes: but nothing inbetween

This post asked the question:

Whenever a class in my model contains a collection which requires that particular care be taken with its items, there’s an internal debate regarding how to expose it to other classes. And with this, there are two major schools: one, the paranoia-based approach which doesn’t allow external code to touch the collection’s internal items and two, the trusting approach which just returns the collection for everyone to deal with.

What are your thoughts on the matter? What do you use, when and why?

Definitely paranoia.

It may make certain things more difficult or require more code, but one of the key cornerstones of object-oriented programming is encapsulation and not exposing your internal data in a way that means that others can break it.

If one wants to go for the trust approach - sure it’s easier - but if easiness is the objective one can write a C program and just declare a struct. Then anyone can access the data anyway they want and there’s absolutely no code to write (not even getters and setters). But the world moved away from that model towards encapsulation as with N lines of code (or Nk LOC or NM LOC), without encapsulation, any of those can be responsible for the creation of inconsistent data.

2 Responses to “Encapsulation or public attributes: but nothing inbetween”

  1. Robin Salih Says:

    I agree with the paranoia approach for sure.

  2. Aviad Ben Dov Says:

    Adrian,

    I wish pingbacks would work too. :)

    Anyway, what you said is something I completely agree with, this is why I always go for the paranoia approach. However, as I wrote in the post itself, this approach causes problems with some frameworks. What do you do when these things happen?

    Thanks for the response. :)

Leave a Reply