DEV Community

David Johnston
David Johnston

Posted on

Immutable OO?

This talk here by Gary Bernhardt has got me thinking.

He's basically proposing what I'd call immutable object-oriented programming, where, you have model objects that contain both data, and functions, but the data is immutable.

When you do need to mutate some data, it returns a new object.

And you bundle that immutable data with helper functions that apply to just that data.

class Foo {
    private data; 
    constructor(data){
        this.data = data; 
    }

    setX(x){
         return new Foo({...this.data, x}); 
    }

    toString() {
        return `This is a Foo object with value x: ${this.data.x}`; 
    }
}

Enter fullscreen mode Exit fullscreen mode

This has the advantages of easy testing, as your Object functions can still be considered pure:

    const object = new Foo({x:1}); 
    expect(object.toString).toBe("This is a Foo object with value x: 1"); 
Enter fullscreen mode Exit fullscreen mode

And reduces a lot of cognitive load that a functional paradigm has where your data, and your functions that use that data are different things.

Eg, the equivalent code for this would be:

   setXOnFoo(foo, x) {
      return {...foo, x};  
   }

   stringifyFoo(foo) {
        return `This is a Foo object with value x: ${foo.x}`; 
   }

   const foo = {x: 1}; 
   expect(stringifyFoo(foo)).toBe("This is a Foo object with value x: 1"); 
Enter fullscreen mode Exit fullscreen mode

In the scenario where the stringifyFoo method is only intended to be used with objects that fit Foo's shape, in the least, by adding those functions to the object means that your IDE is going to be helpful in telling you those methods straight away.

My question is - how well explored is this concept - does it have a different name?

What advantage would function programming have over this?

There is a similar, well received question about this on softwareengineering.stackexchange.

Top comments (0)