开发者

Can I make object unmutable once the constructor is called?

class X
{
  String x1;
  String x2;
  //...
  String x15;

  public X (Other o)
  {
    // initialize x1,x2,...,x15
  }

  String getx1 () { return x1; }  // lot of getters
  String getx2 () { return x2; }
  //...
  String getx15 () { return x15; }
}

The object of class X is initialized in constructor of class Other;

class Other
{
  private X obj;
  // Other members
  public Other ()
  {
    obj = new X(this);
    /开发者_StackOverflow中文版/...
  }
  //...
}

I want to somehow get rid of lot of getter methods in class X. I can simply remove those and make all the data members of X in default scope (X is used only within package).

Is there any way by which I can make the members of X obj un-mutable after the constructor Other is called ? Here the idea is, when using get() methods, the variables inside X cannot be modified.

obj.getx1();

Now, if I use simply obj.x1 then there are chances that it might get overwritten (or at least in code review, it will be objected).

[Note: obj has to be initialized in the Other() constructor only].


If you declare you member variables as final, then they are immutable after constructor.


Here's how you make the class immutable:

class X {
  private final String x1;
  private final String x2;

  public X (Other o)
  {
    x1 = o.getX1();
    x2 = o.getX2();
  }

  String getX1 () { return x1; } 
  String getX2 () { return x2; }
}

However, getting rid of the getters is usually a bad idea. For instance:

  • Getters reduce coupling, and allow the actual implementation types of the xn fields to be changed without breaking client code.

  • Getters can be overridden in a subclass but bare attributes can't.

  • Getters allow the object to be used as a "Java bean".

And the presence or absence of getters doesn't make the class immutable.


Best way to make a class immutable (not un-mutable) is to mark all fields as final (visibility is irrelevant, can be public). Fields must be initialized either with an initializer:

class A { final int x = 10; }

or in every constructor:

class A { 
   final int x, y, z;
   A(int x, int y, int z) { this.x = x;, this.y = y; this.z = z; }
   A() { this (0, 0, 0); }
}


The getter methods don't make the instance mutable. That would be setter methods. Your X, as defined, is already immutable — nothing can change the x values of an instance, they can only be retrieved via the getters.

If you're asking how to get rid of the getter methods and allow direct access to the member variables: Any decent JVM will inline those getter functions via its JIT compiler, making them direct member retrievals instead. So if you keep the getters, you keep flexibility for changes down-the-line, at very nearly no cost.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜