Immutable Type: public final fields vs. getter

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

    Using public final may be fine for such small job, but it cannot be adapted as a standard practice,

    Consider the situation below.

    Public class Portfolio {
       public final String[] stocks;
    }
    

    Of course, being immutable, this object is initialized vis constructor, and then accessed directly. Do I have to tell you the problem in it? It’s evident!

    Consider your client writing the code like below -

    Portfolio portfolio = PortfolioManager.get(“Anand”);
    Portfolio.stocks[0] = “FB”;
    portfolio.calculate();
    

    Is this doable? Your client libraries are able to manipulate the state of your objects, or rather able to hack within your runtime representation. This is a huge security risk, and of course tools like SONAR catch it upfront. But its manageable only if you are using getter-setters.

    If you are using getters, you can very well write

       Public class Portfolio {
          private final String[] stocks;
          public String[] getStocks() {
              return Arrays.coptOf(this.stocks);
          }
       }
    

    This prevents you from potential security threat.

    Looking at the above example, using public final is strongly discouraged if you are using arrays. In such case, it cannot become a standard. A person like me, will refrain from using a code practice that cannot become a uniform standard across all data types. What about you?

提交回复
热议问题