Hacker News new | ask | show | jobs
by CrimsnBlade 3857 days ago
Stuff like this is fascinating to me. I'm by no means an expert in writing code, I'm very much a beginner, but the creative potential that is there has always drawn me in.

If one was going to learn OOP correctly in Java (or Python) from the beginning, where would be a good place to start? Are there any textbooks or good websites for this?

3 comments

The SOLID principles are all you need to know. [0] Then realize through them that inheritance as generally taught is actually a bad idea and use interfaces instead. Then realize that interfaces are just a weaker version of type classes and reach enlightenment.

[0] https://en.wikipedia.org/wiki/SOLID_%28object-oriented_desig...

I had this thought recently that inheritance was a bad solution to languages not supporting containers natively. And or a lame attempt at code reuse. (A root class is an API/Service with no versioning)
Is this in reference to the type classes as seen in Haskell or something else? I want to reach enlightenment but I'm stuck in Java for the time being.
Yes, as in Haskell type classes. Or Rust traits. Basically, anything that acts like an interface (defines a contract) but allows external definition. So you're not stuck wrapping your Integer in a ShowableInteger just to have an Integer that implements the Show interface.
OOP allows you to avoid code like this:

function makesound() { if( thing is a Cat ) return "meow"; else if (thing is a mouse) return "eep": else if (thing is a sheep) return "baa"; }

Code like this in an OOP language would be replaced by creating classes, such that the structure of the program implicitly executes the if else switch above, without you having to write it.

class Cat { makesound() { return "meow"; } }

class Mouse { makesound() { return :eep"; } } . . .

Then if all those classes inherit from a common animal ancestor, the calling code would simply say: animal.makesound()

This becomes very convenient when the program behaviour relies on a combination of two or more types.

In that case the if else example would have to contain nested and possibly repeated ifs (or calls to functions) to handle the logic for all the variations.

Note that inheritance in this example isn't to reuse code, just to establish the relationship between subtypes.

If you become tempted to use the type system as a clumsy code reuse mechanism, you will encounter alligators for sure.

Neither type of code is good or bad, just convenient for different purposes or not.

OOP is especially nice for writing simulations. See: https://en.wikipedia.org/wiki/Simula

> Then if all those classes inherit from a common animal ancestor, the calling code would simply say: animal.makesound()

Which of course throws an exception in the case of Monk (inheriting from Animal -> Human), as it has taken a vow of silence.