Returning mutable member variables (Date/Timestamp) using getter functions in Java? [duplicate]

不打扰是莪最后的温柔 提交于 2020-08-08 05:02:50

问题


I have a java class:

class MyObj{
  private Timestamp myDate;

  public  Timestamp getMyDate(){ 
       return mydate;
  }
  ...
}

when I check it by Findbugs, it says:

Bug kind and pattern: EI - EI_EXPOSE_REP May expose internal representation by returning reference to mutable object

so, what is the better way to write the getter for Date and Timestamp types in Java?


回答1:


Date and Timestamp are both mutable, so returning a reference to your Timestamp means the caller can change the internal state of your class. That's only a problem if it's a problem, if that makes sense; if you mean for the caller to be able to modify the state of your object (by modifying the state of the instance field you're returning), that's okay, though it can be the source of relatively subtle bugs. Often, though, you don't mean to allow the caller to do that; hence FindBugs flagging it up.

You have a couple of choices if you want to avoid exposing a reference to a mutable object:

  1. Clone the object when returning it (a "defensive copy"), so that the caller gets a copy, not the original:

    public Timestamp getMyDate(){ 
         return new Timestamp(mydate.getTime());
    }
    
  2. Return an immutable type or a primitive instead of a mutable one, for instance:

    public long getMyDate(){ 
         return mydate.getTime();
    }
    
  3. Don't use a mutable object at all. For instance, instead of Timestamp, you might use LocalDateTime or ZonedDateTime from java.time, e.g.:

    class MyObj{
      private LocalDateTime myDate;
    
      public LocalDateTime getMyDate(){ 
           return mydate;
      }
      // ...
    }
    

    If you need to update the date in your class (let's use the example of adding a day), instead of mutating the object, you replace it with a new one:

    this.mydate = this.myDate.plusDays(1);
    



回答2:


Return a defensive copy rather than original so that the getter accessor can't modify your actual Timestamp .

 public Timestamp getMyDate(){ 
       return new Timestamp(mydate.getTime());
  }


来源:https://stackoverflow.com/questions/45050480/returning-mutable-member-variables-date-timestamp-using-getter-functions-in-ja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!