0% found this document useful (0 votes)
2 views17 pages

SOLID Design Principles

This document outlines a course on SOLID principles in Java, focusing on their application in enterprise application development. It details learning objectives, outcomes, and the importance of each principle: Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. The course includes practical examples, theoretical materials for self-study, and quizzes to assess understanding.

Uploaded by

Gaurav Mathuriya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

SOLID Design Principles

This document outlines a course on SOLID principles in Java, focusing on their application in enterprise application development. It details learning objectives, outcomes, and the importance of each principle: Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. The course includes practical examples, theoretical materials for self-study, and quizzes to assess understanding.

Uploaded by

Gaurav Mathuriya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SOLID PRINCIPLES IN JAVA

This course offers a comprehensive and detail-oriented treatment of the Solid Design Principles for developers
interested in implementing these principles to develop enterprise applications.

Learning Objectives
Engineers would learn by completing hands-on activities:
1. Understand how to break applications into smaller classes and modules
2. Learn how to track down and fix problems easily
3. Learn to make changes to the codebase without causing unintended consequences (causing other
application modules to break)
Learning Outcomes
By completing these topics, you will be able to:
1. Implement various applications into smaller classes and modules
2. Define interfaces for classes, rather than forcing them to implement too many methods
3. Develop non-changeable working code, develop code for extension and deploy changes to production
faster
4. Develop classes that are extensible without any replacements of existing classes
5. Define multiple interfaces to reuse it in multiple classes (i.e., segregating interfaces)
6. Develop applications which make every class loosely coupled

The approximate time to pass the topic is approximately 3 Hours.

Introduction
In Java, SOLID principles are an object-oriented approach that are applied to software structure design. These five
principles have changed the world of object-oriented programming and changed the way of writing software.
Achieve high quality, well-organized and maintainable code. By following these principles, you can create code that
is easier to understand and more resistant to change.

What is SOLID acronym?

S: Single Responsibility Principle (SRP), O: Open closed Principle (OSP), L: LISKOV substitution Principle (LSP), I:
Interface Segregation Principle (ISP), D: Dependency Inversion Principle (DIP)

Benefits of Solid Principles

 Ease of refactoring. Software changes over time


 Extensibility
 Debugging
 Readability
 Single responsibility principle

Let’s discuss each principle in detail Banking scenarios.

Single Responsibility Principle (SRP)


This principle states that a class must have one responsibility to change. If you observe the image below, you will
see that it violates the SRP principle.

Here we are trying to create a Bank Account by performing the services below:

1. Sign up for a new user and generate user id.


2. Send notification with link to user email to finish user setup
3. User clicks on the notification link to set his password and he will be acting as a user
4. Once the user is created, the system will generate his account number
5. Finally, a User Account will be created

Let’s see the code below to understand it better.


If you see the above class, it has 3 responsibilities (first one is generating USERID on signup & generating account
number, second one is sending notification, third one is create/save User and UserAccount in database) but SRP
states that class/function must have single responsibility. We will try to fix this by the solution below.

Solution (Segregate these functionalities to different classes)


1. For signup functionality, we must keep the user details somewhere statically and generate user id till sign-
up activity is finished. A notification email is being sent to the user to finish the sign-up activity by setting
the password for his account by clicking on the link given in email and once done he will be an active user.
Once he is an active user, System will generate account number for him automatically by calling third
party API. So, you can segregate these 2 methods in one class. So that it takes care of generating user id
and account number. We can do something like below.

User class model will look something like below. Instead of multiple parameters we can create respective fields
and keep them in User class so that instead of multiple parameters in method, we can simply keep User as
parameter.

2. Sends notification to his email but in future if notification needs to be sent to his WHATSPP account to
finish his sign-up activity, implementation will be changed. We can do something like below.
3. User Creation and User Account creation – It’s database activity. We can do something like below.

So, we grouped all these 3 responsibilities to 3 different classes. Finally, we can state that each class has a single
responsibility to change.

Please find the application link for full implementation in Solid-Design-Principles project inside srp package.

Open-Closed Principle (OCP)


This principle states that class must be open for extension but closed for modification. If you observe the below
image, you will see that it violates OCP principle.
Solution
We need to create interface for profile like below.

This LoanProfile needs to be a parameter for calculateDiscountPercentage(LoanProfile profile). Now your


LoanDiscountCalculator will never change even if new profile class gets added to our application. The code will
look something like below.

Finally, We can say that LoanDiscountCalculator class having calculateDiscountPercentage(LoanProfile profile)


method is open for extension but closed for modification.

Please find the application link for full implementation in Solid-Design-Principles project inside srp package.

Liskov-Substitution Principle (LSP)

This principle states that child must be substitute of parent class means you have to override all the methods from
parents and use it in child class but if you simply override parent class method in child class and do not provide any
implementation then child is not a substitute of parent. If you observe the below image, you will see that it violates
LSP principle.
Here in the above image, there is constraint check for BankClerk child class to apply for extra discounts in
BankingApp class in above image.

Solution
We need to change our child class BankClerk like below. So that in BankingApp class we can remove the check for
BankClerk child class to apply for extra discount.

BankingApp class BankClerk class

Finally, BankingApp does not have a check for BankClerk to apply for extra discount. Everything is segregated as
BankClerk child class overrides the Parent class BankCustomer getDiscountPercentage() method and then calls its
another method applyExtraDiscountForBankMembers() method from overridden method of child class
BankClerk. Now we can say child class (BankClerk) is a substitute for parent class BankCustomer.

Please find the application link for full implementation in Solid-Design-Principles project inside srp package.

Interface Segregation Principle (ISP)

This principle states that Clients should not be forced to depend upon interfaces that they do not use . If you
observe the below image, you will see that it violates ISP principle as it forces the implementation classes to
override the methods even if you are supporting that operation/functionality.

Here in the above image, we are overriding operations/functionalities that are not required as part ATM or Loan
classes. This states that we are forcing both the classes to override the methods even if we are not providing any
implementation. This is a violation of ISP principle. No class must be forced to provide implementation if they do
support or use.

Solution (Segregate or split interface functionalities to respective interface systems)


We need to split our operations/functionalities into separate interfaces so that if we need to support the
operations, we can implement that interface with our respective implementation classes like below.
See the below implemented classes. Now we will not be forcing any of our ATM and Loan classes to override
unsupported operations. ATM and Loan classes will look something like below.

Please find the application link for full implementation in Solid-Design-Principles project inside srp package.
Dependency Inversion Principle (DIP)

This principle states that high level modules(class) should not depend on low level modules both should depend on
abstractions. If you observe the image below, you will see that it violates DIP principle.
Solution
So, we need to make our NotificationSender (high level module) class to depend on abstraction (i.e., means on
interface) instead of depending on a class and by doing this the NotificationSender will automatically send
notification using the right client (MobileNotificationClient or EmailNotificationClient or
WhatsAppNotificationClient). We can do something like below.

Now the NotificationSender(High level module) class is dependent on NotificationClient(which is an interface). So


now we are not depending on low level modules (means classes) instead we are depending on abstraction (means
interface NotificationClient). Below are various Clients used to send notifications to mobile, email & WhatsApp.
Now we can use create appropriate Client class object and pass the created object to NotificationSender
constructor and our NotificationClient in NotificationSender class will automatically know that which type
notification it must send to user. You can do something like below.

In the above NotificationApp class, we are sending Email notification to user/customer since we created
EmailNotificationClient object and passed it to NotificationSender constructor. So now NotificationSender will use
appropriate NotificationClient to send notification to user/customer.

Please find the application link for full implementation in Solid-Design-Principles project inside srp package.

Theoretical materials for self-study


# Curated Link to access Time to learn, Mandato Which Comment
content the content min ry or learning from SME
Name Optional outcomes to
does it students
cover?
1 Solid Design https:// 90 Minutes M 1 You will
Principles [Link].c 2 learn about
om/solid- 3 the all the
principles 4 Solid
5 principles
6

2 Solid Design https:// 90 Minutes M 1 You will


Principles [Link].c 2 learn about
om/design- 3 the all the
principles 4 Solid
5 principles
6

Quiz
Question 1.

Final Assessment: Yes


Concerning the solid principle
which of these is odd?
Correct answer Distractor(s) Correct feedback:
 Single Reconstruction  Dependency Inversion Single Reconstruction principle
Principle Principle is odd because Single
 Liskov Substitution Responsibility principle comes
Principle under SOLID design principles
 Interface Segregation Incorrect feedback:
Principle Please read about the topic
from the above What is Solid
acronym section

Question 2.

Final Assessment: Yes


A specific form of decoupling
where conventional
dependency relationships
established from high-level,
policy-setting modules to low-
level, dependency modules are
reversed for the purpose of
rendering high-level modules
independent of the low-level
module implementation details.
High-level modules should not
depend on low-level modules;
both should depend on
abstractions
Correct answer Distractor(s) Correct feedback:
 Dependency Inversion  Open/Closed Principle Dependency Inversion principle
Principle  Liskov Substitution states that a class must depend
Principle upon abstraction.
 Single Responsibility Incorrect feedback:
Principle Please read about the topic
from the above Dependency
Inversion Principal section

Question 3.

Final Assessment: Yes


_______is the notion that
"objects in a program should be
replaceable with instances of
their subtypes without altering
the correctness of that
program".Liskov's notion of a
behavioral subtype defines a
notion of substitutability for
mutable objects; that is, if S is a
subtype of T, then objects of
type T in a program may be
replaced with objects of type S
without altering any of the
desirable properties of that
program (e.g., correctness)
Correct answer Distractor(s) Correct feedback:
 Liskov Substitution  Open/Closed Principle Liskov Substitution principle
Principle  Single Responsibility states that child class must a
Principle substitute for parent class
 Dependency Inversion Incorrect feedback:
Principle Please read about the topic
from the above Liskov
Substitution principle section

Question 4.

Final Assessment: Yes


"Software entities (classes,
modules, functions, etc.) should
be open for extension, but
closed for
modification"[Bertrand Meyer-
1988].
Correct answer Distractor(s) Correct feedback:
 Open Closed principle  Liskov Substitution Open Closed principle states an
Principle entity can allow its behavior to
 Single Responsibility be modified without altering its
Principle source code
 Dependency Inversion Incorrect feedback:
Principle Please read about the topic
from the above Open Closed
Principle section

Question 5.

Final Assessment: Yes


Classes that implement
interfaces should not be forced
to implement methods they do
not use. Another way of putting
it is: use small interfaces, not
fat ones. Focuses on the
cohesiveness of interfaces with
respect to the implementors
that use them. Keep each
implementation independent of
interfaces that they do not use.
If you need to change one
interface, you shouldn't need to
change the other.
Correct answer Distractor(s) Correct feedback:
 Interface Segregation  Open/Closed Principle Interface segregation principle
Principle  Liskov Substitution states that every behaviour
Principle must be implemented in a class
 Dependency Inversion if it requires if not it must force
Principle Principle that class to implement it.
Incorrect feedback:
Please read about the topic
from the above Interface
Segregation Principle section

Question 6.

Final Assessment: Yes


Every object should have a
single responsibility, and that
responsibility should be entirely
encapsulated by the class. All its
services should be narrowly
aligned with that responsibility.
Correct answer Distractor(s) Correct feedback:
 Single Responsibility  Open/Closed Principle Single Responsibility states that
Principle  Liskov Substitution a class must have one reason to
Principle change
 Interface Segregation Incorrect feedback:
Principle Please read about the topic
 Dependency Inversion from the above Single
Principle
Responsibility Principle section

Question 7.

Final Assessment: Yes


Contravariance of method
arguments in the subtype.
Covariance of return types in
the subtype. No new exceptions
should be thrown by methods
of the subtype, except where
those exceptions are
themselves subtypes of
exceptions thrown by the
methods of the supertype.
Is it a definition of the standard
signature requirements of the
Liskov Substitution Principle?
Correct answer Distractor(s) Correct feedback:
 True  False Child class overridden method
must throw same exception or
subtype of it. Method
arguments must be same
whereas return types can be
different means it must allow
covariant return types
Incorrect feedback:
Please read about the topic
from the above Liskov
Substitution principle section

Question 8.

Final Assessment: Yes


1. In its simplest form,
covariance,
contravariance and
invariance describe
type "assignment
compatibility":
 Covariant: class
A is a covariant
of class B when
class A is a
subtype of class
B - class of type
A can be
assigned to an
variable of class
type B. Use out
keyword in c#
to indicate
covariance.
Often used in
return type
assignment
compatibility.
 Contravariant:
class A is a
contravariant of
class B when
class A is a
supertype of
class B - class of
type B can be
assigned to a
variable of class
type A. Use in
keyword in c#
to indicate
contravariance.
Often used in
method
parameter
assignment
compatibility.
 Invariant: class
A is neither a
subtype nor a
supertype of
Class B - no
assignment can
be made
between the
two types.
→ Describe the Single
Responsibility Principle?
Correct answer Distractor(s) Correct feedback:
 False  True Single Responsibility principle
deals with single class
Incorrect feedback:
Please read about the topic
from the above Single
Responsibility Principle section

Question 9.

Final Assessment: Yes


Dependency Inversion Principle
states that specific form of
decoupling where conventional
dependency relationships
established from high-level,
policy-setting modules to low-
level, dependency modules are
reversed for the purpose of
rendering high-level modules
independent of the low-level
module implementation details.
Correct answer Distractor(s) Correct feedback:
 True  False Dependency Inversion principle
states that high level
modules(classes) depend on
low level modules(classes) to
achieve abstraction
Incorrect feedback:
Please read about the topic
from the above Dependency
Inversion principle section

Question 10.

Final Assessment: Yes


When the Open/Closed
Principle is applied, new
behavior can be added to our
application by
Correct answer Distractor(s) Correct feedback:
 writing new classes  Adding new parameters Open closed principle makes
without touching to methods the existing classes to be reused
existing classes  adding new cases or by the newly created classes so
else to switch or if that existing classes does not
statements require a change
 opening the class needs Incorrect feedback:
to change, updating it, Please read about the topic
and then closing it from the above Open Closed
again
principle section

Practical Tasks
Please find the attached zip file [Link]. Extract and import it into your IDE. You will find
2 tasks for LSP and OCP.

Note: The classes which requires change are marked with class level comments as “ Changes Required in
this class” and you need to make changes only in those classes to complete your tasks and it is just a
HINT for you to start. Don’t do any changes to the existing classes which are available in before package.
Your new code and classes must go in after package.

Time to complete the task : 2 Hours .

You might also like