Immutable Classes and Subclasses

前端 未结 3 991
再見小時候
再見小時候 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:06

    It's worth thinking why immutability is desirable - usually it's because you have data which you need to assume is not going to change. One approach to do this is to make a final Employee class with a non-final member containing the details specific to the subclasses:

    public final class Employee {
        private final long employeeId;
        private final String firstName;
        private final String lastName;
        private final DepartmentalDetails details;
    
        public Employee(long employeeId, String firstName, String lastName,
                DepartmentalDetails details) {
            super();
            this.employeeId = employeeId;
            this.firstName = firstName;
            this.lastName = lastName;
            this.details = details;
        }
    }
    
    abstract class DepartmentalDetails {
    }
    
    final class AccountantDetails extends DepartmentalDetails {
        // Things specific to accountants
    }
    
    final class ITDetails extends DepartmentalDetails{
        // Things specific to IT
    }
    
    final class QualityAssuranceDetails extends DepartmentalDetails{
        // Things specific to QA
    }
    

    This isn't technically immutable (since an implementer could write a mutable implementation of DepartmentalDetails) but it does encapsulate the mutability, so it gives the same benefits while allowing some extensibility. (This is related to this is the concept of composition vs inheritance, although I don't believe this pattern is how that is normally used.)

    One other possibility I think is worth considering - you could make the three subclasses as you suggest, make them all final, and stick a big comment on the abstract class saying all implementations should be immutable. It's not bulletproof, but on a small development project the complexity saving is likely to be worth the tiny risk.

提交回复
热议问题