Need help in OOP
is there a better way to do this using OOP? this feels a bit inconsistent to me but im inexperienced in OOP and don't know if there's a better way to do this. would love some help!
42 Replies
I think a more OOP style approach would be for Shape to have
abstract function getArea(): number;
and the extending classes would define the properties themselves - it doesn’t really make sense for a rectangle to have a radius
Imo my library Sceneify is a decent demonstration of OOP with abstract classes and inheritanceinteresting
how would that look like in code? i've never seen an abstract function
It’s like putting a function on a trait in rust
You do everything except add the curly braces and body of the function
Funnily enough, this example uses the abstract class like a trait
hmm, it says abstract methods can only appear in abstract classes
need to learn this lol
Ah yeah you’ll need to make the class abstract too
An abstract class can’t be instantiated, but classes that inherit it can
like this?
Ye
The reason you’d do it this way is that now you can make a function accept
Shape
and know that the getArea
function will existohh that makes sense now
If you move all the properties from
Shape
to the extending classes, you could turn it into an interfaceyeah im trying to code up both approaches to this
one using adts and one using oop
huh
Would never have thought to do that example in that way but yeah it works
what were you thinking
Problem is that it couples
Shape
to the three specific shapesyeah you're gonna have to add other shapes manually
And if this was a library there’d be no way to add more shapes
You also lose being able to rely on object prototypes and
instanceof