assignment operator

Assignment Operator Considered Harmful

Experienced programmers know that the assignment operator (=) can make software hard to understand.

Let’s take a look at an illustrative example. What will this program display in the console?

  var person = new Person("Fred", "Flintstone");

  Console.WriteLine($"The person is {person.FirstName} {person.LastName}.");

  person.FirstName = "Wilma";
  person.LastName = "Smith";
  person.FirstName = "Barney";
  person.LastName = "Rubble";

  Console.WriteLine($"Now the person is {person.FirstName} {person.LastName}.");

The output will be

  The person is Fred Flintstone.
  Now the person is Barney Rubble.

The program listing consists of a few lines. Even so, the code is confusing and hard to follow.

The construction of Person is fine. We initialise the FirstName and LastName properties to “Fred” and “Flintstone”, respectively. So far, so good. Our troubles start now—the code changes (or mutates) the FirstName and LastName of this person instance multiple times. It’s hard to keep track of what the person’s name will be line by line.

It’s hard to reason about code when too many entities change at the same time. On the other hand, we programmers find code easier to understand when entities are unchanging. If, for the duration of a function call, a variable x reliably contains the value 5, then isn’t this better than if x starts as 5, then changes to 7 two lines down and finally ends up with a value of 1?

Yes, of course, it is. Mutable state can be harmful to the understandability of a program. And the Assignment operator is how we create this mutable state.

Encapsulation and immutability are the tools we use to limit or eliminate state changes within objects. They make code easier to follow and reason about. If an immutable variable x contains the value 17, then x will continue to hold 17 for its lifetime.

Consider writing code so that the internal state of objects cannot be altered—or can only be modified via protected and limited access. More on this another time.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply