DEV Community

Discussion on: Use fake static classes to protect your namespace (js/ts)

Collapse
 
supportic profile image
Supportic • Edited

I don't get your point at all.
This

Point = {
    mag: (p: Point) => Math.sqrt(p[0] * p[0] + p[1] * p[1]),
    add: (p: Point, q: Point) => [p[0] + q[0], p[1] + q[1]],
    mul: (p: Point, factor: number) => [p[0] * factor, p[1] * factor],
} as const
Enter fullscreen mode Exit fullscreen mode

is basically this

class Point {
    // ...
    add(q) {
        return new Point(this.x + q.x, this.y + q.y)
    }
}
Enter fullscreen mode Exit fullscreen mode

What stands out to me in favour of classes is that you know exactly what you modify or are you able to tell me without reading the documentation what p[0] means?

The initial problem you mentioned regarding the polution and especially with this example:

function transfer(accountId: string, amount: number) {}
function transfer(from: User, to: User, itemId: string) {}
function transfer<T>(from: T[], to: T[], val: T) {}
Enter fullscreen mode Exit fullscreen mode

is naturally solved by classes. They do different things even if they are named the same. Otherwise you could throw in an object and check which properties are defined and act accordingly when the functionallity stays the same e.g.

function transfer(options) {
  options = options || {}
  const {accountid,amount, from, to, itemId} = options

  if(accountid && amount) ...
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
qpwo profile image
Luke Harold Miles

My biggest issue with classes these days is actually that you have to instantiate them to use methods after you get the value from the db. So I am a bit biased by my particular use case.

You could do all this with static methods but an object works just as well and is shorter and clearly cannot be instantiated.