Hacker News new | past | comments | ask | show | jobs | submit login

If you find yourself regularly writing functions that return more than one closure, you should consider using a class instead.

That’s an ironic joke of course — who does this? — but it’s a helpful way to then think about the inverse. If you have a class with one function then it could probably just be a closure.

Even better, if it closes one thing, one thing only, and uses that thing while never modifying it then your class is really just a group of functions all of which share the same first argument. Quite a lot of “Database” abstractions are like this, with methods built around a single internal reference to a database connection.

The downside of returning a function instead of an object is your caller has to give it a name:

  lol = build_handle()
  lol()
…versus the class-as-sensible-name-enforcement version:

  lol = Handle()
  lol.sensible_name()
As always, quite a lot of these problems are stylistic (or cultural, if you work in a team) rather than technical.

Coding is, amongst other things, an exercise in design.




I do the pair of closures fairly frequently, it's a good match for a producer/consumer pair. For something like a saturated counter an object with a getter and setter is more natural.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: