DEV Community

David Johnston
David Johnston

Posted on

2 1

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.

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay