5 ms·
A class also acts as a namespace. If computation is complex and requires multiple subfunctions that you don't want to leak to the global namespace, I think it'
by kgeist 4y ago
A class also acts as a namespace. If computation is complex and requires multiple subfunctions that you don't want to leak to the global namespace, I think it's totally fine to use a class instead of a bare function. Some algorithms also require a lot of context to be passed between such subfunctions, and it's sometimes quite handy to store such context as private fields of the class to avoid passing it from function to function everywhere. Another thing is dependency injection, if the algorithm requires several dependencies, it's sometimes better to inject them in the constructor once instead of passing them from function to function, or using global state. But I agree that for small functions it's an overkill to create a whole class. It also depends on the language you use and what's idiomatic in it and what is not.
- creatonez 4y agoSounds like a great use case for closures https://en.wikipedia.org/wiki/Closure_(computer_programming) https://en.wikipedia.org/wiki/Closure_(computer_programming)
- DeathArrow 4y agoHow? You use the closure to capture the variables, but how can you make the variables visible in another function?
- kgeist 4y agoYes, this kind of approach is equivalent to closures/currying, in the style of OOP. However, using closures for this may not look idiomatic in some languages.
- Twisol 4y ago> If computation is complex and requires multiple subfunctions that you don't want to leak to the global namespace In cases like this, I still use a top-level free function, but it just instantiates a (private) class and invokes those (private) subfunctions itself. There's usually no need to leak the implementation's strategy for managing complexity to callers. Of course, if your computation required interactivity with the caller, then it's not a one-and-done batch deal anyway, so free functions would not have been as appropriate in the first place.
- kgeist 4y ago>In cases like this, I still use a top-level free function, but it just instantiates a (private) class and invokes those (private) subfunctions itself That's a good approach I follow myself, too. The fact that I decided to use a class to manage complexity is an implementation detail; callers should not be aware of it. I don't think there's an opposition "free functions vs. classes", they complement each other.
- BiteCode_dev 4y agoModules are already name spaces, and dependency injection can be configured using partial application.
- DeathArrow 4y agoIn which language?
- BiteCode_dev 4y agoIn Python.
- DeathArrow 4y ago>A class also acts as a namespace. Namespaces are stateless, they don't contain variables, they contain just functions.