DEV Community

Adam Crockett 🌀
Adam Crockett 🌀

Posted on

The 'not class' pattern

I am coining the term 'not class' because until anyone tells me what this is I am going to refer to it incorrectly otherwise.

The premise is simple, Classes in JavaScript are just a little restrictive, when you go down this route you lose the flexibility of using objects, what if you wanted multiple inheritence or a proxyless new hook and so on. I believe strongly (as an ex class lover) that this pattern is a better way.

I also really like the word new, so here is the code.

const MemoryCtrl = {
  new(config) {
    // a new instance of this entire object will be created
    // I could change what new does, or even add some extends methods bellow
    const inst = Object.create(this)
    this.construct(inst, config);
    return inst;
  },
  construct(inst, config) {
    inst._memory = new WebAssembly.Memory(config);
    inst._mut = new Uint8Array(this._mut);
  },
  append(...bytes) {
    this._mut.findIndex((occupied) => !occupied);
    // Some stuff here
  },
  clear() {
    // Some stuff here
  },
  view() {
    console.log(this._mut);
  }
}

const mem = MemoryCtrl.new({
  initial: 255,
  max: 255
});
Enter fullscreen mode Exit fullscreen mode

I could also turn this into a builder patter, or perhaps restrict the amount of methods returned for true privacy, there is a lot of flexibility here.

Anyway, let me know if you like it or hate it and wish I would just use classes and why.

Top comments (6)

Collapse
 
deciduously profile image
Ben Lovy • Edited

I'm not sold on the fact that allowing multiple inheritance is a good thing, but that might be only because I'm currently learning C++.

Collapse
 
pavelloz profile image
Paweł Kowalski

It is not a good thing. One level max (preferably, composition over inheritance, as classic says), otherwise it becomes nightmare to debug and a huge mental baggage.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I think in my head I have my concepts (names mixed up)

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Completely the developers choice to implient, I choose this as an example of flexibility. Anyway I agree multiple inheritance is unpopular perhaps I meant to say composition.

Collapse
 
deciduously profile image
Ben Lovy

I agree, this is pretty cool - didn't mean to disparage the pattern, this sort of thing had never occurred to me. Re-defining new is pretty interesting.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Thats alright, I didnt take it that way at all. (im just not feeling well today)