Immutable Type: public final fields vs. getter

前端 未结 8 900
臣服心动
臣服心动 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:08

    Forget about encapsulation, immutability, optimization and all other big words. If you are trying to write good java code, I would recommend you just use getter simply because it is java friendly, and most importantly it saves ton of time googling why.

    For example, you probably would not expect using streams when you write the code, but later you found

    listOfImmus.stream().map(immu -> imm.foo).collect(Collectors.toSet()); // with field
    listOfImmus.stream().map(Immu::getFoo).collect(Collectors.toSet());    // with getter
    
    Supplier s = () -> immu.foo;  // with field
    Supplier s = immu::foo; // with getter
    
    // final fields are hard to mock if not impossible. 
    Mockito.when(immuMock.getFoo()).thenReturn("what ever");
    
    //one day, your code is used in a java Beans which requires setter getter..
    ¯\_(ツ)_/¯
    
    

    This list can be long or short or may be none of them makes any sense to your use case. But you have to spend time convincing yourself (or your code reviewers) why you can or should rebel against java orthodoxy.

    It is better to just write the getter/setter and spent the time for something more useful: like complaining java

提交回复
热议问题