0% found this document useful (0 votes)
19 views9 pages

Ooc Lec5

Uploaded by

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

Ooc Lec5

Uploaded by

madetoh181
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

I SLAMIC U NIVERSITY OF T ECHNOLOGY

SWE 4301
LECTURE 5
Topic: SOLID & Open-Closed Principle

September 26, 2024

P REPARED B Y
Maliha Noushin Raida
Lecturer, Department of CSE

1
SWE 4301 Object Orientated Concepts II

Contents
1 SOLID Design Principles in Software Development 3

2 OCP: OpenClosed Princple 3


2.1 Abstraction is the key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 Violating OCP Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Design maintaining OCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Page 2 of 9
SWE 4301 Object Orientated Concepts II

1 SOLID D ESIGN P RINCIPLES IN S OFTWARE D EVELOPMENT


SOLID is a set of five design principles. These principles help software developers design
robust, testable, extensible, and maintainable object-oriented software systems. Each of
these five design principles solves a particular problem that might arise while developing the
software systems. Discuss why principles are important

1. Principles keep everyone in order

2. Principles are well established and proven

3. Following the principles gives consistency

Mention the SOLID principles. The five fundamental principles of OOP.

• S - Single Responsibility Principle (SRP)

• O - Open/Closed Principle (OCP)

• L - Liskov Substitution Principle (LSP)

• I - Interface Segregation Principle (ISP)

• D - Dependency Inversion Principle (DIP)

2 OCP: O PEN C LOSED P RINCPLE


All systems change during their life cycles. This must be born in mind when developing systems
are expected to last longer than the first version

How can we create designs that are stable in the face of change and that will last longer
than the first version? Bertrand Meyer gave us guidance as long ago as 1988 when he coined
the now famous open-closed principle. To paraphrase him:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for
modification.

When a single change to a program results in a cascade of changes to dependent modules,


that program exhibits the undesirable attributes that we have come to associate with “bad”
design. The program becomes fragile, rigid, unpredictable and un-reusable. The open/closed
principle attacks this in a very straightforward way. It says that you should design modules
that never change . When requirements change, you extend the behavior of such modules by
adding new code, not by changing old code that already works.

Page 3 of 9
SWE 4301 Object Orientated Concepts II

• They are “Open For Extension”. This means that the behavior of the module can be
extended. That we can make the module behave in new and different ways as the
requirements of the application change, or to meet the needs of new applications.

• They are “Closed for Modification”. The source code of such a module is inviolate. No
one is allowed to make source code changes to it.

It would seem that these two attributes are at odds with each other. The normal way to
extend the behavior of a module is to make changes to that module. A module that cannot be
changed is normally thought to have a fixed behavior.
Conformance to this principle is what yields the greatest benefits claimed for object
oriented technology; i.e. re-usability and maintainability. Yet conformance to this principle
is not achieved simply by using an object oriented programming language. Rather, it requires
a dedication on the part of the designer to apply abstraction to those parts of the program
that the designer feels are going to be subject to change.
By adhering to OCP, this encourages loose coupling between components that are closed
modifications and new functionality that is added. Usually, this is accomplished when
components depend on interface instead of concrete classes. An interface acts as a layer
of abstraction where well-defined components do not have to worry about the underlying
changes made by the concrete classes that implement the interface. Therefore, this makes
the program easy to maintain.

2.1 Abstraction is the key


It is possible to create abstractions that are fixed and yet represent an unbounded group of
possible behaviors. The abstractions are abstract base classes, and the unbounded group
of possible behaviors is represented by all the possible derivative classes. It is possible
for a module to manipulate an abstraction. Such a module can be closed for modification
since it depends upon an abstraction that is fixed. Yet the behavior of that module can be
extended by creating new derivatives of the abstraction. Both the Client and Server classes

Figure 1: Client and Server Class without Abstraction

are concrete. The Client class uses the Server class. If we wish for a Client object to use

Page 4 of 9
SWE 4301 Object Orientated Concepts II

a different Server object, then the Client class must be changed to name the new Server
class.

Figure 2: Client and Server Class with Abstraction

In this case, the ClientInterface class is an abstract class with abstract member func-
tions. The Client class uses this abstraction; however, objects of the Client class will be
using objects of the derivative Server class. If we want Client objects to use a different server
class, then a new derivative of the ClientInterface class can be created. The Client class
can remain unchanged.

2.2 Violating OCP Example

1 enum EmployeeType {
2 Permanent , Contructual , PartTime
3 }
4

5 class Employee {
6 private readonly EmployeeType type ;
7 private int tr an spo rt Al low an ce ;
8

9 public Employee ( EmployeeType type , int t ra ns por tA ll owa nc e ) {


10 this . type = type ;
11 this . t ran sp or tA llo wa nc e = tr an sp ort Al lo wa nce ;
12 }
13

14 public int CalculateSalary ( int basic , int phr , int hw ) {


15 if ( type == EmployeeType . Permanent ) {
16 return basic + basic / 4 + tra ns po rtA ll ow anc e ;
17 } else if ( type == EmployeeType . Contructual ) {
18 return basic + tra ns po rtA ll ow anc e + phr * hw ;

Page 5 of 9
SWE 4301 Object Orientated Concepts II

19 } else {
20 return basic + phr * hw ;
21 }
22 }
23

24 public int CalculateBonus ( int basic ) {


25 if ( type == EmployeeType . Permanent ) {
26 return basic / 2;
27 } else if ( type == EmployeeType . PartTime ) {
28 return 0;
29 } else {
30 return 5000;
31 }
32 }
33 }

Listing 1: A Employee class in Java

How do you handle changing requirements and feedback that may affect the open-closed
principle in OOP?
• Use abstraction and inheritance: One way to adhere to the open-closed principle is
to use abstraction and inheritance to create a hierarchy of classes that share common
features but can also have specific behaviors. Abstraction is the process of hiding the
details of how something works and exposing only the essential interface. Inheritance
is the mechanism that allows a subclass to inherit the attributes and methods of a
superclass and override or extend them as needed.

• Use interfaces and polymorphism: Another way to follow the open-closed principle
is to use interfaces and polymorphism to define contracts and behaviors for different
types of objects. An interface is a collection of abstract methods that specify what an
object can do, but not how it does it. Polymorphism is the ability of an object to take
different forms and behave differently depending on the context. For example, you can
create an interface called Flyable that defines a method called fly, and then implement
this interface in different classes like Bird, Airplane, and Superman. This way, you
can use polymorphism to call the fly method on any object that implements Flyable,
without knowing or changing its internal details.

2.3 Design maintaining OCP

1 enum EmployeeType {

Page 6 of 9
SWE 4301 Object Orientated Concepts II

2 PERMANENT , CONTRACTUAL , PARTTIME


3 }
4

5 abstract class Employee {


6 protected int t ran sp or tAl lo wa nce ;
7

8 public Employee ( int t ra ns por tA ll owa nc e ) {


9 this . t ran sp or tA llo wa nc e = tr an sp ort Al lo wa nce ;
10 }
11

12 public abstract int calculateSalary ( int basic , int phr , int hw ) ;


13

14 public abstract int calculateBonus ( int basic ) ;


15 }
16

17 class Per manentEm ployee extends Employee {


18

19 public Perman entEmplo yee ( int tr an sp ort Al lo wan ce ) {


20 super ( tr ans po rt All ow an ce ) ;
21 }
22

23 @Override
24 public int calculateSalary ( int basic , int phr , int hw ) {
25 return basic + basic / 4 + tra ns po rtA ll ow anc e ;
26 }
27

28 @Override
29 public int calculateBonus ( int basic ) {
30 return basic / 2;
31 }
32 }
33

34

35 class C on t ra c tu a l Em p lo y e e extends Employee {


36 public C o nt r a ct u al E m pl o ye e ( int tr an spo rt Al low an ce ) {
37 super ( tr ans po rt All ow an ce ) ;
38 }
39 @Override
40 public int calculateSalary ( int basic , int phr , int hw ) {
41 return basic + tra ns po rtA ll ow anc e + phr * hw ;
42 }
43 @Override

Page 7 of 9
SWE 4301 Object Orientated Concepts II

44 public int calculateBonus ( int basic ) {


45 return 5000;
46 }
47 }
48 class PartTimeEmployee extends Employee {
49 public PartTimeEmployee ( int tr an sp ort Al lo wan ce ) {
50 super ( tr ans po rt All ow an ce ) ;
51 }
52 @Override
53 public int calculateSalary ( int basic , int phr , int hw ) {
54 return basic + phr * hw ;
55 }
56 @Override
57 public int calculateBonus ( int basic ) {
58 return 0;
59 }
60 }
61

62 public class Main {


63 public static void main ( String [] args ) {
64 Employee pe rmanentE mployee = new Perma nentEmplo yee (3000) ;
65 Employee c on t ra c t ua l Em p lo y e e = new C o n tr a ct u al E m pl o ye e (2000) ;
66 Employee partTimeEmployee = new PartTimeEmployee (1000) ;
67

68 // Example calculations
69 System . out . println ( " Permanent Employee Salary : " +
perma nentEmpl oyee . calculateSalary (50000 , 200 , 160) ) ;
70 System . out . println ( " Permanent Employee Bonus : " +
perma nentEmpl oyee . calculateBonus (50000) ) ;
71

72 System . out . println ( " Contractual Employee Salary : " +


c on t r ac t ua l Em p l oy e e . calculateSalary (30000 , 150 , 100) ) ;
73 System . out . println ( " Contractual Employee Bonus : " +
c on t r ac t ua l Em p l oy e e . calculateBonus (30000) ) ;
74

75 System . out . println ( " Part - Time Employee Salary : " +


partTimeEmployee . calculateSalary (20000 , 100 , 80) ) ;
76 System . out . println ( " Part - Time Employee Bonus : " +
partTimeEmployee . calculateBonus (20000) ) ;
77 }
78 }

Listing 2: Design reconstructed in Java

Page 8 of 9
SWE 4301 Object Orientated Concepts II

We solved the violation using abstract class and polymorphism.


In general, no matter how “closed” a module is, there will always be some kind of change
against which it is not closed. Since closure cannot be complete, it must be strategic. That is,
the designer must choose the kinds of changes against which to close his design. This takes a
certain amount of prescience derived from experience. The experienced designer knows the
users and the industry well enough to judge the probability of different kinds of changes. He
then makes sure that the open-closed principle is invoked for the most probable changes.

Page 9 of 9

You might also like