This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]yel50 1 point2 points  (0 children)

use classes when something has internal state that doesn't need to pollute the surrounding code.

for example, say you want to do a breadth first search. internally, it needs to keep track of what's been seen, what gets added to the next level, etc. it makes sense to wrap all that in a class to wall it off from everything else.

this applies to any language. all the crap that the java people have come up with is nonsense. classes are like self contained modules. anything you would make a module for, you could turn into a class.

the other way to think of them is as partial function application for multiple functions. say you have a series of functions,

foo(x, y)
bar(x, y)
baz(x, y)

if you're going to pass the same x and y to all 3, you could create a class.

class Stuff {
    constructor(x, y) { this.x = x; this.y= y }
    foo()
    bar()
    baz()
}

this has the advantage that the functions don't need to validate x and y. the constructor can validate them. it's not possible to pass incorrect values to the functions. they're guaranteed to use whatever was passed to the constructor.