by fuzzy2 · 6y ago · 0 comments
> I’m terrible at making good abstractions with classes.
Then don’t. Or only do it after everything is done and you have explored the domain. Don’t try to be clever from the start. Unless you have understood everything, it will backfire.
> But as other classes extend and override those methods to address their version of the problem space, they usually end up having some other responsibilities in addition to the original task.
Inheritance gone wrong. If a derived type behaves differently, it should not be a derived type. See Liskov substitution principle. Just because a hash map is somewhat like a list of key/value pairs doesn’t mean it should derive from one.
It could also be a problem of missing separation of concerns/responsibilities, which is entirely unrelated to OOP.
> Secondly, I’ve noticed that classes have a tendency to grow large.
Yes, I did see many big classes. They were always the result of... missing separation of concerns/responsibilities. The fabled god objects.
The section about state management appears to be very much React-specific, too. So, not about classes.
The problem with classes in languages that use them as a main abstraction (Java, Ruby, etc) is that people reach for them for all abstraction and software design as their Day 1 tool.
All program state and behavior is now immediately fragmented from Day 1 in arbitrary buckets and my experience some moss quickly grows on them and things are never changed for the life of the program.
Just seems your post doesn't offer much insight beyond the classic OOP advice I've heard for years when people realize it's not that great: oh no, you're doing it wrong, don't do the bad things, just do the good things and ensure everyone else is doing them too. I don't see how that's actionable nor useful.
Limiting class use as much as possible and using functional module pattern as TFA does, on the hand hand, is actionable advice for these common issues with classes.
State management is hard. Changing how you refer to the state isn't going to make it any easier, just different.
In an object, all the functions implicitly take that state (or explicitly don't if you mark them static).
So instead of namespace::function(arg1), you now have namespace::function(obj, arg1), even when your function has nothing to do with obj. From the outside, you then have to wonder which members of obj might be being read or written inside the function. If lots of those methods call other methods, which may or may not modify the state of the object, you can end up in a situation where it's hard to reason about the functions because you have to read a lot of code to work out what the inputs and outputs really are.
This is the problem in the Java-style "everything must be a member of a class" approach. People have a tendency to make everything into members of objects.
A function that only takes the values it needs is much easier to reason about.
I think that you are right in that there isn't much practical difference between the two approaches when well-written (in particular when staticness/mutability/constness are clear). However, I find poorly written OO (e.g all methods are instance methods, local variables stored as members) to be really tricky to reason about, and all too common. I haven't had that problem with poorly-written non-OO code.
Perhaps Java would be cleaner if it had free functions. But this isn't so different than a big class that has a pile of static methods.
C++ also addresses the "you have to wonder what members might be read or written inside the function" by encouraging the use of "const" as much as possible. You get really nice invariants preventing surprise state changes in receiver objects and other parameters through judicious use of "const", even if everything is a class or object.
With a class, however, you normally make the data members private; that is, only the member functions of the class can change them. If the data gets mangled, you now have a very small set of places to look. That difference matters when debug time comes around.
> only the member functions of the class can change them. If the data gets mangled, you now have a very small set of places to look.
But probably anything could have called those mutating methods, so you still need to consider the entire codebase.
It also wasn’t supposed to be advice. (Not sure what you mean by TFA.)
By the definitions I'm familiar with, functions would be abstractions of program segments, and variables would be abstractions of program data.
With that understanding, the closest you could get to writing a program without creating abstractions would be to write in assembly—but even if you opt to use as little abstraction as possible, you may just get further from your original recommendation to "Create the literal thing you want to create":
I can see a couple ways of interpreting that statement.
1) Imagine what you want to create already existed: what it would literally be is a block of machine code, so when you write your program you should make it as close to that hypothetical literal existence as possible.
2) What you want to create doesn't exist materially, so its only literal existence is a set of high-level domain-specific concepts (i.e. its existence is a spec), in which case the most literal way to represent it would be through a set of matching high-level concepts defined through a programming language, i.e. a set of matching abstractions.
Under the second interpretation at least, it requires heavy use of abstraction in order to implement the spec as literally as possible.
It's tempting to design a class hierarchy from first principles: everything in the game is an entity, from which players and NPCs are derived. The NPC base class has several derived versions (allies, monsters); the monster class is specialized into animals and dragons, which in turn....
You can often paint yourself into a corner this way, where you suddenly don't want the dragon class to reuse part of the MonsterBase. They're suggesting making the classes stand-alone with duplicated code, at least until you figure out what these classes actually have in common and what is incidental overlap.
The trouble is that "extends" conflates three different things, and many languages don't offer an easy way to do those things separately:
1. Ad-hoc polymorphism: this thing offers the same interface as this other thing, but with a different implementation
2. Composition: this thing contains this other thing, and uses it to implement its own functionality
3. Delegation: this thing implements this interface by forwarding it to this thing that it contains (possibly overriding some parts)
So you end up with things that need to share implementation accidentally exposing a common interface, or vice versa. Thankfully we're seeing more and more languages offering the option to do delegation more explicitly (Kotlin/Rust-style delegation, Haskell/Rust-style derivation), and to do ad-hoc polymorphism without needing to share implementation (Java-style interfaces, Haskell typeclasses / Rust traits).
1. Polymorphism
class Example {
method be-nice () {
'be nice'
}
}
class Bill-and-Ted is Example {
method be-nice () {
'be excellent to each other'
}
}
2. Composition role Salaried {
has $.salary;
}
role Employee {
has $.title;
}
class Manager does Employee does Salaried {}
3. Delegation class Price {
has $.cost;
}
class Product {
has Price $.inner handles( 'price' => 'cost' );
}
Any call to the `.price()` method on `Product` will delegate to the `.cost()` method on the inner object.But when your public facing methods are big blobs, they tend to have lots of params that cause fairly different thing to happen, and it gets much harder to have testing confidence around that than if you had a bigger set of smaller public-facing operations.
It's a basic philosophical difference in what a unit test should be doing. It goes back over a decade.
I'm a bit in between the way described there, though, since I'll often happily leave other objects mocked as long as I know that my contract successfully called that object. I don't need to test all the way through their own implementation - there should be sufficient testing on that object to drive a refactor of it. I just want to support a refactor of me.
My view is basically: "we're gonna have to restructure some of this code as future requirements come in, so let's make sure our tests ensure that the things we really want to happen do happen" (like an update being sent to the database or other backend service layer).
I have similar hesitancy about applying a lot of design patterns early. Most of the places I've worked have been in the experimentation and rapid feature development stages of the business, with all development being internal development (rather than providing an SDK to others), so being able to change the code is more critical than being able to treat the code as more of a framework.
I think classes without internal state, can be large and still simple to understand. But if many mutable fields and internal constraints, then things can get complicated. Better keep such classes smaller
If an existing services does not match exactly what you need to do, you write a new service and reuse the same repositories.
I think this really hits the nail on the head. Classes are the ultimate DRY tool but it seems like much of our industry is realizing that it's rare for any project outside of small self-contained libraries to reach the point where you know enough about your problem domain to ever start meaningfully factoring code out like this.
Instead having "here are the different shapes of state you might see floating around" and "here are some functions that can do things with certain shapes" becomes really powerful when you need to be nimble with features/requirements. Encapsulation is beautiful when the scope is specified completely up front but it I've found it leads to more complicated code and mental overhead because you create a world where the least cost path to doing what you want does a run around with types.
Seriously, just hire a good senior software engineer
I find some problems are solved better in an OO way such as interacting with a relational database.
Others like data processing, are better done in a functional pattern.
I look for the right tool for the job rather than some idealistic purity
I've switched to functional interactions with a database, (Elixir/Ecto) and really, it's much better. In particular the explicit and declarative nature of the database interactions combines the convenience of an ORM with "not hiding important gotchas from you". I'm not arguing for pure functional systems (which I can see going very poorly with relational databases).
There are some things that objects are good at like caching state as a model. But even here the FP systems typically do it better via FP actors and (again, impure) message passing, which enforces no-shared memory, and at least in erlang virtual machine systems, couples segregated state with limiting blast radius for your systems failure domains, which is 150% the "right thing to do". Of course if we're getting pedantic, this is even close to OO the way that Alan Kay imagined it, than what the OP and GP talk about, and I don't consider that to be OO in the contemporary, colloquial sense of "everything that happened after Bjarne Soustroup invented C++"
I highly recommend this video for a more philosophical take on how to do "impure FP" without OO that is informed by a decade of industry experience: https://www.youtube.com/watch?v=yTkzNHF6rMs which is by Gary Bernhardt (of WAT fame)
> I look for the right tool for the job rather than some idealistic purity
This is all about right tool for the job. IMO, FP code is easier to read, easier to reason about, easier to maintain. I think it's a shame that FP gets this reputation for being 'about ideological purity'. I like using "working programmer's FP", and the FP that I use are built on designs that are driven by real, customer-use-case driven concerns and real-world constraints, and how to make life easier for programmers and operators.
Many of the methods on those organizational classes are implemented in a functional manner.
I rely on the class/instance pattern for working with a database. static class methods for actions that work on multiple rows, instance methods for single row interactions.
This works especially well in typescript where I can set private/protected/public
That said, I rarely use inheritance except when it's obvious - no nested class hierarchies or other such traps.
Thanks for the video, I'll give it a watch.
Why? The very best "OO" interactions I have with a database are via Linq which is a monad [1]. What it actually does is simply build the plan for what to do in the database and actually do the query at the last possible opportunity. Exactly how it would work in a purely functional setting.
[1 ]https://github.com/louthy/language-ext/wiki/Thinking-Functio...