Immutable Type: public final fields vs. getter

前端 未结 8 916
臣服心动
臣服心动 2020-11-30 04:48

I need a small Container-Class for storing some Strings which should be immutable. As String itself is an immutable type, I thought of something like that:

p         


        
8条回答
  •  半阙折子戏
    2020-11-30 05:12

    I found this thread hoping for some actual arguments, but the answers I've seen here didn't help me all that much. After some more research and thinking I think the following has to be considered:

    • public final looks cleanest for immutable types.
    • Mutable types could be altered by accessors even if this is not intended - in concurrent environments this could lead to a lot of headaches.
    • There can be no no-arguments constructor. This is importent if you need factory methods (e.g. for LMAX Disruptor). In a similar way instantiating your objects via reflection becomes more complicated.
    • Getters and setters can have side effects. Using public final clearly tells the programmer that no hidden magic is occuring and the object is inherently dumb :)
    • You can't return a wrapper or a derived class instance to the accessor. Then again, this is something you should know about when the field is assigned its value. In my opinion container classes should not be concerned about what to return to whom.

    If you're mid development and no guideline is stopping you and the project is isolated or you have control over all involved projects I'd suggest using public final for immutable types. If you decide you need getters later on, Eclipse offers Refactor -> Encapsulate Field... which automatically creates these and adjusts all references to the field.

提交回复
热议问题