Immutable Classes and Subclasses

前端 未结 3 993
再見小時候
再見小時候 2021-01-05 12:04

I\'m trying to learn about mutable/immutable classes and I came across this post

Part of the answer provided was:

If you want to enforce immu

3条回答
  •  太阳男子
    2021-01-05 12:16

    java.lang.String is special, very special - it's a basic type used everywhere. In particular, java security framework heavily depends on Strings, therefore it is critical that everybody sees the same content of a String, i.e. a String must be immutable (even under unsafe publication!) (Unfortunately a lot of people blindly apply those strict requirements of String to their own classes, often unjustified)

    Even so, it's not really a big deal if String can be subclassed, as long as all methods in String are final, so that a subclass cannot mess with what a String is supposed to be like. If I'm accepting a String, and you give me a subclass of String, I don't care what you do in the subclass; as long as the content and the behavior of the String superclass is not tempered with.

    Of course, being such a basic type, it's wise to mark String as final to avoid all confusions.


    In your use case, you can just have an abstract Employee, and make sure all subclasses are implemented as immutable. Any Employee object, at runtime, must belong to a concrete subclass, which is immutable.

    If, you cannot control who subclasses Employee, and you suspect that they are either morons that don't know what they are doing, or villains that intend to cause troubles, you can at least protect the part in Employee so that subclasses cannot mess it up. For example, the name of an Employee is immutable no matter what subclass does -

    final String name;
    
    protected Employee(String name) { this.name = name; }
    
    public final String getName(){ return name; }  // final method!
    

    However, such defensive design is often unjustified in most applications by most programmers. We don't have to be so paranoid. 99% of coding are cooperative. No big deal if someone really need to override something, let them. 99% of us are not writing some core APIs like String or Collection. A lot of Bloch's advices, unfortunately, are based on that kind of use cases. The advices are not really helpful to most programmers, especially new ones, churning out in-house apps.

提交回复
热议问题