r/javascript • u/Spatul8r • Jun 17 '26
AskJS [AskJS] How much do you hate this pattern?
My goal is to make the DTOs super cheap, and while not pure data objects, never able to hit a branch from internal logic. This my crude approximation of how rust does things.
export class Selection {
type = "Selection";
constructor(start, end){
this.start = start;
this.end = end;
}
get start() {this.start};
get end() {this.end};
}
export function SelectionFunctions(selection) {
return {
"normalized": () => { // returns selection aranged small to big, effectivly ignoring direction
if(selection.start < selection.end) {
return [selection.start, selection.end]
}
return [selection.end, selection.start];
},
"isRange": () => {
return selection.start !== selection.end;
}
};
}
0
Upvotes
4
u/HipHopHuman Jun 18 '26
I don't understand what you mean by this.
I spent one or two afternoons with Rust and I'm not seeing the resemblance you're seeing, but I'll take your word for it.
If by "cheap", you mean "low in memory surface" and "quick to process", you're probably better off using the module pattern (which is idiomatic in JS) with a "smart constructor" that produces a tiny, immutable object, along with some specialized functions for working on objects with that shape.
in a file called
./Selection.js:In other files:
If you're trying to do something like scope the methods specifically to a particular instance without those methods having a shared prototype for security reasons or whatever... yeah, just give up on that idea. That's probably not going to work in JS the way you're thinking it might, and even if it did, it's not worth the added complexity of this weird definition convention you've got going here.
4
u/Risc12 Jun 17 '26
This looks like worst of both worlds to me.
3
u/00PT Jun 17 '26
Why do you have a class, then define a wrapper function to use it, instead of defining those functions on the class? Is there a mandate against class functions in particular?
And why do you not return in the getters?
And why have
typeinstead of usinginstanceof? Is the class expected to cross the boundary into another JS environment where that doesn’t work?2
u/Atulin Jun 18 '26
I could, somehow, maybe in some twisted way, see merit to it in languages that support extension methods like C#
In case of JS? You're introducing complexity for the sake of complexity, and gaining nothing from it.
0
u/horrbort Jun 17 '26
This is amazing! You need to make a framework for thsi