by freetonik · 2y ago · 0 comments
(In a way, even CSS is kind of OOP, albeit with very confusing overriding rules.)
When writing generic backend code in a language like Java, I often found fighting against OOP because the business logic is not necessarily mappable to "dog inherits from animal". And I can't change the business logic, so OOP has to give in. But when developing user interfaces, I am usually in more control, I am actually designing it, not observing directly from the business logic. And OOP forces me to have a more consistent implementation, which is beneficial for the user, because consistent UI makes it easy for people to get used to it, find the underlying logic in it, and start relying on it. If all links on all web pages would inherit from normal HTML href link (like it was designed in the beginning), we wouldn't suffer from those weird JS web apps where you can't open a link in a new page for example.
> there could be an element inheriting low-level behavior (HTTP/API call, etc) from a button and a high-level behavior (style/presentation, etc) from a visual class.
This becomes very messy very quickly, and you would need to clearly separate the concerns to make them non-expressible on either side. CSS and JS make this possible by being two different languages, one Turing-incomplete (in usual scenarios).
Textbooks have an example like "Dog inherits from Animal" as a way to demonstrate the concept of inheritance, but people took that as an invitation to become Linnaeus and create a hierarchical taxonomy of their domain.
It might be a useful exercise, actually, but it's rarely the best way to design software and you can do OOP (and do it better) with sparing use of inheritance (by replacing it with extensive use of composition).
Because OOP is somewhat equals to inheritance (or more strictly late binding + open recursion + self-polymorphism, inheritance is just one way to achieve that).
"delegating" is completely orthogonal to OOP, you can have delegates in any modular language, like ML. Saying "you need to use more delegates and less inheritance" basically equals to "you need to write less OOP code".
I'm struggling to understand this, could you give an example?
module type Repo = sig
type t
type user
val get_user : t -> name:string -> user option
val get_all_users : t -> user list
end
module LoggedRepo (R : Repo) : sig
(* Resulting module is of type Repo plus create function *)
include Repo
val create : delegate:R.t -> logger:Logger.t -> t
end = struct
type t = { delegate : R.t; logger : Logger.t }
type user = R.user
let create ~delegate ~logger = { delegate; logger }
let get_user repo name =
Logger.debug repo.logger "Get user by name";
R.get_user repo.delegate name
let get_all_users repo =
Logger.debug repo.logger "Get all users";
R.get_all_users repo.delegate
end
In languages like C it would be harder since they don't have notion of interface and implementation, so you would have to implement that as an object-like structure of function pointers and opaque structs for state.The point is, for delegate you don't need lately bound methods and virtual dispatching, i.e. oop, only the notion of interface and implementation supported (or emulated), and then you can create implementations that wrap another implementations.
Regardless, the inheritance remains an implementation detail.
[1]: https://docwiki.embarcadero.com/RADStudio/Alexandria/en/Inte...
That's because inheritance isn't really elsewhere, making it uniquely an OO concept (though I'm sure there are exceptions).
When people say OO is all about X, Y, and inheritance, well, X and Y are in most of the other languages too.
That's what OO is to me. Inheritance is nice for some things, but entirely optional.
I admit I would really like a 'delegate function call to <object>' construct, but excuse me for being dense, what composition are you referring to? Other than inheritance and delegation, what else is there[1] , and what would a suitable construct supporting it in the language look like? TIA
[1] (there is functional-style composition, but that's perfectly well supported in many decent languages like Scala)
Yeah, I'd love to see Kotlin's delegation[0] developed further and appear in other languages as well.
[0]: I admit I would really like a 'delegate function call to <object>' construct
One reason is that inheritance is strictly more powerful. When you delegate (compose), you can't modify the inner working of the object you delegated to, you can only wrap it. Often that's not sufficient. You want to actually customize the implementation in some way. OOP's inheritance is ideal for this, because the superclass can clearly define chunks of functionality that subclasses are allowed to either (a) replace entirely or (b) wrap or (c) provide (abstract methods).
This is a very flexible approach. With mere delegation you can only wrap, and only for method calls that originate outside the object, and only for public methods.
It's also clean. The distinction between what you must implement, what you can implement and what is for the user is defined in the type system and enforced by the compiler. Additionally you separate the interface for customizations from the interface for users (protected vs public), which keeps documentation and auto complete properly focused.
When combined with dependency injection and code generation it also allows third party frameworks and libraries to enhance the code you write in various ways, that remain mostly tucked out of the way but can be revealed in an IDE in an instant (and a good IDE will show visual hints that there are such customizations in effect).
The final advantage is that in some languages the implementation is highly optimized. On HN you'd be forgiven for thinking nobody writes virtual method calls since 20 years ago but in reality virtual method dispatch is so common in real programs that it's heavily optimized by both CPUs (sophisticated indirect branch caching) and language runtimes (PICs in fast VMs like Hotspot or V8). Composition is less well optimized.
Inheritance gets an overly bad rap on Hacker News, despite how prevalent it is. I think this is because it's so flexible you can easily make a mess with it, and some people have. Also the decision of Java to make all classes and methods open by default means overriding is often used as a hacky way to hot-patch libraries in the field, rather than as part of any principled overall design. Kotlin reverses that decision to some extent and so classes and methods are all final by default, unless a compiler plugin overrides that.
I also suspect the move to web development has had this effect, because in most classical OOP toolkits you are allowed or even encouraged to extend the UI by subclassing pre-existing node types. So you can make a custom button by subclassing Button or whatever. HTML is implemented using classical OOP designs, but mostly for implementation reasons that isn't exposed to the web developer who instead is expected to customize the controls purely through CSS and setting properties. If you want to make a custom button widget, well that's too bad, better learn React or something similar. So people just aren't exposed to the situations where OOP is useful because browsers weren't designed for UI, and the memory of why it was originally developed atrophies.
And some of it is just memeing.
OK, now tell me why I'm wrong.
In my experience, a relational model is the best solution for domain modeling precisely because it can directly represent circular dependencies without any sort of weird interface hacks, one off Init() methods, etc.
A practical example of this would be something like the domain of banking. In a bank, you generally have 2 major types of entities: accounts and customers. Accounts can have many customers and customers can have many accounts. Which type should "win"? In SQL you don't have to make this decision at modeling time - it is deferred to the caller and its specific view of the world.
You can certainly emulate this in OOP, but then you are stuck doing joins between collections manually.
What about cycles?
For example, "List all distinct customers from all accounts that are owned by customers who are members of some other subset of accounts".
CSS is also interesting, we mostly try to avoid the inheritance with scoping, utility classes and or css in js solutions as it becomes really hard to manage otherwise.
The right way to achieve the same and better results is interfaces / typeclasses / traits. They work pretty well in languages from Rust and Haskell to Typescript, Kotlin, Java, and even Go. (Go is a bit special because you don't even have to declare that your class implements an interface, as long as it actually has a set of methods with right signatures.)
Ideally, all public methods should only describe parameters and return values in terms of interfaces, and never as concrete classes.
If you need to take a big class and inherit from it to override one or two methods, it's a failure to compose the things correctly. These one or two methods usually are better off as their own entity which you can pass to the "base" as parameters. This both prevents proliferation of "god objects", increases testability, and improves build times (shallower dependency graph, yay).
Citation needed. I've seen interface heavy Go code, and without fail it's always unreadable garbage. Interfaces are best used in moderation, at API boundaries only.
Though most contemporary frameworks (react, elm, android compose) tend to prefer (functional) reactive programming.
In the 80s we called that "event-driven programming", and until threads became widely available, it is how all native GUI programming worked, more or less.
Inheritance makes for a very powerless form of logical programing. CSS is way more than OOP.
(Powerless is always preferred if it's sufficient, but CSS clearly shows a single hierarchy isn't sufficient.)
("We recommend defining components as functions instead of classes." at top of page at https://react.dev/reference/react/Component)
Although React tutorials start by saying your UI becomes a pure function of your app's state, React components do have encapsulated state. Any time you call useState inside a react function you're doing something that doesn't exist in real FP programs. Additionally React boils down to a way to create DOM elements, which are highly stateful C++ objects exposed to JavaScript, implemented using inheritance:
https://source.chromium.org/chromium/chromium/src/+/main:thi...
An HTMLButtonElement is a HTMLFormControlElement is a HTMLElement (and a ListedElement and a FormAssociated).
The rules for how you write code in React (or Jetpack Compose) violate even the most basic rules of the host language. useState defines or returns what is effectively an object field (it's data associated with that widget), but it looks syntactically like a local variable. It's not a local variable though because its value will survive the exit of the scope. Nor is useState a normal function call because there's a hidden invocation counter used to work out what state slot you want, which is why you aren't allowed to call it inside conditional branches and why loops need special handling.
So in React's "functional style" we can see that you're actually defining objects with encapsulated state, that register event handlers, that export properties and so on. It's just obfuscated to look like it's not OOP.
Meh, it's just a monad, hidden in a fake syntax so people don't panic.
> Additionally React boils down to a way to create DOM elements, which are highly stateful C++ objects exposed to JavaScript, implemented using inheritance
And C++ and JavaScript are just ways to run machine code, which is fully unstructured. But all of that is an implementation detail. React creates DOM elements because that's what you have to do to render UI in the browser, not because its creators think the DOM is a good idea.
> So in React's "functional style" we can see that you're actually defining objects with encapsulated state, that register event handlers, that export properties and so on. It's just obfuscated to look like it's not OOP.
It's not OOP - it doesn't have inheritance, most state is (idiomatically) immutable and exposed, and as you noted, React state does not follow the same rules as OOP state. While it's not fully pure functional (I'd actually say the React state model is a novel and interesting thing, that I expect may end up being a language feature in the next generation of successors), it's closer to functional than traditional OOP, and most of the benefits are those of a functional rather than OO style.
Jetpack Compose now, that is a pure implementation of the React concept all the way to the bottom. And their compiler plugin basically makes the React model a part of the language, so you could go take a look at that if you're interested in language-integrated approaches. There's essentially no OOP there and all state is handled with their useState equivalent. But as I write in another post it actually does suffer badly from that decision, in my view. The combination of the React concept with static typing doesn't mix well at all. There's an astonishing amount of copy/paste coding going on in the Compose landscape and worse, a new generation are starting to learn that this is normal and just the way UI code looks.
On the web the React approach took off due to the history of JS/HTML not really supporting proper componentization or indeed proper OOP until very late (arguably it still doesn't). Then the Android guys decided to adopt it to be more familiar to web devs and as a way to justify the huge expense of starting over, which they did need, the old Android toolkit has a lot of tech debt in it.
But I think we will come to regret that evolutionary path. Once you get past the convenience of being able to add/remove widgets by rebuilding the whole layout from scratch, it's just not a good way to express UI in statically typed languages.
Honestly for recent simple GUIs I've made for my own in house tools I'm still using JavaFX. Mostly because I always seem to end up needing a good table view, and because I happen to know it. If I were working with it a lot I'd end up maintaining a TornadoFX style set of wrappers but for simple stuff the plain API works OK.
Because I'm weird I'd probably use it for low-traffic web apps these days too, with JPro (jpro.one). Probably not for mobile web, and not for stuff where users are on high latency connections in general, but if the user has a nice big screen and a low latency connection I'd personally find it a lot easier and more productive than dealing with HTML and CSS. The results are indistinguishable for the user if you are careful.
(This change has little to do with OOP vs functional. React calls them function components, not functional. React has always used functional patterns, even in the class components.)