Object Oriented Programming
Object Oriented Programming
MAHEDEE.NET
Page 1 of 45
Page 2 of 45
Contents
Introduction .................................................................................................................................................. 6
What is Software Architecture? .................................................................................................................... 6
Importance of Software Architecture ........................................................................................................... 6
OOP in a Nutshell .......................................................................................................................................... 7
Five basic characteristics of OOP Approach.............................................................................................. 7
Procedural Programming .............................................................................................................................. 8
Advantages of OOP ....................................................................................................................................... 8
User Defined Data type ................................................................................................................................. 9
Classes and Object ........................................................................................................................................ 9
What are objects? ..................................................................................................................................... 9
What are classes? ................................................................................................................................... 10
How to identify and design a Class? ........................................................................................................... 11
Four Main Object Oriented Programming Concept .................................................................................... 12
Abstraction .............................................................................................................................................. 12
Polymorphism ......................................................................................................................................... 13
Inheritance .............................................................................................................................................. 14
Encapsulation .......................................................................................................................................... 15
Coupling ...................................................................................................................................................... 15
Cohesion ..................................................................................................................................................... 16
Association .................................................................................................................................................. 16
Composition ................................................................................................................................................ 17
Difference between Association, Aggregation and Composition ............................................................... 17
Abstraction and Generalization .................................................................................................................. 18
Abstract class .............................................................................................................................................. 19
Interface ...................................................................................................................................................... 20
What is the difference between a Class and an Interface? ........................................................................ 21
What is the difference between an Interface and an Abstract class? ........................................................ 21
Implicit and Explicit Interface Implementations ......................................................................................... 22
Method Overloading ................................................................................................................................... 22
Operator Overloading ................................................................................................................................. 23
Page 3 of 45
Page 5 of 45
Introduction
Partitioning the problem and the system to be built into discrete pieces
Techniques used to create interfaces between these pieces
Techniques used to manage overall structure and flow
Techniques used to interface the system to its environment
Appropriate use of development and delivery approaches, techniques and tools.
Controls complexity
Enforces best practices
Gives consistency and uniformity
Increases predictability
Enables re-use.
Page 6 of 45
OOP in a Nutshell
Everything is an object
A program is a bunch of objects telling each other what to do by sending messages
Each object has its own memory and might made up of other object
Every object has a type
All objects of a particular type can receive the same messages
Page 7 of 45
Procedural Programming
Graphical representations of the three basic patterns. The box diagrams (blue) were invented right
for the new theory, and you can see here their equivalents in the mostly used control flow charts.
Advantages of OOP
Reusability
o Classes and Objects
Extensibility
o Inheritance, aggregation and composition
Simplicity
o Abstraction, encapsulation and polymorphism
Maintainability
o All of the above three combined help us to maintain the code better.
Better suited for team development
Facilitates utilizing and creating reusable software components
Makes business profitable by reusability;
o Reduces cost of solution
o Reduces time of development
o Reduces effort
Easier GUI programming
Easier software maintenance
All modern languages are object-oriented: Java, C#, PHP, Perl, C++ etc.
Page 8 of 45
An object can be considered a "thing" that can perform a set of related activities.
Software objects model real-world objects or abstract concepts
o E.g. dog, bicycle, queue
Real-world objects have states and behaviors
o Dogs' states: name, color, breed, hungry
o Dogs' behaviors: barking, fetching, sleeping
The set of activities that the object performs defines the object's behavior.
o For example, the hand can grip something or a Student (object) can give the name or
address.
So, an object can have state, behavior and identity
This means that an object can have
o internal data (state),
o Methods, functionalities or services why object exists (behavior)
o and each object can be uniquely distinguished from every other object of same or
different types (Identity)
How do software objects implement real-world objects?
o Use variables/data to implement states
o Use methods/functions to implement behaviors
In pure OOP terms an object is an instance of a class.
An object is a software bundle of variables and related methods
Page 9 of 45
Example:
public class Student
{
}
Student objStudent = new Student();
Page 10 of 45
There are more principles for object oriented design and dependency management other than
SOLID. They are
Page 11 of 45
Abstraction
Polymorphism
Inheritance
and Encapsulation
These concepts are the four main Object Oriented Programming Concepts often called APIE
Abstraction
Abstraction is an emphasis on the idea, qualities and properties rather than the particulars
o a suppression of detail
The importance of abstraction is derived from its ability to hide irrelevant details and
from the use of names to reference objects
It places the emphasis on what an object is or does rather than how it is represented or
how it works.
Thus, it is the primary means of managing complexity in large programs.
Page 12 of 45
Polymorphism
It means
o Same object acts differently to serve same service of different natures
o Different objects of same type receive same message to do same job differently
still with due accuracy
Page 13 of 45
Inheritance
Ability of a new class to be created, from an existing class by extending it, is called
inheritance
Inheritance specifies an is-a (for specialization) kind of relationship
Derived classes inherits properties and methods from base class, allowing code reuse
Derived classes become more specialized.
Abstraction is closely related with generalization, the inheritance is closely related with
specialization.
Page 14 of 45
Encapsulation
The encapsulation is the inclusion within a program object of all the resources need for
the object to function - basically, the methods and the data
The class is kind of a container or capsule or a cell
o which encapsulate the set of methods, attribute and properties to provide its
indented functionalities to other classes
In that sense, encapsulation also allows a class to change its internal implementation
without hurting the overall functioning of the system.
That idea of encapsulation is to hide how a class does it but to allow requesting what to
do
There are several other ways that an encapsulation can be used, as an example we can
take the usage of an interface
Coupling
The notion of coupling attempts to capture this concept of how strongly dierent
modules are interconnected.
Coupling among classes or subsystems is a measure of how interconnected those classes
or subsystems are.
Coupling increases with the complexity and obscurity of the interface between modules.
Tight coupling means that related classes have to know
o internal details of each other,
o changes ripple through the system, and
o the system is potentially harder to understand
o It violates Encapsulation
Ensure Loose Coupling - the goals behind achieving loose coupling between classes and
modules are to:
Make the code easier to read.
Make our classes easier to consume by other developers by hiding the ugly inner
workings of our classes behind well-designed APIs.
Page 15 of 45
Cohesion
Cohesion refers to how closely related methods and class level variables are in a class.
Cohesion of a module represents how tightly bound the internal elements of the module
are to one another
A class with high cohesion would be one where all the methods and class level variables
are used together to accomplish a specific task.
On the other end, a class with low cohesion is one where functions are randomly inserted
into a class/ classes to accomplish a variety of different tasks.
Generally tight coupling gives low cohesion and loose coupling gives high cohesion.
Association
Example:
public class StudentRegistrar
{
public StudentRegistrar ();
{
new RecordManager().Initialize();
}
}
In this case we can say that there is an association between StudentRegistrar and
RecordManager or there is a directional association from StudentRegistrar to RecordManager or
StudentRegistrar use a (*Use*) RecordManager. Since a direction is explicitly specified, in this
case the controller class is the StudentRegistrar.
Page 16 of 45
Composition
Has-a relationship
Decreases Degree of Coupling
Object behaviors are easier to modify
Enables an object dealing with multiple other objects for providing services
Composition is preferred over Inheritance
Association is a (*a*) relationship between two classes, where one class use another.
But aggregation describes a special type of an association.
Aggregation is the (*the*) relationship between two classes
When object of one class has an (*has*) object of another, if second is a part of first
(containment relationship) then we called that there is an aggregation between two
classes.
Unlike association, aggregation always insists a direction
But even without a Chancellor a University can exists. But the Faculties cannot exist
without the University, the life time of a Faculty (or Faculties) attached with the life time
of the University. If University is disposed the Faculties will not exist. In that case we
called that University is composed of Faculties. So that composition can be recognized as
a special type of an aggregation.
Page 17 of 45
Same way, as another example, you can say that, there is a composite relationship inbetween a KeyValuePairCollection and a KeyValuePair. Both depend on each other.
.Net and Java uses the Composite relation to define their Collections
So in summary, we can say that aggregation is a special kind of an association and
composition is a special kind of an aggregation. (Association->Aggregation>Composition)
Abstraction is an emphasis on the idea, qualities and properties rather than the particulars
o A suppression of detail
The importance of abstraction is derived from its ability to hide irrelevant details and
from the use of names to reference objects
Abstraction is essential in the construction of programs.
It places the emphasis on what an object is or does rather than how it is represented or
how it works.
It is used to manage complexity in large programs.
In a sentences - abstraction reduces complexity by hiding irrelevant detail
Generalization reduces complexity by replacing multiple entities which perform similar
functions with a single construct.
Generalization is the broadening of application to encompass a larger domain of objects
of the same or different type.
It places the emphasis on the similarities between objects.
Thus, it helps to manage complexity by collecting individuals into groups and providing a
representative which can be used to specify any individual of the group.
Abstraction and generalization are often used together.
Page 18 of 45
Abstract class
or
When a derived class inherits an abstract method from an abstract class, it must override
the abstract methods
You can also create an abstract class that contains virtual methods, as shown in the
following example:
In this case, a derived class does not have to provide an implementation of the Sleep
method because Sleep is defined as virtual.
Page 19 of 45
Interface
In summary the Interface separates the implementation and defines the structure
Apart from that an interface is very useful when the implementation changes frequently
Interface can be used to define a generic template and then one or more abstract classes to
define partial implementations of the interface
An interface like that of an abstract class cannot be instantiated.
An interfaces can inherit other one or more interfaces
Is a reference type that define contract
Can contain method, properties, indexers, events
Does not provide the implementations for the members
Declare an interface
interface ICarnivore {
bool
IsHungry { get; }
Animal
Hunt();
void
Eat(Animal victim);}
Implement an interface
public class Lion: ICarnivore {
private bool hungry;
public bool IsHungry {
get {
return hungry;
}
}
public Animal Hunt() {
// hunt and capture implementation
// return animal object
}
public void Eat( Animal victim ) {
// implementation
}
}
Page 20 of 45
Page 21 of 45
The concept of implicit and explicit implementation provide safe way to implement
methods of multiple interfaces by hiding, exposing or preserving identities of each of
interface methods, even when the method signatures are the same.
Example:
Let's consider the interfaces defined below.
interface IDisposable
{
void Dispose();
}
Here you can see that the class Student has implicitly and explicitly implemented the method
named Dispose() via Dispose and IDisposable.Dispose.
class Student : IDisposable
{
public void Dispose()
{
Console.WriteLine("Student.Dispose");
}
void IDisposable.Dispose()
{
Console.WriteLine("IDisposable.Dispose");
}
}
Method Overloading
The method overloading is the ability to define several methods all with the same name
The method overloading is the ability to define several methods all with the same name
public class MyLogger
{
public void LogError(Exception e)
{
// Implementation goes here
}
public bool LogError(Exception e, string message)
{
// Implementation goes here
}
}
Page 22 of 45
Operator Overloading
Page 23 of 45
Its an acronym of five principles introduced by Mr. Robert Martin (commonly known as Uncle
Bob)
o S-SRP -Single responsibility Principle
o O-OCP - Open-closed Principle
o L-LSP -Liskov substitution Principle
o I-ISP - Interface segregation Principle
o D-DIP - Dependency inversion Principle
Before we talk about this principle I want you take a look at following class.
What is SRP?
SRP says "Every software module should have only one reason to change".
Now its up to us how we achieve this. One thing we can do is create three different classes
1. Employee Contains Properties (Data)
2. EmployeeDB Does database operations
3. EmplyeeReport Does report related tasks
public class Employee
{
public string EmployeeName { get; set; }
public int EmployeeNo { get; set; }
}
public class EmployeeDB
{
public void Insert(Employee e)
{
//Database Logic written here
}
public Employee Select()
{
//Database Logic written here
}
}
public class EmployeeReport
{
public void GenerateReport(Employee e)
{
//Set report formatting
}
}
The answer is YES. Now you might ask how its possible that
1. A class will have single responsibility.
2. A method will have single responsibility.
3. A class may have more than one method.
Page 25 of 45
Page 26 of 45
Lets assume you want to add one more floor between the first and second floor in your two floor
house. Do you think it is possible? Yes it is, but is it feasible? Here are some options:
One thing you could have done at time you were building the house first time was make
it with three floors, keeping second floor empty. Then utilize the second floor anytime
you want. I dont know how feasible that is, but it is one solution.
Break the current second floor and build two new floors, which is not sensible.
What is OCP?
First introduced by Betrand Meyer in 1988
He says Software entities (Class, module, function etc.) should be open for extension, but
closed for modification.
An entity is Open for extension means that its behavior can be extended to accommodate
new demand.
The entity is closed for modification means that the existing source code of the module is not
changed or minimum change when making enhancement
Reduces risk Because sometimes code changes introduce heavy risk
Example:
//Rectangle class
public class Rectangle : Shape
{
public double Height { get; set; }
Page 27 of 45
//Triangle class
public class Triangle : Shape
{
public double Base { get; set; }
public double Height { get; set; }
public Triangle(double vbase, double vheight)
{
this.Base = vbase;
this.Height = vheight;
}
public override double CalculateArea()
{
return 1 / 2.0 * Base * Height;
}
}
//If you wish to add Circle You dont need to modify existing class
public class Circle : Shape
{
public double Radius { get; set; }
Page 28 of 45
{
Shape objShape = new Rectangle(20, 30);
Console.WriteLine("Area of Rectangle: " + objShape.CalculateArea());
objShape = new Triangle(20, 30);
Console.WriteLine("Area of Triangle: " + objShape.CalculateArea());
objShape = new Circle(4);
Console.WriteLine("Area of Circle: " + objShape.CalculateArea());
Console.ReadKey();
}
}
You might be wondering why we are defining it prior to examples and problem
discussions. Simply put, I thought it will be more sensible here.
It says, "Subclasses should be substitutable for base classes." Dont you think this
statement is strange? If we can always write BaseClass b = new DerivedClass() then
why would such a principle be made?
A father is a real estate business man whereas his son wants to be cricketer.
A son cant replace his father in spite of the fact that they belong to same family
hierarchy.
Lets talk about a very common example. Normally when we talk about geometric
shapes, we call a rectangle a base class for square. Lets take a look at code snippet.
public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
Page 29 of 45
}
public class Square:Rectangle
{
//codes specific to
//square will be added
}
o.Width = 5;
o.Height = 6;
Perfect but as per LSP we should be able to replace Rectangle with square. Lets try to do
so.
o.Width = 5;
o.Height = 6;
What is the matter? Square cannot have different width and height.
What it means? It means we cant replace base with derived. Means we are violating LSP.
Why dont we make width and height virtual in Rectangle, and override them in Square?
public class Square : Rectangle
{
public override int Width
{
get{return base.Width;}
set
{
base.Height = value;
base.Width = value;
}
}
public override int Height
{
get{return base.Height;}
set
{
base.Height = value;
base.Width = value;
}
}
}
We cant because doing so we are violating LSP, as we are changing the behavior of
Width and Height properties in derived class (for Rectangle height and width cannot be
equal, if they are equal its cannot be Rectangle). (It will not be a kind of replacement).
Page 30 of 45
Now there will be two concrete classes independent of each other, one rectangle and one
square, both of which will be derived from Shape. Now the developer can say:
Shape o = new Rectangle();
o.Width = 5;
o.Height = 6;
Shape o = new Square();
o.Width = 5; //both height and width become 5
o.Height = 6; //both height and width become 6
This principle is just an extension of the Open Close Principle and it means that we must make
sure that new derived classes are extending the base classes without changing their behavior.
Page 31 of 45
Lets say we want to develop a Report Management System. Now, the very first task is creating
a business layer which will be used by three different UIs.
1. EmployeeUI Show reports related to currently logged in employee
2. ManagerUI Show reports related to himself and the team for which he/manager
belongs.
3. AdminUI Show reports related to individual employee ,related to team and related to
company like profit report.
public interface IReportBAL
{
void GeneratePFReport();
void GenerateESICReport();
void GenerateResourcePerformanceReport();
void GenerateProjectSchedule();
void GenerateProfitReport();
}
public class ReportBAL : IReportBAL
{
public void GeneratePFReport()
{/*...............*/}
public void GenerateESICReport()
{/*...............*/}
public void GenerateResourcePerformanceReport()
{/*...............*/}
public void GenerateProjectSchedule()
{/*...............*/}
public void GenerateProfitReport()
{/*...............*/}
}
public class EmployeeUI
{
public void DisplayUI()
{
IReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
}
}
public class ManagerUI
{
public void DisplayUI()
{
IReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
objBal.GenerateResourcePerformanceReport ();
Page 32 of 45
objBal.GenerateProjectSchedule ();
}
}
public class AdminUI
{
public void DisplayUI()
{
IReportBAL objBal = new ReportBAL();
objBal.GenerateESICReport();
objBal.GeneratePFReport();
objBal.GenerateResourcePerformanceReport();
objBal.GenerateProjectSchedule();
objBal.GenerateProfitReport();
}
}
Now in each UI when the developer types "objBal" the following intellisense will be
shown:
The developer who is working on EmployeeUI gets access to all the other methods as
well, which may unnecessarily cause him/her confusion.
What is ISP?
It states that "Clients should not be forced to implement interfaces they dont use."
It can also be stated as "Many client specific interfaces are better than one general
purpose interface."
In simple words, if your interface is fat, break it into multiple interfaces.
Page 33 of 45
{
void GenerateProfitReport();
}
public class ReportBAL : IAdminReportBAL
{
public void GeneratePFReport()
{/*...............*/}
public void GenerateESICReport()
{/*...............*/}
public void GenerateResourcePerformanceReport()
{/*...............*/}
public void GenerateProjectSchedule()
{/*...............*/}
public void GenerateProfitReport()
{/*...............*/}
}
Page 34 of 45
Lets talk about our desktop computers. Different parts such as RAM, a hard disk, and
CD-ROM (etc.) are loosely connected to the motherboard. That means that, if, in future
in any part stops working it can easily be replaced with a new one. Just imagine a
situation where all parts were tightly coupled to each other, which means it would not be
Page 35 of 45
possible to remove any part from the motherboard. Then in that case if the RAM stops
working we have to buy new motherboard which is going to be very expensive.
Identify Problem in Programming
In the above code CustomerBAL is directly dependent on the FileLogger class which
will log exceptions in physical file. Now lets assume tomorrow management decides to
log exceptions in the Event Viewer. Now what? Change existing code. Oh no! My God,
that might create a new error!
What is DIP?
It says, "High level modules should not depend upon low level modules. Rather, both
should depend upon abstractions."
Page 36 of 45
{
public void LogError(Exception e)
{
//Log Error in a physical file
}
}
public class EventViewerLogger : ILogger
{
public void LogError(Exception e)
{
//Log Error in a physical file
}
}
public class CustomerBAL
{
private ILogger _objLogger;
public CustomerBAL(ILogger objLogger)
{
_objLogger = objLogger;
}
public void Insert(Customer c)
{
try
{
//Insert logic
}
catch (Exception e)
{
_objLogger.LogError(e);
}
}
}
Page 37 of 45
In another angle a use case encodes a typical user interaction with the system. In
particular, it:
o Captures some user-visible function.
o Achieves some concrete goal for the user.
A complete set of use cases largely defines the requirements for your system: everything
the user can see, and would like to do.
Page 38 of 45
A class diagrams are widely used to describe the types of objects in a system and their
relationships.
Class diagrams model class structure and contents using design elements such as classes,
packages and objects
Class diagrams describe three different perspectives when designing a system,
conceptual, specification, and implementation
Different Diagram
Package Diagram
Package diagrams are used to reflect the organization of packages and their elements
Sequence Diagram
A sequence diagrams model the flow of logic within a system in a visual manner, it
enable both to document and validate your logic, and are used for both analysis and
design purposes.
Page 39 of 45
The three tier software architecture (also known as three layer architectures) emerged in
the 1990s
o Overcome the limitations of the two tier architecture.
Presentation Tier or Web Server: User Interface, displaying/ accepting data/ input to/
from the user
Application Logic/ Business Logic/ Transaction Tier or Application Server: Data
validation, acceptability check before being added to the database and all other business/
application specific operations
Data Tier or Database server: Simple reading and writing method to database or any
other storage, connection, command, stored procedures etc
Page 40 of 45
What is SOA?
Page 41 of 45
Page 42 of 45
The data access layer (DAL), which is a key part of every n-tier system, is mainly consist
of a simple set of code that does basic interactions with the database or any other storage
device.
These functionalities are often referred to as CRUD (Create, Retrieve, Update, and
Delete).
The data access layer need to be generic, simple, quick and efficient as much as possible.
It should not include complex application/ business logics.
Business logic actually is, and in many cases it's just the bridge in between the
presentation layer and the data access layer with having nothing much, except taking
from one and passing to the other.
In some other cases, it is not even been well thought out, they just take the leftovers from
the presentation layer and the data access layer then put them in another layer which
automatically is called the business logic layer.
The Gang of Four (GoF) patterns are generally considered the foundation for all other
patterns.
They are categorized in three groups: Creational, Structural, and Behavioral.
Creational Patterns
o
o
o
o
o
Structural Patterns
o
o
o
o
o
o
o
Page 43 of 45
Behavioral Patterns
o
o
o
o
o
o
o
o
o
o
o
History Card
Version No
1
2
Modification History
Created
Update Cover
Update Date
5 December 2013
24 November 2014
Published Date
22 December 2013
24 November 2014
Page 44 of 45
References:
1.
2.
3.
4.
5.
6.
http://www.oodesign.com/liskov-s-substitution-principle.html (link)
http://mahedee.blogspot.com/2012/12/open-close-principle.html (link)
http://www.objectmentor.com/omSolutions/oops_what.html (Links)
http://en.wikibooks.org/wiki/Object_Oriented_Programming (Link)
http://oopsconcepts.blogspot.com/ (Link)
http://www.codeproject.com/Articles/22769/Introduction-to-Object-OrientedProgramming-Concep (Link)
7. Basic Object-Oriented Concepts - Edward V. Berard (The Object Agency, Inc.) (Slide)
8. Qualities of a class (Slide)
9. http://www.virtuosimedia.com/dev/php/procedural-vs-object-oriented-programming-oop
(Link)
10. http://www.princeton.edu/~achaney/tmve/wiki100k/docs/Procedural_programming.html
(Link)
11. http://en.wikipedia.org/wiki/Structured_programming (Link)
12. A Concise Introduction to Software Engineering - Pankaj Jalote (Book)
13. MSDN C# Training Materials (Tutorial)
14. http://www.codeproject.com/Articles/567768/Object-Oriented-Design-Principles (Link)
15. http://www.codeproject.com/Articles/495019/Dependency-Inversion-Principle-and-theDependency(Link)
Page 45 of 45