DEV Community

Discussion on: Why Do JS Devs Hate Namespaces?

Collapse
 
lionelrowe profile image
lionel-rowe

To provide a contrary perspective, why does allow need to be a class? Classes can be useful in situations where they might need to be instantiated with different parameters, but your example makes it looks like all the methods being consumed are static, and the class isn't being instantiated at all.

Surely this is the perfect use case for a module, and the principle of least power suggests that we shouldn't reach for a class when a module will do.

If the only issue is namespacing, that can easily be solved by using the import * as allow from '<path>' syntax, and it also provides the flexibility to only import certain functions if the consumer of the module wishes to do so.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

It was created as a class to facilitate chaining by constantly returning this. That being said, it's not the only way to accomplish that goal.

I don't personally disagree with your point - but I don't necessarily see it as a "contrary perspective" either. IMHO, it's more of an alternate perspective. Maybe that's splitting hairs. But the point is that I can't really see how a class, in this scenario, is wrong, but I can absolutely accept that maybe it's not preferred.

Consequently, I literally just started exploring making this an NPM package. (Like... last night.) And I'm thinking that it doesn't really need to be a class - but maybe a plain-ol' object.

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Hmm, a fluent interface does lend itself to OO and OO lends itself to classes, but could be implemented with a plain object too. Not saying this would necessarily be perfect for your use case, but it could be done.

const fluent = {
    fn1: () => { console.log(1); return fluent },
    fn2: () => { console.log(2); return fluent },
}

fluent.fn1().fn2()
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
bytebodger profile image
Adam Nathaniel Davis

I'm actually implementing it now with a module design pattern. So basically, it's a function... that looks a heckuva lot like a class.

github.com/bytebodger/allow/blob/m...