Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

There is a class method (static method) in which I create and build some object. And for filling that object, I create it as mutable object.

My mutable object is a subclass of immutable object. So i can return it as super Class type.

That object is just created in class method and returns. It is not a part of object or class state.

Should I return mutable object or it immutable copy? (what solution will be correct in concept of encapsulation)

For example there is some pseudo code:

// MutableArray is subclass of Array
MutableArray : Array;

// Another class

static (Array *)getEngineers {
   Array *employees = Array.arrayWithContentsOfResource("employees.txt");
   MutableArray *engineers = new MutableArray;
   for (Employee *employee in employees) {
      if (employee.profession == "Engineer") {
   return engineers; // should I return Array.arrayWithArray(engineers) instead of engineers ?


I mean, if I have a mutable array that is a member of the object, then it makes sense to return immutable copy in getter method (to provide access control and encapsulation). But if I have method like in example. I need only immutable object for using. But creating immutable copy of array is additional operations. Does it make sense to make it immutable?

share|improve this question

closed as not a real question by Jimmy Hoffa, Robert Harvey, Martijn Pieters, Bart van Ingen Schenau, thorsten müller Apr 9 '13 at 11:26

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

Hey Pavel, maybe you could join The Whiteboard to talk about how your question could be improved? It's a bit unclear what exactly you're asking about here, and what your reasoning is for either choice – Jimmy Hoffa Apr 8 '13 at 15:58
Thank you, sorry for my bad English – BergP Apr 9 '13 at 6:01
What is immutable in Array that becomes mutable with MutableArray? The container itself (you can't add/delete elements from Array), the elements held by the container or both? – Bart van Ingen Schenau Apr 9 '13 at 8:15
f.e. NSArray and NSMutableArray (objective-c foundation), for NSMutableArray you can add and remove objects after initializing – BergP Apr 9 '13 at 8:18
up vote 3 down vote accepted

if only your team is using this code in the same process then i would return the same object (mutable object) . keep it simple and fast. Your own team would not change something on the objects unless they needed to, and if they did then they would have to make another copy.

If I was making a API too I would not keep it immutable, simple because engineer looks like its an object that can change (like if the object had something like reporting To or degrees-held - that can change over time.

Objects should mimic their real world counter parts as much as possible. Some attributes could be immutable (like date of birth etc)

Good external docs or code comments could explain how to use the object where required

share|improve this answer

Encapsulation doesn't have anything to do with immutability. Well, maybe it does a little. A more accurate term would be "access control." An immutable object restricts access control because you cannot write it; you can only read it.

You make objects immutable when you are using them in a multi-threaded context, and you want to make your code more... "deterministic." There is no right or wrong about this, no "correct" or "incorrect;" if you're not using multiple threads, you probably don't need to worry about immutability at all.

Make objects immutable when you want to guarantee "safe" access to the object via another thread. An object is "safe" to access in a multi-threaded context when you can guarantee that another thread won't be writing an object while you're trying to read it. You can do this with immutability, but you can also do it with locks, mutexes, semaphores and other concurrency mechanisms.

share|improve this answer
To be fair multi-threading isn't the only scenario where you make objects immutable. Immutable objects allow you to verify their state during construction and then never have to do so again since they can't have their state changed to invalid later. For this reason I make objects that deal with unmanaged resources immutable usually. Also since the validity is only tested at one point, that means only one place in consuming code do you need to worry about your object complaining about invalidity. After construction, every other part of code consuming the object can know it's valid. – Jimmy Hoffa Apr 8 '13 at 15:52
I guess my point is there's no such thing as "correct." Asking simply for "which way is correct" in this scenario is meaningless, because the answer is "it depends." However, feel free to enumerate all of the use cases for immutables and let the OP pick the one that fits. :) – Robert Harvey Apr 8 '13 at 15:53
True, I deliberately didn't answer this question because it's pretty vague – Jimmy Hoffa Apr 8 '13 at 15:56
I mean, if I have a mutable array that is a member of the object, then it makes sense to return immutable copy in getter method (to provide access control and encapsulation). But if I have method like in example. I need only immutable object for using. But creating immutable copy of array is additional operations. Does it make sense to make it immutable? – BergP Apr 8 '13 at 17:16
Immutable objects are not only about multi-threading, like Jimmy Hoffa correctly pointed out. Making an object immutable also makes it simpler to reason about single-threaded code: for example, if I see x mentioned somewhere, more code follows, then x again, I know it represents exactly the same value or object state as before; I don't even have to look at the function calls in between. – Andres F. Apr 8 '13 at 20:16

Without knowing more about the use of this mutable/immutable Array, perhaps one factor to consider is the lifetime of the Array. Are you going to store the Array object for later use or pass it around to other parts of your code? If so, then an immutable object might be better because it reduces the chance of accidentally (or perhaps maliciously) having the Engineer array changed. If this is a one-time use, then you might be able to get away with a mutable array because the exposure of that array is already minimal.

share|improve this answer

Your subclass shouldn't violate the contract that the super-class has with its clients.

It isn't automatically true that returning something mutable when the client expects something immutable will violate that contract, but I'm assuming the super-class returns something immutable for a reason, and that clients therefore expect to have an immutable object returned. So, unless you have specific knowledge that it's OK in this case, don't break any client code relying on immutability - return something immutable.

(An example of what might go wrong - maybe classes written to work with the super-class never check its state because they assume it was checked on creation and can't be modified. Then it gets an instance of your class, and fails to verify it is currently in a valid state).

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.