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") { engineers.addObject(employee) } } return engineers; // should I return Array.arrayWithArray(engineers) instead of engineers ? } Update:
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?
Arraythat becomes mutable withMutableArray? The container itself (you can't add/delete elements fromArray), the elements held by the container or both?