× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Maintain consistent loose coupling given complex inheritance

James Jensen
Feb 10, 2015
<p>I have a few observations. I'm hoping one or two of them will apply to the specific situation you're running into:</p> <ol> <li>It's often better to favor <em>composition over inheritance</em>. In other words, rather than having a <code>CitroenCar</code> and a <code>FordCar</code> that inherit from <code>Car</code>, you could just have a <code>Car</code> with a <code>Make</code> property to tell you which kind of car it is.</li> <li>Rather than basing functionality on what you know about specific types of cars, try focusing on <em>feature checking</em>. There are a few different approaches you can take. For example: <ol> <li>Make the objects implement feature-specific interfaces (<code>IHaveWindscreenHeater</code>).</li> <li>Make the main <code>ICar</code> class implement a <code>bool CanHeatWindscreen{get;}</code> property, as well as a <code>TurnOnScreenHeating()</code> method. This latter method could either do nothing or throw an exception in cars that don't have heating.</li> </ol></li> <li>The fact that you're calling your controller <code>FordController</code> tells me that you can no longer loosely couple this: You're declaring it to do stuff pertaining to Ford cars, so even if you manage to decouple it from the <code>FordCar</code> class in code, you're still conceptually tightly coupled. This may be even more dangerous than having tight coupling in your code. Following observation #1 above, you may want to just use a single <code>CarController</code> class that handles all your <code>Car</code> actions.</li> </ol> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23223979/Maintain%20consistent%20loose%20coupling%20given%20complex%20inheritance/23224580">Stack Overflow</a>.</p>
comments powered by Disqus