4

According to Effective Java's Item 15: Minimize Mutability, it is always better to make classes Immutable. According to that, how would I handle classes that are by nature given to change?

Some examples would be:

  • A Customer class, where an address or phone number can (and probably will) change.
  • A ShippingRule class, where shippers are selected based on different criteria. It makes sense that the rule should be editable...

In such cases, do we necessarily make them immutable? What other conventions are there?

Tulains Córdova
  • 39,570
  • 13
  • 100
  • 156

1 Answers1

6

I read the chapter you stated, and I can see how you might be confused, as the chapter doesn't describe how you might use immutable objects.

Immutability is a core part of functional programming. To see how it works, consider this code:

MyImmutableClass newInstance = transform(MyImmutableClass originalInstance);

The transform method accepts the originalInstance object, transforms it (that transformation can be any operation), and returns a new object containing the transformation.

Why would you want to create a new object, instead of modifying an existing one?

  1. It creates a history of changes.
  2. It makes concurrency easier. Immutable objects are not subject to concurrency problems like race conditions. Functions using immutable objects can be easily decomposed into separate concurrent processes without problems.
  3. Immutable objects are easier to reason about.

In business applications involving CRUD operations, because you're typically already using a database with ACID guarantees, it's more common to simply mutate the values in the object you want to change, and then perform a Save (Update).

Robert Harvey
  • 200,592