2

I know that pure functions shouldn't mutate state that's not passed in as a parameter but I don't know if the this keyword is an exception to that rule. Here is a simple example of what I'm thinking:

 class Car {
    color: string = 'red';
    make: string = 'Dodge';

    constructor() {}

    changeMake(newMake: string): string {
      this.color = 'blue';  // <-- Is this impure?
      return newMake;
    }
  }

Is this impure? Why, or why not?

TheCodeFox
  • 96
  • 10

1 Answers1

4

No, you cannot mutate properties since that changes the value (object) and that is a side effect. Pure methods can expose their data, but never change them. They can create new objects and then they are considered pure:

class Car {
    color: string;
    make: string;

    constructor(color = 'red', make = 'Dodge') {
        this.color = color; 
        this.make = make;
    }

    changeMake(newMake: string): Car {
        return new Car(this.color, newMake);
    }
}

This creates a copy of the original car with the new make and thus every place the old object was used still has the old object.

A really good example of this is the Java String class, which is purely functional. Every method that returns a String that is different always return a newly constructed one. Quite a feat when thinking it was conceived in the golden age of OO.

Sylwester
  • 47,942
  • 4
  • 47
  • 79
  • javascript strings are immutable too – Mulan Jan 15 '19 at 06:18
  • Two additions: A language with reference values like JS `Object`s cannot be technically pure because it has referential identity instead of the required transparency. And when you work with `class`es and their hierarchies it is only natural to work with mutations as well, because such a design relies on mutations. –  Jan 15 '19 at 10:33