Mutable, Immutable and Generics

Immutable objects help with avoiding bugs. Suppose I have two interfaces implementing the Immutable Interface pattern. One interface for Point and one with MutablePoint. The pattern suggests a cast to ImmutablePoint p; ((Point)p).setX( 1.0 ); get the mutable interface. This isn’t safe and can be replaced with a Generics solution.

First we have the mutable point:

which we want to create from an Immutable object without a cast:

The second benefit beside the missing cast is that users of the Point interface know there is a mutable interface which they can get in a defined way.

The makeMutable() method comes from a generic interface called Mutable

which is extended by the Point interface.

Our Point implementation now only needs to implement MutablePoint and Point. Voila.

A negative side effect is that people who have a reference to a Point object can get a mutable version. When the main point is to have more immutable objects. The other way round is often better, have MutablePoint and create an immutable version.

Thanks for listening.

Update: As pointed out, making an mutable object from an immutable one will break the contract, as will making an immutable one from an mutable one. You do need to copy the object to be safe. For example with a BeanCopier or a copy constructor I’ve wrote about in Beautiful Java: Reflection and the BeanCopier. Better name the method asMutable than makeMutable

40 thoughts on “Mutable, Immutable and Generics”

  1. Pingback: yandex ankara
  2. Pingback: ???
  3. Pingback: SEO Wien
  4. Pingback: venus factor
  5. Pingback: para kazanmak
  6. Pingback: para para dinle
  7. Pingback: para para dinle
  8. Pingback: economics tuition
  9. Pingback: economics tuition
  10. Pingback: fightinjustice
  11. Pingback: joe de saram
  12. Pingback: joe de saram
  13. Pingback: sfeerhaard
  14. Pingback: M88
  15. Pingback: kimsin sen
  16. Pingback: hire an attorney
  17. Pingback: m88asia
  18. Pingback: Denver Uber Driver
  19. Pingback: buy oral steroids
  20. Pingback: celtic rings
  21. Pingback: apps
  22. Pingback: APKBucket
  23. Pingback: margaret cunniffe
  24. Pingback: Skrota bilen
  25. Pingback: brook stagles
  26. Pingback: top to bottom

Comments are closed.