R
R
rxlrxl2015-01-25 17:08:04
Programming
rxlrxl, 2015-01-25 17:08:04

Extending the public interface in the successor, how is this solved?

Hello.
I’ll describe the situation right away, and then I’ll formulate a question.
There is a class Car, in which the fields are components Engine, Gearbox, Body, etc. with their public interfaces.
Let's say we want to extend the public interface of the Body component and add a retractable spoiler to the car body.
The solution that immediately comes to mind:
Ok, create a successor to Body, let's call it WingedBody.
This spoiler will be advanced based on some logic of the Car class, i.e. the deploySpoiler() method should be called by the Car class (or rather, its successor).
We create a descendant of Car called WingedCar, and then the question arises: how to use the new functionality of the WingedBody class? After all, we have inherited a field with type Body from the Car class, but we need WingedBody.
A few obvious solutions:
1) A head-on option - type casting, that is, downcasting from Body to WingedBody. Ugly and inefficient.
2) We create an additional field with the WingedBody type and call new functionality through it. Minus - you need to maintain the equality of both fields (the old one with the Body type and the new one with the WingedBody type must be the same object).
3) An improved version of the second solution. We create the IDeployableSpoiler interface, implement it in the WingedBody class, and in the WingedCar class we create a field with the IDeployableSpoiler type and not WingedBody. A more understandable solution, but still, we essentially produce extra fields.
It is believed that such a situation in real work occurs very rarely and is a design error. If you think so, then please justify it, because, as it seems to me, it is impossible to foresee all the functionality (and, accordingly, the public interface) in advance (and if it is either, then it is impossible to add a parent class).
The question has already been raised, but I will repeat for clarity. How would you solve such a problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
maaGames, 2015-01-25
@maaGames

The Car class has an IAerodynamics object container that contains all objects that affect aerodynamics. If you want - add a spoiler, if you want - body kits, if you want - you remove everything.

N
Nikita, 2015-01-25
@jkotkot

No need to use inheritance. Keep using aggregation.
The car consists of the engine, body and wheels. The body consists of doors, fenders, spoiler and so on.
Where there is no spoiler, we return null. Something like this...

A
Armenian Radio, 2015-01-25
@gbg

You can also make a class template car with parameters engine, gbox, and so on. And generate the necessary combinations of machines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question