S.O.L.I.D. Principle Implementation In Real Life Android Development
Hi,
As being a programmer we all must know about S.O.L.I.D. principle, I am explaining here implementation of S.O.L.I.D. in real life Android Development.
S.O.L.I.D. Principles are
- The Single Responsibility Principle (SRP)
- The Open-Closed Principle (OCP)
- The Liskov Substitution Principle (LSP)
- The Interface Segregation Principle (ISP)
- The Dependency Inversion Principle (DIP)
S — The Single Responsibility Principle (SRP)
A class only have one responsibility.
Look at example of Room DAO interface
Correct way of implementation is
O — The Open-Closed Principle (OCP)
Software entities such as classes, functions, modules should be open for extension but not modification.
Look at this code, violating OCP — we have save method to store some data but can i add two new type of storage without changing this code? I want to add SaveToCache() and SaveForSession(), it is not possible without changing in the code.
Now the correct way of implementation is
L — The Liskov Substitution Principle (LSP)
Child classes should never break the parent class’ type definitions.
In this case see how the LSP principle is violated in this scenario
Correct way of implementation is
I — The Interface Segregation Principle (ISP)
The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.
In this case we are using animator listener just to show you ISP violation, look at this code.
I want to use only onAnimationEnd, i don’t need other method in my code, so
Correct way of implementation is
in this case AnimatorListenerAdapter is a abstract class, i use this example just to keep everything within Android.
D — The Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend upon details. Details should depend upon abstractions.
Look at this code violating DIP and other principle as well
To implement a class that follows the Dependency Inversion Principle and can use the GoogleAdMob or the FacebookAudienceAds class to handle ads, we need to apply the Open/Closed (OCP)and the Liskov Substitution Principle(LSP). Now we have to introduce abstractions
Correct way of implementation is
If you enjoyed this article, please don’t forget to clap.
Happy Coding, Cheers!!