Ask HN: Why would I use a class over a module for stateless computation?
On the one hand, I don’t want to blindly imitate programmers who are dealing with problems of a different type (or scale) than those I’m dealing with and end up making my own code unnecessarily complex. I sometimes have an imaginary conversation with a composite “seasoned Python programmer” in which I proudly show him code that I’ve written as a collection of classes, and he looks at me quizzically and says, “Why did you write all these classes to solve this problem? I would have just used modules.”
On the other hand, as I’ve matured as a programmer I’ve noticed that my code has started to look more like the code I read, not due to conscious imitation, but because I’ve improved and those improvements have naturally made my code look more like the code of more experienced programmers. If I’m inevitably going to rediscover the reason for using objects when state isn’t an issue, I might as well just be told what I’m missing and save myself some time (and spare my employer the inferior code that I’ll be writing in the interim).
3 comments
[ 4.0 ms ] story [ 42.3 ms ] threadIs this a matter of professional pride? I do not know. I just make a module for truly global variables: class G: a=1; b=2; which can be easily accessed everywhere G.a=G.b+4 .
It sounds like maybe you’re talking about what I’ve heard referred to as “cross-cutting concerns” that happen to be stateful. I haven’t developed anything large or complex enough to run into that, but I can imagine (in a fuzzy sort of way) code that contorts itself to avoid globals when a far simpler solution would be, “Use this small number of globals, but be careful.”
I could be way off here. I’m eager to hear your response.
Classes also has some extra trickery over modules which you can use and abuse. Such as __getattr__ and __getitem__.