This violates Dependency inversion principle in SOLID programming, can someone explain why and refactor this to look correct? public class Computer : IPowerState { public bool IsOn { get; set; } public void TurnOn() { } public void TurnOff() { } } public class Button { public Computer _computer { get; set; }; public Button() { _computer = new Computer(); } public void Press() { if (_computer != null) { if (_computer.IsOn) _computer.TurnOff(); else _computer.TurnOn(); } } }
Reason :
In the code, the Button class uses the concrete Computer class. ****Therefore, it is still tightly coupled.
Dependency Inversion Principle(DIP): a high-level module should not depend on low-level modules. Both should depend on abstraction. So, first, decide which is the high-level module (class) and the low-level module. A high-level module is a module that depends on other modules.
In the above code, Button depends on the Computer class, so Button class is a high-level module and the Computer class is a low-level module. So, as per the first rule of DIP, Button should not depend on the concrete Computer class, instead, both classes should depend on abstraction.
I hope it answers your problem. Also, do upvote the solution.
Get Answers For Free
Most questions answered within 1 hours.