Skip to content
Advertisement

(Date) may expose internal representation by storing an externally mutable object into CategoryModel.createdDate

While working on model class i face an following warning :–

JavaScript

My model Class

JavaScript

Description of the warning:–

Returning a reference to a mutable object value stored in one of the object’s fields exposes the internal representation of the object. If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is better approach in many situations.

In above model class i get an warning , what is the better approach to handle this ?? Thanks in advance…

Advertisement

Answer

Defensive copy

You are accepting a reference to mutable object from outside your class for use inside your class. That means the source of that mutable object can mutate its value behind your back. One moment your own object contains June 3rd of this year, and a moment later it contains November 27th of last year. And any other objects with a reference to that mutable object can mutate its value behind your back in the same tragic manner.

Best practice is to make a defensive copy of that mutable object upon receipt. Copy out its internal values into another fresh object. You know this fresh object is safe as no other objects have a reference to it.

If you do not understand this behavior of object references in Java, study some basics about Java programming. Perhaps the Oracle.com Tutorials, or the Head First book on Java by the O’Reilly publisher.

An alternative to defensive copy is to use an immutable object in the first place. If immutable, the entire issue is eliminated.

java.time

You are using troublesome old date-time classes, now supplanted by the modern java.time classes.

The java.time classes are immutable. So your problem described above is eliminated if you replace every use of Date & Calendar with a java.time class. For a moment on the timeline in UTC, the same as java.util.Date, use java.time.Instant.

JavaScript

Usage when interfacing with legacy code.

JavaScript

And:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement