125 points · by Tomte · 4y ago · 175 comments
The author is obviously an experienced programmer, so I suspect they've forgotten what the mindset of an absolute novice is like, and to start programming with zero prior exposure to the concepts.
For the novice being introduced OOP, the `Duck / Cat / Dog <: Animal` analogy is useful to demonstrate how things like inheriting methods and sharing behavior works. It helps one start to think in terms of hierarchies and the boundaries between "concepts" in code. Obviously, in 'real' code, you won't be writing much that involves a literal hierarchy of animal species.
That's not the point. A beginner knows what a dog and a duck and a cat are in the real world. The "a-ha!" moment is mapping real-world relationships into a brand new abstract environment called Object Oriented Programming.
When you've never written a line of code in your life, abstract things like "network protocols" and "file I/O" and "ImageDisplay" (which is neither an image nor a display) are confusing, and so frustrating, and so not useful for teaching a complete novice.
Don’t worry about Wimp Lo, he’s an idiot. We’ve purposefully taught him wrong… as a joke.
Composition is an infinitely better method to teach if you have to teach OOP. That way you don’t need to unlearn what you thought was the right way but is actually useless at modeling almost anything.
Look at a classically inheritance-based system: a GUI library. You'll see lots of inheritance. Buttons and Checkboxes extend ClickableThing, ClickableThing extends Control. Whatever.
And then you compose those controls on a Form.
Look at a classically composition-based system: a video game entity-component system. You'll see Monsters composed of GraphicsObjects and Animations and WeaponSlots and AIAgents.
And you implement all of those components in an inheritance hierarchy, or else your GameObjectThinger can't have a list of them that can grow or shrink at runtime.
So keep saying "teach composition, not inheritance". You might as well tell musicians to study "rhythm, not tempo".
Edit: A previous version of this comment was more wordy in stating this and mentioned that there are formal proofs to this effect.
I finally broke through it after being forced to write a ton of enterprise Java, which helped me come to realize that classes and objects are useful units of abstraction for encapsulating related sets of data and behavior, as well as finally grasping the idea of composition and the utility of things like dependency injection, but I could've avoided years of pain if someone had actually explained that properly with concrete examples of useful object-oriented code. Since then, I've seen the same conceptual misunderstandings over and over from beginners and all of it comes down to the fact that these inane `Cat extends Animal` examples are simply wrong.
> When you've never written a line of code in your life, abstract things like "network protocols" and "file I/O" and "ImageDisplay" (which is neither an image nor a display) are confusing, and so frustrating, and so not useful for teaching a complete novice.
The solution here is not to teach them something that dooms them to even more frustration and confusion in the future. Also, if someone has never written a line of code ever, why are you teaching them OOP? If someone can't yet grasp concepts like network protocols and file I/O, OOP is literally not useful to them. It's like teaching someone calculus when they haven't even learned algebra yet. Start with the basics and then build up from there.
I mostly agree in principle with the idea of building up a foundation. Going right into the deep end without decent guidance may leave one with horrible heuristics.
However, (IMO) a crawl->walk->run abstraction does not always work well. I hate to say "it's case by case," but pedagogy is not easy. Algebra, IMO, should be taught either near or with its uses (modern calculus being one of them). Otherwise, one may be learning a bunch of abstract concepts without much reification.
I derinitely agree pedagogy is hard. I have many thoughts about how the pedagogy of programming is deeply broken that are far too numerous to drop in an HN comment. I would say I'm not arguing for a purely linear approach so much as making sure there's actual conceptual understanding at each phase of the learning process. Teaching OOP before someone really grasps programming well enough to actually need it feels very premature, but there are lots of elements of it that can be sprinkled in throughout the learning process.
And inheritance can be expressed in terms of composition, the base class(es) can be represented as composition and delegation instead (with a protected interface, a public interface and the implementation details all tightly coupled behind a single name which is what really makes it so poor).
At first I was enthusiastic. Then I've realized that there might be better ways to solve problems than trying to fit everything in a "everything is an object" mentality.
OOP can lead to overly complex code, uneeeded abstractions and design patterns thrown on top of each other for no good reason.
There was a thinking that using objects you can model or imitate real life, but that is silly. And of course, programming doesn't deal with real life, but with bytes and instructions, data and actions performed on the data.
I still use OOP because most of the industry demands it, but when I can, I try to use a data oriented and a bit of a functional approach, even if I am using an OOP language.
This apparently goes back to part of the inspiration of Smalltalk (dataless programming). It enables you to create an ubiquitous language and radically improves your ability to structure a program in terms of reusable abstractions. It is fundamentally about hiding complexity and specificity on one end and only requiring or assuming what you _need_ to require or assume on the other.
In comparison to this, inheritance feels like a half baked implementation detail that got out of hand. Especially static inheritance hierarchies feel like the antithesis of object orientation. Pinning everything down and turning a codebase into immovable concrete.
- Alan Kay -
Other remarks from him about OOP are (paraphrased):
- OOP is a recursion on the notion of the computer itself
- The internet\Erlang is more OOP than java
His vision for OOP is something akin to distributed computing: Each object is a seperate computer with its own private memory that absolutely nobody can write to, it presents to the world an interface which is the set of all messages it can respond to (messages might or might not be asynchronous, and might or might not be unreliable in order,delivery,etc...). "Late Binding" because you have zero gaurantees about anything not explicitly stated in the object's contract, anything the object doesn't promise to respect will be violated, you better not depend on it. This is to give freedom to as much different implementation of the same interface as possible.
Two other analogies I encountered are
- Objects are like hardware ICs (their interfaces are the external pins and the type of signals the IC expects on them, their internals is the private hardware and signals that nobody is expected to inspect or modify)
- Objects are like seperate programs (their interfaces are the GUI/cmd the program presents and the set of all possible actions you can do, their internals are the executable code and in-memory data structures that nobody is expected to inspect or modify)
Inheritance actually precedes mature OOP, it was introduced way back in Simula-62, the proto-OOP language that wasn't a proper language as much as a simulation framework. Inheritance makes perfect sense in a simulation framework, because you're modelling a small world with a definite ontology that you can articulate and be sure of, the creators of Simula stumbled on it when they found they were repeatedly duplicating code verbatium. The analogies of Car<Vehicle and Cat<Animal make perfect sense, this is what inheritance is really made for, it's just that most real software isn't discrete event simulations with platonic ontologies.
If one squints hard enough, one could argue that we are continuing to move in his direction even so, slowly and in fits. But it's not because we have an Alay-Kay-OO language, and to the extent it is happening, it's not clear that it's happening at a level of abstraction that languages matter much with. When people use OO as a term today, it's a different definition.
All programming paradigms can do that, you are not making any particularly salient point about OOP here.
OOP doesn't mean that everything needs to be an object, but inheritance and shared behaviors are concepts that map neatly between the real world and the programming world, which is why OOP has been such a resounding success.
We have refined this approach now (e.g. using delegation over inheritance), but these basic concepts of shared behavior and reuse remain.
"Modeling the world as OOP", OTOH, is a load of bull.
… we use different sets of building blocks for modelling the world and modelling the software …"
1994 "Designing Object Systems"
https://www.google.com/books/edition/Designing_Object_System...
Personally, after working with vanilla JS, then jquery, I looked at angular and react. I liked react so much better
I do agree with most of his points though, which just so happens to be closely aligned with how I've ended up programming. I like to use interfaces, so my objects hierarchies are very shallow and use a lot of delegation, overriding few if any methods.
I also write a lot of free-standing functions, some long, when I feel that's best. I also mix in a fair bit of functional-like programming, especially when massaging data.
1994 "It should be clear to anyone that models of the world are completely different from models of software. The world does not consist of objects sending each other messages, and we would have to be seriously mesmerised by object jargon to believe that it does.
… we use different sets of building blocks for modelling the world and modelling the software …"
page 6 "Designing Object Systems"
https://www.google.com/books/edition/Designing_Object_System...
Yea, sure, we didn't gain anything.
Except milions of programmers being able to model complex real world into their software that powers almost everything now.
Even if it is "shitty" "hard to maintain"
then it at least works
If I need some functionality, I write a function and pass it a struct. I’ve yet to find a time when this approach is too limiting, or chaotic.
Even for interfaces, function pointers achieve that goal entirely.
I do miss type safe vectors, e.g templating. Thats above and beyond the most common thing I miss.
There's a certain conceptual and implementation elegance to OoO so I understand why it became popular. But in practice all the new languages moving away from it are doing so for good reason.
`thing.doWork(arg)`
`doWork(thing, arg)`
`doThingWork(thing, arg)`
The first example is marginally more readable IMO. The second one sucks from a human perspective because we don't immediately know (unlike the IDE) that the function signature only accepts Things. The last one addresses this but is even longer, and we still have to mentally unpack the args.
IMO there is not much profound about OOP, but it can lead to slightly more readable code if used appropriately.
I can admit though that from an IDE point of view having auto-completion upon writing thing and typing the dot and seeing the results is very useful, whereas there is nothing (as far as I know) that comes even close in functional languages where the second example is more typical.
Functions can be invoked in at least 3 different ways or a mixture of the three
1. Prefix - C style f(x,y,z)
2. Infix - x + y; x.f(y,z); a join b
3. Post fix- (x,y,z) $ f
Infix is the best style in most cases, OOP accidentally helped programmers use a more readable infix style.
A lot of the benefits of OOP can be had by allowing good infix invocation support and interface support in an imperative non OOP language. Might as well throw in generics.
Long function invocations are an annoying consequence.
I feel like classic OOP is a mistake because you're binding data objects with functional objects. The latter being a collection of functions that performs operations on the former.
If you break them up you can have multiple widgets for dealing with a data object. Each of them with whatever dependencies they need and nothing else. I feel like this style of programing has become more important because it fits in the the idea of computing as an assembly line. Passing data through a data pipelines. Steps which often happen on different processes or machines.
Dependency injection is also really really useful for clean C code.
I've seen it all. Prius extends Car extends vehicle extends motor extends ...
Right within the first five minutes of the interview.
But I also think these old "a bike extends a " tutorials were the most frustrating thing in the world and made no sense to me when I was trying to learn OOP in the first place. From my memory, I recall all the examples I could find were absolutely nonsense but blogs were full of posts with lots of non-real-world about connecting web requests things to a DB code and lots of "yeah it's just like a person is-a mammal which is-an animal which...".
It wasn't until I wrote some c++ and looked at how it worked in the heap and stack before I started to understand it better. Then later I learnt about SOLID and discovered that you almost never really want to use extension in practice (at least in the problems I worked on), except for things like interfaces in places you expect (and plan to have, and even better if you already do have) a reason for variations in sub-types that have the same contract, or need to cross system boundaries.
I almost always want to use composition. I will use extensions but this should be really specifically be selected for a few key points.
And that brings me to a topic that's entirely different but also very relevant: job interviews bring interviewer-biases with them.
If you run into an old-school interviewer who would do exactly that "Prius extends Car extends Vehicle, etc." nonsense, but you don't know it, they would rate you negatively.
If you run into someone who is just in love with functional programming, you'll lose any OO implementation.
If you run into someone who doesn't like it when you ask questions, you'll lose. If you run into someone who doesn't like you asking questions they don't know the answer to, you lose.
And if you get sent a 3-hour long Hackerrank or Leetcode algorithmic test, everybody loses.
Tech job interviews are just horribly biased and the game is won if you read your audience correctly. And even then, if the other person is a racist, or just doesn't like your face, or had a bad day, or feels threatened, or disapproves of how you write "Javascript" instead of "JavaScript", you still lose.
So don't project programming ideals you don't believe in. If they can't reconcile different opinions, it's their problem. You won't have the conviction or experience to do it convincingly anyway.
The exact example the grandparent used was essentially a wrong answer, so our "old-school interviewer" (that sounds kind of ageist doesn't it?) marking us down for not using it is a bad thing.
An interviewer who loves functional programming and doesn't communicate any preference then marks you down for not reading their mind is someone to avoid.
An interviewer who punishes you for asking questions is a huge red flag and you'll be dodging a huge bullet.
I'm a self-taught dev so I definitely have some thoughts on how tech interviewing goes, but an interview runs both ways. I'd much rather miss out on a job because the other person was racist or they hate when people ask questions, than to end up working with them.
I think this is a different challenge related to the "background" hidden context: training interviewers. I think the "foreground" discussion point ("please make me a car") is way less relevant than the skill of an interviewer.
For about a year I tried this with every candidate: literally tell them what I am looking for in the interview and what is on my scorecard. Nobody asked any questions even once.
That's actually a win in your book, not a loss!
It takes a brave interview candidate to say "the best solution depends on the exact nature of the problem - and your problem doesn't make any sense so there's no valid solution".
I got that a few times and it's a good sign I have a senior candidate.
The real-world use case is simple when you imagine that I want to get a JSON payload describing different car configurations, possibly for a "car configurator" on a sales website, or perhaps for a videogame where there are different cars with different attributes at random. Once I go from "make a car" to "give me some json" everyone started to see it's as a less fictitious problem.
> Prius extends Car extends vehicle extends motor extends
The problem isn't that it's too in-depth, or too overbuilt, that answer is as close to objectively wrong as you get on a pretty open ended question and I'd imagine only an extremely junior developer would come up with that.
For example, you could maybe argue that a model of car extends a specific car. I'd expect an experienced developer to favor composition over inheritance at that stage, but that's open to debate.
But if a Vehicle extends a motor, does a motor extend a piston? Does a wheel extend a lug nut?
At that point you're moving away from "arguably correct" to just plain failing to answer the question. It shows they don't know the difference between composition and inheritance.
> It takes a brave interview candidate to say "the best solution depends on the exact nature of the problem - and your problem doesn't make any sense so there's no valid solution".
You're free to ask questions, we're supposed to be trying to collaborate. I don't think it's "brave" to instead say "your problem doesn't make sense". Shows more hubris than anything.
How is it any different than a systems design question?
You can’t add code to ducks.
You can’t refactor ducks.
Ducks don’t implement protocols.
If I got asked this question I'd probably spend the whole interview inquiring about the purpose of the modeling. It's for a simulation? What info do you want to get from the simulation? It's for an ERP app?I don't have problems with simple tasks which are not real-world but abstract something from the real-world use cases. The problem with "model me a car" is that it abstracts nothing.
Also for the most real-life purposes of modeling a car factory you wouldn't even have a "Car" in your object hierarchy.
It wasn't until I started trying to make a simple video game that these concepts made sense: an "Enemy" class could have properties of health and speed that a "Boss" or "Minion" could inherit from, etc.
Virtual functions are about implementation: a derived type that overrides a virtual function does so specifically in order to deliver a specialized implementation.
The degree to which your class's virtuals match its public interface is an exact measure of how bad that interface is, as an OO abstraction. If your class was doing enough work to earn its keep, it would be presenting an interface in terms the client wants to see. Those are implemented for variant internal representations by composing calls to one or more private virtual interfaces.
The above is true about OO subsystems. But not all uses of virtual functions are about OO. Virtual functions are a mechanism. Anywhere the mechanism is useful, it is OK to use it, OO or no OO.
Java offers no other organizational facilities than OO mechanisms, so there you have little choice but to use them everywhere. In problems not suited to OO solutions, use of virtual calls may have nothing to do with OO, and none of the OO rules need apply: if it works, it works.
Any language that offers only one kind of abstraction is a very poor and limited language. Calling it "pure" should not fool anybody. The world is complicated and demands many kinds of tools. Any one will only match certain aspects of certain problems.
I wish someone had told me this when I first started coding. I wasted so much time building pointless hierarchies based on ontology rather than DRY.
I speculate that if we think of our hierarchies as tools, they say at least as much about our own brains and the problems we’re trying to solve as the do about the domain.
Which is fine, tools exist as levers for the mind. But we shouldn’t confuse them with reality. The map is not the terrain.
The real art is maintaining the balance between abstraction and pragmatic simple code.
There are aspects of DRY that are worth pursuing (like reducing the number of places you need to get things right) and some that aren't worth pursuing (thinking you reduce the amount of work by re-using code heavily). For code to be reusable you have to be sure that developers only have to care about its interface. Implementation inheritance often doesn't do that. I've worked on projects with people who were obsessed with DRY and made heavy use of implementation inheritance, and the projects inevitably needed extra work to untangle a brittle mess with lots of surprising behaviors.
In fact, if you think of Go as an OO language (which I guess many won't), it has all the things you actually care about from OO. It doesn't have inheritance and you don't explicitly declare that a type implements some interface (). Since there is no inheritance of implementation you are forced to use composition, which is what people tend to end up recommending after a few years of fighting with OO code that has been written by people in love with a Linnean hierarchies and complex approaches to DRY.
(
) There are tricks to accomplish this, for instance creating a New() function that returns an interface type, which will make the compiler ensure you implement the interface).Yeah. Exactly. Which is why Dog extends Animal. It has a set of common features (code/behaviors, and data like number of legs, amount of fur, and so on). It is a really good analogy and a really good point to give someone an idea of why you would use inheritance. It requires absolutely no programming knowledge, and best of all, it's not difficult to imagine cases where you might actually use it. c.f. basically any game with dogs in it where they're a subclass of NPCs.
And the same for Car extends Vehicle. A vehicle can have any number of wheels and any number of doors. A car can have any number of doors but it always has 4 wheels. All cars move in approximately the same way, while vehicles can articulate or skid-steer or ...
Just because something is simplified does not mean it has no value. And just because *you* would not use these designs in *your* life does not mean others wouldn't. As TFA says: "unless they are talking about writing a clone of The Sims".
Does that mean zero doors and zero wheels? Because a jet ski is surely a vehicle, right, and it has zero wheels and zero doors.
Likewise, what about a cable car (aerial lift)? It has doors (maybe), but probably not an internal engine. It's definitely a vehicle, but it has almost nothing that's similar about it compared to the car (automobile) you described earlier. If it where a class, the "vehicle class" could really only meaningfully have some attributes related to transport (like human/cargo capacity) and some methods around movement in the most general sense. If we keep breaking this down, we'll find a huge taxonomical network, a vast sea of interlocking Venn-diagrams of attributes and capabilities. This is the corner that those OOP tutorials force people into: trying to turn a network into a tree, and it doesn't ever really work (at least not without awkward compromises).
Sure, for a beginner who's never grappled with trying to map concepts to things, this can be a nice contained way to start. Eventually though, that beginner will need to learn some the next levels of more general thinking; e.g. one where they can start modeling interfaces/protocols and their relationships.
Except even in game design it's a bad idea once you get more than a handful of entity types. https://gameprogrammingpatterns.com/type-object.html
https://en.m.wikipedia.org/wiki/Reliant_Robin
https://en.m.wikipedia.org/wiki/Piaggio_MP3
What shall we do with them in our class hierarchy?
What I got as a side-effect was a bunch of re-written code. And I wondered:
Maybe OOP is a terrible paradigm. Maybe the designs that come out of it are so awful that it causes people to rewrite code, over and over. Re-examined systems are often better than first attempts. Once you reimplement something five or six times, you've probably explored most of the problem space and are pretty good at it. It's even likely that you are thoroughly sick of the project and just want to get the stupid thing done and shipped. (Yeah, your PMs and entire management chain just smiled behind your back).
In other words, it's Brook's "plan to throw one away, you will anyway" in action, while telling your boss that you had to rewrite your framework again because it didn't handle the flightless, swimming bird scenarios.
So it helps to compare the old ways to the new ways side by side, with a real world example, to understand why the new ways are better.
It's like listening to a conversation about cars where someone says they hate cars because you have to figure out a manual choke and the many inner tube failures.
Do people still use these crazy inheritance trees? I haven't encountered it since the early 2000's.
EventTarget -> Node -> Element -> SVGElement -> SVGGraphicsElement -> SVGTextContentElement -> SVGTextPositioningElement -> SVGTSpanElement
And the whole tree could be described as "crazy", but it does actually make sense.But inheritance is just a shit feature imo. Situations where it would be beneficial are extremely rare. I generally just pretend it doesnt exist. There are much better alternatives to it for most situations (eg. composition, build a class from other smaller classes that do one thing)
I think this is also the better approach, making inheritance something you have to explicitly design for instead of a way to monkeypatch almost everything.
You can with "new", no?
public class Foo
{
public void Say() { Console.WriteLine("Foo!"); }
public void Think() { Console.WriteLine("I;m thinkin about thos beans");
}
public class Bar : Foo
{
new public void Say() { Console.WriteLine("Actually, Bar!"); }
}
So with Bar we have inherited Think(), but have overridden Say(). Ok technically the MSDN docs will say that we've "hidden" the inherited method Say(), but the effect here is that we've overridden something not marked "virtual"edit: Oops yeah I'm talking rubbish, see replies for more info :D
Once I have all these really nice tiny functions, Its trivial to reorganise and replace them.
Though I find classes also very useful, a class is mainly a bucket that you put functions into. Ideally a class is a black box that does one thing. All the functions needed to do that thing are in the class and also any relevant fields. Not being able to have fields in there would be counter productive. It's just so handy to have all the functions + fields that govern this one element of your game all in one place.. When you need to make changes everything relevant is one place, and that place also functions as a black box that the other elements dont know about. So to change one feature in the game u just change or replace that one class.
Just looking at the functions, nice maintainable code would look identical in a functional or OO language. I think the big differences between functional and OO are actually not important. I could put functions in a class, or just together in the same file. Putting certain functions and fields into this same bucket is just a convenience and its intuitive to understand imo. Like I said in 6 months time when I have to change feature X I know where to look.
It's clear that OOP in the sense of "Car extends Vehicle" is not a good idea, yet the classic OOP languages go out of their way to support this kind of programming. Meanwhile the alternative approaches require you to jump through a bunch of hoops or apply convoluted "design patterns". Writing good, modern "OOP" you are often fighting the OOP language! Things are getting somewhat better (e.g. Java Record types) but perhaps it is time to admit these languages just aren't a good fit?
Add on the fact that people somehow seem to think Alan Kay has some insights (even if they can never tell you what they are), and Bob's your uncle.
What do you mean by "delegation" here?
It's not a bad base for UI programming. There is quite a lot of functionality that is suited to the OOP paradigm.
As an example, if I want to use composition in C# using ASP.NET, I simply inject the class I want to use into my new class using the built-in DI. This is as simple as extending the class.
- Discriminated unions
- Immutable data types (records)
- Free functions (or modules of free functions)
- Software transactional memory (STM), atoms
- Ad-hoc polymorphism (traits)
- Custom operators (used sparingly for building DSLs)
- List comprehensions
Instead we get anti-features like automatic properties, implementation inheritance, events, object initializers, etc...
there are
>- List comprehensions
Enumerable.Range?
>- Custom operators (used sparingly for building DSLs)
Could you please show what kind of DSL you'd want to write?
As a dev you just use whatever features u like and can safely ignore the majority of them. Its very non-prescriptive unlike some languages where you must do a thing only one way.
Eg. Inheritance is pretty much terrible, I just never use it. Same way I try to not write bad code and instead write good code.
Also sure you need to put functions in classes, but thats fine, classes are just buckets for code. In any language you need to put your functions somewhere eg. in a text file.
* That has a hardcoded list of strings baked into it
* Accepts as inputs a filename (but can be empty) and a substring to search for
* At runtime, either (a) (if filename empty) iterates over hardcoded list of strings, or (b) opens file and iterates over lines in it
* For each string / line, if contains search string then output to stdout (and maybe also increment a counter).
It's very artificial but does allow the basic idea of OO to be illustrated and it's far less code than a GUI example. You have a base class and two derived classes that really do have a different mechanism, and even have different state (file handle or integer index). The program logic is also quite decoupled (the class interface is not tied to the fact you're doing string search).
You could solve the problem without classes by reading the whole file into the same list structure as the hardcoded strings, but that aspect is actually quite nice because you can present that first and then ask what to do if you want to avoid that unnecessary memory usage. It's also nice that you're illustrating a really common OO pattern (iterator).
The only slight downside is that some languages make this easy to do without (explicit) classes e.g. Python generator functions. But you can add a footnote that they exist and this is just to illustrate classes - it still beats the abstract examples.
static void Main(string[] args) {
var filename = args[0];
var needle = args[1];
var linesToProcess = filename != '' ? File.ReadAllLines(filename) : HardcodedLines;
ProcessLines(linesToProcess, needle);
}
static void ProcesLines(string[] linesToProcess, string needle) {
// lines-processing code...
}
into something like static void Main(string[] args) {
var filename = args[0];
var needle = args[1];
var linesProvider = filename != '' ? FileLinesProvider(filename) : MemoryLinesProvider(HardcodedLines);
ProcessLines(lineProvider, needle);
}
static void ProcesLines(ILinesProvider linesProvider, string needle) {
var linesToProcess = linesProvider.GetLines();
// lines-processing code...
}
would still need some justification, IMO: what's the benefit of giving ILinesProvider to the ProcessLines instead of just string[]?If your GetLines() is returning a string[] then I agree there was no benefit. But that's not what I meant. As I said, I'm imagining the base class (ILinesProvider) to have an iterator-like interface. So, rather than string[] GetLines() method, it would have a string getNextLine() method that you call in a loop. That way, with the file, you don't load the whole thing in memory (as I also said).
If your GetLines() method is returning an IEnumerable<string> (since this seems to be C#) then this is the problem I mentioned at the end of my comment - the base class I'm imagining is similar to an existing base class in the language, and it's confusing to write your own similar-but-slightly-different version in an example. But I think it's best to do it anyway and explain it away in a footnote. (But my ILinesProvider wouldn't return an IEnumerable, like in your snippet - instead, ILinesProvider actually is the iterator (but with a slightly different interface).)
The suggestion of GUI widgets is certainly better and more concrete; although it's skating dangerously close to "Circle extends Ellipse" and "Square extends Rectangle" territory! (e.g. https://softwareengineering.stackexchange.com/questions/2381... )
- A base class and its implementation(s) must never be written by the same person.
Obviously a bit of a strong opinion, but inheritance should delimit layers of abstraction, technically separating the responsibility of developers.
Yep. That would be like having immutable lists which implement List which has an "add" method. Obviously that would be too stupid for a sensible programming language.
Compare:
> If B and C are subtypes of A, then List<T> must be invariant over T since List<B> should not be a subtype of List<A>, which can contain both B and C.
with:
> List<Cat> can't become List<Animal>, because you might add Dogs to that list!
I've thought about this for quite some time and couldn't come up with anything that strikes a nice balance between simple and actually useful.
I admit I taught intro to C++ and used shapes as an example. I spent a few weeks building a little "ASCII render" thingy with a 80x30 "canvas" where each character is a pixel. Then you could place Shapes on the canvas and the shape would decide whether a given pixel was contained() inside of it.
I remember my first OO class where the car analogy was proven to be bad using the existence of the El Camino.
Goodbye, shitty Car extends Vehicle object-orientation tutorial (2011) - https://news.ycombinator.com/item?id=21298341 - Oct 2019 (101 comments)
Goodbye, shitty "Car extends Vehicle" object-orientation tutorial - https://news.ycombinator.com/item?id=2914405 - Aug 2011 (128 comments)
Inheritance in OOP languages is used to either for interfaces, or for tacking on data and maybe functionality because you are too lazy to implement out composition instead.
"You can’t fake the ability to turn a duck into a penguin by moving its duckness into an animal of some other species that can be replaced at runtime."
See, for example, section 3.2 in https://www.econstor.eu/obitstream/10419/66819/1/717744094.p...
Modern multi-paradigm langues do a much better job of letting you use OO when OO works, functional when functional works, etc.
You should use the tool that works when it works. I do plenty of functional and OO programming in ruby, declarative programming in SQL, mostly functional style in JS. There are plenty of places where each one works great.
OOP wasn't meant to be used by professional programmers ever, but this is always always forgotten. Why do we still talk about OOP when it comes to professional / full-time programming? OOP was always meant to be about providing end-users a way to create programs & dynamic behavior without becoming full-time programmers.
- http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay...