3 ms·
Except that interface are not supposed to have behaviors. Shape can lay itself out with regards to its enclosing rectangle for example. From my experience, us
by bsaul 13y ago
Except that interface are not supposed to have behaviors.
Shape can lay itself out with regards to its enclosing rectangle for example.
From my experience, using IS-A only works on simple concepts, and almost never on more than 2 layers. But it's still useful.
I suppose that if languages had the same "automatic function redirection" to sub-components, such as Golang, then people would use composition a lot more, though. That's actually the thing that seduces me the most about this language.
- derefr 13y ago> Shape can lay itself out with regards to its enclosing rectangle for example. How so? I mean, sure, Shape can declare, say bool is_inside(Rectangle enclosing_rect) ...but how would Shape know how to calculate that? It'd be an abstract method. All of Shape's methods would be abstract methods. Thus, a Shape is an interface: a contract an object makes with the system to say that it has a given API.
- kmkemp 13y agoThe template method pattern is a great example of how you might define some behavior for is_inside, without completely defining it.
- kibibu 13y agoBut this is an excellent example of where Shape can have concrete code in it though. is_inside is true iff the shape's bounds are inside the rectangle. So assuming you have a means to test rectangle bounds: bool is_inside(Rectangle enclosing_rect) { return enclosing_rect.contains(this.get_bounds()); } Now you don't need to implement cookie cutter is_inside methods everywhere, but rather the simpler get_bounds(). In fact, you can add is_inside after all your shapes are implemented and it will just work, as long as they have get_bounds. Maybe you want to add some sanity checking to make sure bounds never have negative width, so you implement get_bounds() in Shape, and implement get_left(), get_right(), get_top(), get_bottom() in the child classes. Now you don't have to add cookie-cutter assert(left < right) stuff everywhere, just in one place. Other similar ideas: if you write an "intersects(Point)" method on each shape, then you can pull a concrete implementation of sampling-based area approximation up to the base Shape class, and leave analytical area calculation to the children. This is useful if you are working with distance-field, parametric or noisy shapes, for example.