java - (Date) may expose internal representation by storing an externally mutable object into CategoryModel.createdDate -
while working on model class face following warning :--
com.model.products.categorymodel.setcreateddate(date) may expose internal representation storing externally mutable object categorymodel.createddate
my model class
@jsoninclude(include.non_null) public class categorymodel { private date createddate; public date getcreateddate() { return createddate; //warning message:--com.model.products.categorymodel.getcreateddate(date) may expose internal representation storing externally mutable object categorymodel.createddate public void setcreateddate(date createddate) { this.createddate = createddate; //warning message:--com.model.products.categorymodel.setcreateddate(date) may expose internal representation storing externally mutable object categorymodel.createddate }
description of warning:--
returning reference mutable object value stored in 1 of object's fields exposes internal representation of object. if instances accessed untrusted code, , unchecked changes mutable object compromise security or other important properties, need different. returning new copy of object better approach in many situations.
in above model class warning , better approach handle ?? in advance...
defensive copy
you accepting reference mutable object outside class use inside class. means source of mutable object can mutate value behind back. 1 moment own object contains june 3rd of year, , moment later contains november 27th of last year. , other objects reference mutable object can mutate value behind in same tragic manner.
best practice make defensive copy of mutable object upon receipt. copy out internal values fresh object. know fresh object safe no other objects have reference it.
if not understand behavior of object references in java, study basics java programming. perhaps oracle.com tutorials, or head first book on java o’reilly publisher.
an alternative defensive copy use immutable object in first place. if immutable, entire issue eliminated.
java.time
you using troublesome old date-time classes, supplanted modern java.time classes.
the java.time classes immutable, problem described above eliminated if replace every use of date
& calendar
java.time class. moment on timeline in utc, same java.util.date
, use java.time.instant
.
Comments
Post a Comment