bel
bel

Reputation: 459

Return immutable copy of mutable object from method

I have some closed component which is working over some XML object. I need to expose this object outside of this component, but I don't want to allow changes on it outside of my component. How can I complete this?

Upvotes: 3

Views: 3673

Answers (3)

user2864740
user2864740

Reputation: 61925

Well, here is the access level's advocate ;-)

If you just wish to prevent the caller from making changes, it doesn't mean that it has to be immutable [in your package] - it just means that it shouldn't have a [public] way to mutate it :) I'm actually a growing fan of returning a limiting public interface.

For instance:

// Option A with a "limiting public interface"
public interface Awesome {
    public String getText();
}

class MyAwesome implements Awesome {
    public String getText() {
       // ..
    }
    // Option B is to make setText non-public
    public void setText() {
       // ..
    }
}

Then your code can return Awesome which doesn't [directly] provide a way mutate the object.

Upvotes: 2

Duncan Jones
Duncan Jones

Reputation: 69359

Ensure your object has a copy constructor that allows you to make a deeply-cloned copy of your class.

Then call this when you return the object, e.g.

SomeClass instance = // ....


public SomeClass getInstance() {
  return new SomeClass(instance);
}

This won't make the returned object immutable. But it doesn't need to be - you just don't want the external code making changes to your copy of the data.

Upvotes: 4

Utku Özdemir
Utku Özdemir

Reputation: 7745

I think you need to create another class which is immutable, taking your object as a parameter (maybe in constructor). Then you should only expose the instance of your new class.

Here's some tips to make an object immutable: Immutable class?

Upvotes: 1

Related Questions