What do YOU do instead of providing abstract base classes?

Thanks god.

Yeah. Pretty much. And we know that OOP doesn't work and we even know why OOP doesn't work.

The core unfixable vulnerability of OOP is LSP. It's often mentioned in the OOP tutorials, but never explored in depth — because if you think about it for 5 minutes you would realize that the whole OOP methodology is fundamentally flawed and couldn't be fixed.

LSP, of course, looks like this: 𝑆⊑𝑇→(∀𝑥:𝑇)ϕ(𝑥)→(∀𝑦:𝑆)ϕ(𝑦)

Or, in text form: Let ⁠ ϕ(x) be a property provable about objects ⁠ x of type T. Then ⁠ϕ(y)⁠ should be true for objects ⁠y⁠ of type S where S is a subtype of T.

Looks innocuous enough, right? Just look on the set of ϕ and then… but stop! Where and how can we obtain that list of ϕ? These are, obviously, not all properties imaginable (then types would be identical) and also that set is not empty (because then there would be no need for subtyping). OOP says: who cares, let's make it as flexible as possible and then we would, later, do something about that mess. Math answers: is you made you list ϕ non-trivial, expandable, and you have made your list of types expandable, too then have just made it fundamentally impossible to write provably correct programs. Not hard. Impossible.

That's not a theoretical concern, the whole Old New Thing blog is filled with examples of how people produce bugs because of that, some are hilarious, some are hard to imagine and fix.

And here the theory hits the practical side: how do you provide these ϕ, these properties provable, for your subclasses? Rust essentially gives two options that make the list trivial (math term, not random word): either limit number of classes (this would give you ADT, structs and enums), then for each ϕ (no matter how many of them) you can verify everything — or limit number of ϕ by providing trait with default implementations. List of default implementations is fixed, non-expandable, thus giving limit to list ϕ in another way.

So please answer the core question: do you want to limit number of subclasses or number of implementations of ϕ? This would give you an answer to where to proceed.

P.S. It's possible that the only way to create a useful UI is to demand that there are both unlimited number of classes and unlimited number of properties. That would just mean that it's impossible to develop UI in a way that makes to correct, bug-free. That would be sad outcome, to be honest, but I'm not asserting that it's not the only one: making good UI is hard and it wouldn't surprise me that a bug-free way to make it just simply doesn't exist.

Great solution, you put together the pieces very nicely! I'm glad to be wrong about my OO comment.

I agree that the standard formalizations of LSP are problematic, but I think you're complaining in the wrong direction.

The problem with defining LSP in terms of the PROVABLE properties of ALL objects of type T is that there are no such properties at all, except what the language enforces. The restrictions on subtyping that the language enforces are folded into the definition of type T, and that makes LSP into a useless tautology.

The way that I use LSP is simply that subtypes need to honor their supertypes' contracts, which of course includes a lot of things that are not spelled out in the syntax of the language. This is has implications for the design of both the subtypes and supertypes, and is actually very useful in practice.

It's not “the standard formalizations of LSP are problematic”, it's “an attempt to have your cake and eat it, too” is problematic.

OOP is based on fundamentally flawed idea that you may build everything on top of the system where some pieces are “sometimes same, sometimes not” without any formalization at all.

And we know, from experience, that it simply just doesn't work — not reliably, at least. That's not “minor problem with formalization”, that's an experience.

And while Rust's decisions to only give you two choices (either pick limited number of classes or limited amount of common code) may be too drastic… in practice it's the best choice I saw.

Not really. LSP doesn't say anything about what these ϕ, these “properties provable” are. Just “a set needed to prove correcess of your program”, presumably. And yes, it may even work like that for a finite, non-expandable, program… but that's precisely not what OOP sells!

When you build a library where user of the library may arbitrarily expand the list… it all falls apart.

But who decides what these contracts even are? And who decides when they are violated? Heck, how do you decide whether they are violated or not?

If you can arbitrarily expand both the list of functions that exist and list of classes that implement these functions then sooner or later you would hit a conflict when two developers extend your class hierarchy in two incompatible directions… usually when the new version of Windows or macOS changes the implicit assumptions that apps relied on.

IOW: this “theoretical weakness” is very much not theoretical, it has profound practical implications.

Another thing you could try is basically a "strategy pattern via generics".

Rather than having

struct MyFoo(...);
impl Foo for MyFoo { ... }

The upstream library provides

struct Foo<S>(..., S);
impl<S: FooStrategy> Foo<S> {
    fn from_strategy(s: S) -> Self { ... }
}

Then downstream you have

struct MyFooStrategy(...);
impl FooStrategy for MyFooStrategy { ... }
type MyFoo = Foo<MyFooStrategy>;

That way upstream provides all the methods on the type that are actually called, but in places where you would have called an abstract virtual in OOP, you call a trait method on the strategy field instead.

(And since the strategy type can be a ZST, having that field doesn't impose any space cost.)

This is what the clanker suggested, so I guess it's pretty common. It makes sense if the strategy pattern is what you really want, but in my case I ruled it out, because it makes it too cumbersome for the user to implement other traits on the resulting type, and because the unnecessary generic shows up everywhere.

I would say that these definitions actually don't have any practical implications, because almost nobody pays much attention to them.

Similarly, I have been writing software far too long to worry about problems with whatever kind of dogma you think OOP is or isn't based on.

I know what I want to write -- what I want to provide, and want I want to require in turn, what constraints I want to impose and what I'm willing to accept. OO languages these days have features that are generally pretty useful in expressing the things I want to write, and rust does too.

This thread is a pretty good example of an OO vs rust tradeoff. The accepted solution is pretty good, but I'm not really happy with the extra method exposed in the trait. The OO equivalent is also pretty good, but the way inheritance mixes overrides and callbacks together is a big mess. Neither is ideal, but in practice they both work fine.

I think this is where "abstract base class" is a limiting term because it's implementation-focused.

If you're using a ABC as mixin-style reuse then the strategy pattern is clearly bad -- but also arguably ABC is bad in OOP for that too because it creates a subtyping relationship.

The strategy-style approach here is definitely best for the "of course most of the traits are implemented by the upstream" uses of this. Depending how complex the strategy type it's even possible that you wouldn't be able to implement a trait for Foo<MyStrategy<...>> due to coherence too.

So as usual, these kinds of things end up in philosophy and goal conversations.

I would say that it does have practical implications. Immense ones.

Precisely. The end result: instead of something that's written, finished and released we have endless streams of service packs, updates and hotfixes for hotfixes that seems to never quite make things bug-free.

If by “work fine” is “it kinda-sorta works if you don't look on it wrong”. Are we doomed to forever continue in that cycles? Possible, but as I have said: it's a sad though to believe that there are no alternative. And as long as we insist in using OOP there could not be an alternative, because OOP doesn't have any solid foundations to stay on… that's why it's not included in Rust, actually: there were many attempts but they were all rejected because you couldn't make them sound… and it looks if it's fundamentally impossible to make OOP sound, at this point.

That is why “no one uses these OOP definitions”: because they are flawed.

Ah, IC. Well... I'm sympathetic to your cause. It seems to require a language that captures a complete definition of correctness, and a compiler that validates it.

We will have that eventually. We might already. But it's not OOP and it's not rust, and it sounds like something only AI will write for real.

The level of verification that I want from my compiler is a little more than what C++ provides and a little less than what rust provides, because I sometimes get pretty exhausted trying to make the borrow checker accept perfectly valid semantics.

Maybe, hopefully, that in between thing will be ... Rust. If it continues to improve the borrow checker with Polonius, view types, etc.

Not necessarily. Theoretical ability to create one is enough for me. Then you may write something that would be in use by billions of people and yet in 10 years would only have one or two known error (like what I did at my $DAY_JOB). Actual formal proof would be nice, but it's an extra.

There are many things that work like that: from quicksort and simple implementation of some algorithms to whole publishing system in the form of TeX plus METAFONT.

OOP never had such a stable foundation AFAICS and as a result we went from “number of errors in a program may be counted on one, maybe two hands” to “number of errors fixed and ones introduces this week is measures in hundreds if not thousands”.

Not if we would go into opposite direction.

Existing AI is great at finding and making mistakes, not so much with fixing them. It may improve with time, or maybe not… But the main issue is that we couldn't arrive there if we would insist that the ability to prove that code actually works is irrelevant.

Trying to work around the borrow checker in Rust is generally the wrong approach. The compiler and the code linter Clippy are there to help you.

AI is great at transfer tasks. It is poor at creativity. There are a few mathematical proofs that have been achieved with the help of AI. However, in these cases, the AI served more as a sparring partner than as the entity that actually provided the proof.

There are languages that demonstrate significantly greater correctness than Rust—for example, Haskell. In Rust, correctness is very often sacrificed for the sake of convenience. For example, a map in Rust is not defined via a parent trait, and an Option<t> is not a true monad, but rather an enum.

pub struct ElementBase;

pub trait ElementStorage {}

impl ElementStorage for ElementBase {}

pub struct Element<T: ElementStorage = ElementBase> {
    storage: T,
}

No base class needed...

They do, it's a consequence of Rusts explicitness. You and your users can easily avoid having really complex types everywhere though, simply by defining type aliases.

Exactly, you do a very right in my opinion, for example:

use crate::template;
use std::{collections::HashMap, error::Error};

pub trait WebPage {
    /// Returns a response content type
    ///
    /// text/html is used by default
    fn content_type(&self) -> &str {
        "text/html"
    }

    /// The method supposes to return a response load accordingly to the content type
    ///
    /// This method has to be implemented
    fn main_load(&self) -> Result<String, Box<dyn Error>>;

    /// Returns a vec of additional headers including cookie set in format name:value
    ///
    /// no additional headers returned by default
    fn get_extra(&self) -> Option<Vec<(String, String)>> {
        None
    }

    /// The method can modify hashmap used for a response content interpolation
    ///
    /// When no interpolation is required, the map should be cleared to avoid side effects.
    /// If an error happens during applying effects, a response with this error will be returned.
    fn apply_specific(&self, _page_map: &mut HashMap<&str, String>) -> Result<(), Box<dyn Error>> {
        Ok(())
    }

    /// Returns custom response status as a tuple: (code and description)
    ///
    /// None means use the standard response: 200 Ok
    fn status(&self) -> Option<(u16, &str)> {
        None
    }

    /// Outs an error response
    ///
    /// The method can be implemented for a response customization.
    fn err_out(&self, err: Box<dyn Error>) {
        print! { "Status: {} Internal Server Error\r\n", 500 }
        print! {"Content-type: text/plain\r\n\r\n{err:?}"}
    }

    /// The method has an internal implementation
    fn show(&self) {
        // => Result<(), String>
        match self.main_load() {
            Ok(page) => {
                let mut page_items = HashMap::from([("theme", String::new())]);
                match self.apply_specific(&mut page_items) {
                    Ok(_) => {
                        if let Some(status) = self.status() {
                            print! { "Status: {} {}\r\n", status.0, status.1 }
                        }
                        if let Some(extra_headers) = self.get_extra() {
                            for header in extra_headers {
                                print! { "{}: {}\r\n", header.0, header.1 }
                            }
                        }
                        print! {"Content-type: {}\r\n\r\n", self.content_type()};
                        print! {"{}", if page_items.is_empty() {page} else {template::interpolate(&page, &page_items)}}
                    }
                    Err(error) => self.err_out(error),
                }
            }
            Err(error) => self.err_out(error),
        }
    }
}

Generally only one method of the base class can be implemented, however it doesn't prevent you to implement any other method if you want.