3 ms·
On the topic of eliminating simplistic classes: one of things an object is for is to enclose multiple pieces of data and provide multiple methods that access th
by gorgoiler 6y ago
On the topic of eliminating simplistic classes: one of things an object is for is to enclose multiple pieces of data and provide multiple methods that access that data.
If one can compose ones problem into a lot of classes of object that only have one method then it is quite acceptable to just use closures instead:
HI = ‘Hello’
def greeter(title, name):
def f():
print(HI, title, name)
return f
I wrote a whole bunch of Python like this, yesterday. It felt liberating! So terse!
Downside: one very common reason to have more than one method in a class is to define __str__. There will be no pretty debug printable version of my greeter() “class” for me, alas.
- ivalm 6y agoYou can manipulate f.__name__ to improve the debugging experience, since presumably you actually care for what is in f(), not greeter.
- cessor 6y agoI like it. It gives you (f)actual private fields in python, as title and name can't be accessed via the instance variable of f. That also works in JavaScript: function Fraction(a, b) { this.value = function () { return a / b; } } const half = new Fraction(1, 2); It feels weird to me, that classes were eventually introduced in JS.
- gorgoiler 6y agoIt’s worth pointing out that classes in both of these languages implement another headline feature of OO: code reuse through prototypes and inheritance.
- aikah 6y ago> It feels weird to me, that classes were eventually introduced in JS. if you don't put value in the Fraction prototype, then value will be created each time Fraction is instanced. But that's not why class where created. Class simplify writing classes, doing inheritance and introduce "super" static binding which wasn't possible before with functions. Also, JS will now force you to use new when instanciating Fraction class as an object. You can't call it like a function.