+ All Categories
Home > Technology > 20 Object-oriented programming principles

20 Object-oriented programming principles

Date post: 28-May-2015
Category:
Upload: maznabili
View: 130 times
Download: 1 times
Share this document with a friend
Description:
Object-oriented programming principles
Popular Tags:
72
Object-Oriented Object-Oriented Programming Programming Fundamental Concepts Fundamental Concepts Svetlin Nakov Svetlin Nakov Telerik Telerik Corporation Corporation www.telerik. com
Transcript
Page 1: 20 Object-oriented programming principles

Object-Oriented Object-Oriented Programming Programming

Fundamental ConceptsFundamental Concepts

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: 20 Object-oriented programming principles

ContentsContents

1.1. Fundamental Principles of OOPFundamental Principles of OOP

2.2. InheritanceInheritance

3.3. AbstractionAbstraction

4.4. EncapsulationEncapsulation

5.5. PolymorphismPolymorphism

6.6. Cohesion and CouplingCohesion and Coupling

2

Page 3: 20 Object-oriented programming principles

Fundamental Fundamental Principles of Principles of

OOPOOP

Page 4: 20 Object-oriented programming principles

Fundamental Principles Fundamental Principles of OOPof OOP

InheritanceInheritance Inherit members from parent classInherit members from parent class

AbstractionAbstraction Define and execute abstract actionsDefine and execute abstract actions

EncapsulationEncapsulation Hide the internals of a classHide the internals of a class

PolymorphismPolymorphism Access a class through its parent Access a class through its parent

interfaceinterface4

Page 5: 20 Object-oriented programming principles

InheritancInheritancee

Page 6: 20 Object-oriented programming principles

Classes and InterfacesClasses and Interfaces Classes define attributes and Classes define attributes and

behaviorbehavior Fields, properties, methods, etc.Fields, properties, methods, etc.

Methods contain code for executionMethods contain code for execution

Interfaces define a set of Interfaces define a set of operationsoperations Empty methods and properties, left Empty methods and properties, left

to be implemented laterto be implemented later

6

public class Labyrinth { … }public class Labyrinth { … }

public interface IFigure { … }public interface IFigure { … }

Page 7: 20 Object-oriented programming principles

InheritanceInheritance Inheritance Inheritance allowsallows child child classes classes inheritsinherits

the characteristics of existing the characteristics of existing parentparent classclass Attributes (fields and properties)Attributes (fields and properties)

Operations (methods)Operations (methods) Child class can extend the parent classChild class can extend the parent class

Add new fields and methodsAdd new fields and methods

Redefine methods (modify existing Redefine methods (modify existing behavior)behavior)

A class can A class can implementimplement an interface by an interface by providing implementation for all its providing implementation for all its methodsmethods 7

Page 8: 20 Object-oriented programming principles

Inheritance terminologyInheritance terminology

derived derived classclass

base class /base class /parent classparent classinheritsinherits

derived derived interfaceinterface

base base interfaceinterface

implementsimplements

classclass interfaceinterfaceimplementsimplements

8

Page 9: 20 Object-oriented programming principles

Inheritance – BenefitsInheritance – Benefits Inheritance has a lot of benefitsInheritance has a lot of benefits

Extensibility Extensibility

ReusabilityReusability

Provides abstractionProvides abstraction

Eliminates redundant codeEliminates redundant code Use inheritance for buidling Use inheritance for buidling is-ais-a

relationshipsrelationships E.g. dog E.g. dog is-ais-a animal (dogs are kind of animal (dogs are kind of

animals)animals) Don't use it to build Don't use it to build has-ahas-a relationshiprelationship

E.g. dog E.g. dog has-ahas-a name (dog is not kind of name (dog is not kind of name)name) 9

Page 10: 20 Object-oriented programming principles

Inheritance – ExampleInheritance – Example

PersonPerson+Name: String+Name: String+Address: String+Address: String

EmployeeEmployee+Company: String+Company: String+Salary: double+Salary: double

StudentStudent+School: String+School: String

Base Base classclass

Derived Derived classclass

Derived Derived classclass

10

Page 11: 20 Object-oriented programming principles

Class HierarchiesClass Hierarchies Inheritance leads to a hierarchy of Inheritance leads to a hierarchy of

classes and/or interfaces in an classes and/or interfaces in an application:application:

11

GameGame

MultiplePlayersGameMultiplePlayersGame

BoardGameBoardGame

ChessChess BackgammonBackgammon

SinglePlayerGameSinglePlayerGame

MinesweeperMinesweeper SolitaireSolitaire ……

……

Page 12: 20 Object-oriented programming principles

Inheritance in .NETInheritance in .NET A class can inherit only one base classA class can inherit only one base class

E.g. E.g. IOExceptionIOException derives from derives from SystemExceptionSystemException and it derives from and it derives from ExceptionException

A class can implement several interfacesA class can implement several interfaces

This is This is .NET’s.NET’s form of form of multiple inheritancemultiple inheritance

E.g. E.g. List<T>List<T> implements implements IList<T>IList<T>, , ICollection<T>ICollection<T>, , IEnumerable<T>IEnumerable<T>

An interface can implement several An interface can implement several interfacesinterfaces

E.g. E.g. IList<T>IList<T> implements implements ICollection<T>ICollection<T> and and IEnumerable<T>IEnumerable<T> 12

Page 13: 20 Object-oriented programming principles

How to Define How to Define InheritanceInheritance??

We must specify the name of the We must specify the name of the base class after the name of the base class after the name of the derived derived

In the constructor of the derived In the constructor of the derived class we use the keyword class we use the keyword basebase to to invoke the constructor of the base invoke the constructor of the base classclass

13

public class Shapepublic class Shape{...}{...}public class Circle : Shapepublic class Circle : Shape{...}{...}

public Circle (int x, int y) : base(x)public Circle (int x, int y) : base(x){...}{...}

Page 14: 20 Object-oriented programming principles

Simple Inheritance Simple Inheritance ExampleExample

public class Mammalpublic class Mammal{{ public int Age { get; set; }public int Age { get; set; }

public Mammal(int age)public Mammal(int age) {{ this.Age = age;this.Age = age; }}

public void Sleep()public void Sleep() {{ Console.WriteLine("Shhh! I'm Console.WriteLine("Shhh! I'm sleeping!");sleeping!"); }}}}

14

Page 15: 20 Object-oriented programming principles

Simple Inheritance Simple Inheritance ExampleExample (2) (2)

public class Dog : Mammalpublic class Dog : Mammal{{ public string Breed { get; set; }public string Breed { get; set; }

public Dog(int age, string breed)public Dog(int age, string breed) : base(age): base(age) {{ this.Breed = breed;this.Breed = breed; }}

public void WagTail()public void WagTail() {{ Console.WriteLine("Tail wagging...");Console.WriteLine("Tail wagging..."); }}}}

15

Page 16: 20 Object-oriented programming principles

SSimple imple Inheritance Inheritance

Live DemoLive Demo

Page 17: 20 Object-oriented programming principles

Accessibility LevelsAccessibility Levels Access modifiers in C#Access modifiers in C#

publicpublic – access is not restricted – access is not restricted privateprivate – access is restricted to the – access is restricted to the containing type containing type

protectedprotected – access is limited to the – access is limited to the containing type and types derived from containing type and types derived from it it

internalinternal – access is limited to the – access is limited to the current assembly current assembly

protectedprotected internalinternal – access is limited to – access is limited to the current assembly or types derived the current assembly or types derived from the containing classfrom the containing class 17

Page 18: 20 Object-oriented programming principles

Inheritance and Inheritance and AccessibilityAccessibility

class Creatureclass Creature{{ protected string Name { get; private set; }protected string Name { get; private set; }

private void Talk()private void Talk() {{ Console.WriteLine("I am creature ...");Console.WriteLine("I am creature ..."); }}

protected void Walk()protected void Walk() {{ Console.WriteLine("Walking ...");Console.WriteLine("Walking ..."); }}}}

class Mammal : Creatureclass Mammal : Creature{{ // base.Talk() can be invoked here// base.Talk() can be invoked here // this.Name can be read but cannot be modified // this.Name can be read but cannot be modified herehere}}

18

Page 19: 20 Object-oriented programming principles

Inheritance and Inheritance and Accessibility (2)Accessibility (2)

class Dog : Mammalclass Dog : Mammal{{ public string Breed { get; private set; }public string Breed { get; private set; }

// base.Talk() cannot be invoked here (it is // base.Talk() cannot be invoked here (it is private)private)}}

class InheritanceAndAccessibilityclass InheritanceAndAccessibility{{ static void Main()static void Main() {{ Dog joe = new Dog(6, "Labrador");Dog joe = new Dog(6, "Labrador"); Console.WriteLine(joe.Breed);Console.WriteLine(joe.Breed); // joe.Walk() is protected and can not be // joe.Walk() is protected and can not be invokedinvoked // joe.Talk() is private and can not be invoked// joe.Talk() is private and can not be invoked // joe.Name = "Rex"; // Name cannot be accessed // joe.Name = "Rex"; // Name cannot be accessed herehere // joe.Breed = "Shih Tzu"; // Can't modify Breed// joe.Breed = "Shih Tzu"; // Can't modify Breed }}}}

19

Page 20: 20 Object-oriented programming principles

Inheritance and Inheritance and AccessibilityAccessibility

Live DemoLive Demo

Page 21: 20 Object-oriented programming principles

Inheritance: IInheritance: Important mportant AAspectspectss

StructuresStructures cannot be inherited cannot be inherited

In C# there is no In C# there is no multiplemultiple inheritanceinheritance

Only multiple interfaces can be Only multiple interfaces can be implementedimplemented

Instance and static constructors are Instance and static constructors are not inherited not inherited

Inheritance is Inheritance is transitivetransitive relation relation

If C is derived from B, and B is derived If C is derived from B, and B is derived from A, then C inherits A as wellfrom A, then C inherits A as well 21

Page 22: 20 Object-oriented programming principles

Inheritance: Important Inheritance: Important FeaturesFeatures

A derived class extends its base classA derived class extends its base class It can add new members but cannot It can add new members but cannot

remove derived onesremove derived ones Declaring new members with the Declaring new members with the

same name or signature hides the same name or signature hides the inherited onesinherited ones

A class can declare A class can declare virtualvirtual methods methods and propertiesand properties Derived classes can Derived classes can overrideoverride the the

implementation of these membersimplementation of these members

E.g. E.g. Object.Equals()Object.Equals() is virtual method is virtual method22

Page 23: 20 Object-oriented programming principles

AbstractioAbstractionn

Page 24: 20 Object-oriented programming principles

AbstractionAbstraction AbstractionAbstraction means ignoring irrelevant means ignoring irrelevant

features, properties, or functions and features, properties, or functions and emphasizing the relevant ones ...emphasizing the relevant ones ...

... relevant to the given project (with ... relevant to the given project (with an eye to future reuse in similar an eye to future reuse in similar projects)projects)

Abstraction = managing complexityAbstraction = managing complexity

"Relevant" to what?"Relevant" to what?

24

Page 25: 20 Object-oriented programming principles

Abstraction (2)Abstraction (2) Abstraction is something we do every dayAbstraction is something we do every day

Looking at an object, we see those things Looking at an object, we see those things about it that have meaning to usabout it that have meaning to us

We abstract the properties of the object, We abstract the properties of the object, and keep only what we needand keep only what we need

E.g. students get "name" but not "color of E.g. students get "name" but not "color of eyes"eyes"

Allows us to represent a complex reality Allows us to represent a complex reality in terms of a simplified modelin terms of a simplified model

Abstraction highlights the properties of Abstraction highlights the properties of an entity that we need and hides the an entity that we need and hides the othersothers 25

Page 26: 20 Object-oriented programming principles

In .NET abstraction is achieved in In .NET abstraction is achieved in several ways:several ways: Abstract classes Abstract classes

InterfacesInterfaces

InheritanceInheritance

+Color : long+Color : longButtonBaseButtonBase

+click()+click()ControlControl

ButtonButton RadioButtonRadioButton CheckBoxCheckBox

Abstraction in .NETAbstraction in .NET

26

Page 27: 20 Object-oriented programming principles

Abstraction in .NET – Abstraction in .NET – ExampleExample

27

System.ObjectSystem.Object

System.MarshalByRefObjectSystem.MarshalByRefObject

System.ComponentModel.ComponentSystem.ComponentModel.Component

System.Windows.Forms.ControlSystem.Windows.Forms.Control

System.Windows.Forms.ButtonBaseSystem.Windows.Forms.ButtonBase

System.Windows.Forms.ButtonSystem.Windows.Forms.Button

Page 28: 20 Object-oriented programming principles

Interfaces in C#Interfaces in C# An An interfaceinterface is a set of operations is a set of operations

(methods) that given object can (methods) that given object can performperform

Also called "contract" for supplying a Also called "contract" for supplying a set of operationsset of operations

Defines abstract behaviorDefines abstract behavior

Interfaces provide abstractionsInterfaces provide abstractions

You shouldn't have to know anything You shouldn't have to know anything about what is in the implementation about what is in the implementation in order to use itin order to use it 28

Page 29: 20 Object-oriented programming principles

Abstract Classes in C#Abstract Classes in C# Abstract classes are special classes Abstract classes are special classes

defined with the keyword defined with the keyword abstractabstract Mix between class and interfaceMix between class and interface

Partially implemented or fully Partially implemented or fully unimplementedunimplemented

Not implemented methods are declared Not implemented methods are declared abstractabstract and are left empty and are left empty

Cannot be Cannot be instantiatedinstantiated Child classes should implement Child classes should implement

abstract methods or declare them as abstract methods or declare them as abstractabstract

29

Page 30: 20 Object-oriented programming principles

Abstract Data TypesAbstract Data Types Abstract Data Types (ADT) are data Abstract Data Types (ADT) are data

types defined by a set of types defined by a set of operations (interface)operations (interface)

Example:Example:

LinkedList<T>LinkedList<T>

+Add(item : Object)+Add(item : Object)+Remove(item : Object)+Remove(item : Object)+Clear()+Clear()……

«interface»«interface»IList<T>IList<T>

List<T>List<T>

30

Page 31: 20 Object-oriented programming principles

Inheritance HierarchiesInheritance Hierarchies Using inheritance we can create Using inheritance we can create

inheritance hierarchiesinheritance hierarchies Easily represented by UML class diagramsEasily represented by UML class diagrams

UML class diagramsUML class diagrams Classes are represented by rectangles Classes are represented by rectangles

containing their methods and datacontaining their methods and data

Relations between classes are shown as Relations between classes are shown as arrowsarrows

Closed triangle arrow means inheritanceClosed triangle arrow means inheritance

Other arrows mean some kind of Other arrows mean some kind of associationsassociations

31

Page 32: 20 Object-oriented programming principles

UML Class Diagram – UML Class Diagram – ExampleExample

32

Shape

#Position:Point

structPoint

+X:int+Y:int

+Point

interfaceISurfaceCalculatable

+CalculateSurface:float

Rectangle

-Width:float-Height:float

+Rectangle+CalculateSurface:float

Square

-Size:float

+Square+CalculateSurface:float

FilledSquare

-Color:Color

+FilledSquare

structColor

+RedValue:byte+GreenValue:byte+BlueValue:byte

+Color

FilledRectangle

-Color:Color

+FilledRectangle

Page 33: 20 Object-oriented programming principles

Class Class Diagrams Diagrams in Visual in Visual StudioStudioLive DemoLive Demo

Page 34: 20 Object-oriented programming principles

EncapsulatioEncapsulationn

Page 35: 20 Object-oriented programming principles

EncapsulationEncapsulation Encapsulation hides the Encapsulation hides the

implementation detailsimplementation details Class announces some operations Class announces some operations

(methods) available for its clients – (methods) available for its clients – its its public interfacepublic interface

All data members (fields) of a class All data members (fields) of a class should be hiddenshould be hidden Accessed via properties (read-only Accessed via properties (read-only

and read-write)and read-write) No interface members should be No interface members should be

hiddenhidden 35

Page 36: 20 Object-oriented programming principles

Encapsulation – Encapsulation – ExampleExample

Data fields are privateData fields are private Constructors and accessors are Constructors and accessors are

defined (getters and setters)defined (getters and setters)

PersonPerson

-name : string-name : string-age : TimeSpan-age : TimeSpan

+Person(string name, int +Person(string name, int age)age)+Name : string { get; +Name : string { get; set; }set; }+Age : TimeSpan { get; set; +Age : TimeSpan { get; set; }}

36

Page 37: 20 Object-oriented programming principles

Encapsulation in .NETEncapsulation in .NET Fields are always declared Fields are always declared privateprivate

Accessed Accessed through through propertiesproperties in in read-only or read-write moderead-only or read-write mode

Constructors are almost always Constructors are almost always declared declared publicpublic

Interface methods are always Interface methods are always publicpublic Not explicitly declared with Not explicitly declared with publicpublic

Non-interfaceNon-interface methods are methods are declared declared privateprivate / / protectedprotected

37

Page 38: 20 Object-oriented programming principles

Encapsulation – Encapsulation – BenefitsBenefits

Ensures that structural changes remain Ensures that structural changes remain local:local: Changing the class internals does not Changing the class internals does not

affect any code outside of the classaffect any code outside of the class

Changing methods' implementation Changing methods' implementation does not reflect the clients using themdoes not reflect the clients using them

Encapsulation allows adding some logic Encapsulation allows adding some logic when accessing client's datawhen accessing client's data

E.g. validation on modifying a property E.g. validation on modifying a property valuevalue

Hiding implementation details reduces Hiding implementation details reduces complexity complexity easier maintenance easier maintenance 38

Page 39: 20 Object-oriented programming principles

PolymorphisPolymorphismm

Page 40: 20 Object-oriented programming principles

PolymorphismPolymorphism PolymorphismPolymorphism = ability to take more than = ability to take more than

one form (objects have more than one type)one form (objects have more than one type)

A class can be used through its parent A class can be used through its parent interfaceinterface

A child class may override some of the A child class may override some of the behaviors of the parent classbehaviors of the parent class

Polymorphism allows abstract operations to Polymorphism allows abstract operations to be defined and usedbe defined and used

Abstract operations are defined in the base Abstract operations are defined in the base class' interface and implemented in the child class' interface and implemented in the child classesclasses

Declared as Declared as abstractabstract or or virtualvirtual40

Page 41: 20 Object-oriented programming principles

Polymorphism (2)Polymorphism (2) Why handle an object of given type as Why handle an object of given type as

object of its base type?object of its base type? To invoke abstract operationsTo invoke abstract operations

To mix different related types in the To mix different related types in the same collectionsame collection

E.g. E.g. List<object>List<object> can hold anything can hold anything

To pass more specific object to a To pass more specific object to a method that expects a parameter of a method that expects a parameter of a more generic typemore generic type

To declare a more generic field which To declare a more generic field which will be initialized and "specialized" laterwill be initialized and "specialized" later

41

Page 42: 20 Object-oriented programming principles

Virtual MVirtual Methodethodss Virtual method is method that can be Virtual method is method that can be

used in the same way on instances of used in the same way on instances of base and derived classes but its base and derived classes but its implementation is differentimplementation is different

A A method is said to be a virtual method is said to be a virtual when when it is declared as it is declared as virtualvirtual

MethodsMethods that are that are declared as virtual declared as virtual in a base class canin a base class can be overridden be overridden using the keyword using the keyword overrideoverride in the in the derived classderived class

42

public virtual void CalculateSurface()public virtual void CalculateSurface()

Page 43: 20 Object-oriented programming principles

The The overrideoverride Modifier Modifier UsingUsing overrideoverride we can modify a we can modify a

method or property method or property An override method provides a new An override method provides a new

implementation of a member implementation of a member inherited from a base class inherited from a base class

You cannot override a non-virtual You cannot override a non-virtual or static method or static method

The overridden base method must The overridden base method must be virtual, abstract, or overridebe virtual, abstract, or override

43

Page 44: 20 Object-oriented programming principles

Polymorphism – How it Polymorphism – How it Works?Works?

Polymorphism ensures that the Polymorphism ensures that the appropriate method of the subclass is appropriate method of the subclass is called through its base class' interfacecalled through its base class' interface

Polymorphism is implemented using a Polymorphism is implemented using a technique called technique called late method bindinglate method binding Exact method to be called is determined Exact method to be called is determined

at at runtimeruntime, just before performing the call, just before performing the call

Applied for all Applied for all abstractabstract / / virtualvirtual methods methods Note: Late binding is slower than normal Note: Late binding is slower than normal

(early) binding(early) binding

44

Page 45: 20 Object-oriented programming principles

Polymorphism – Polymorphism – ExampleExample

override CalcSurface() override CalcSurface() {{ return size * size;return size * size;}}

override CalcSurface() override CalcSurface() {{ return PI * radius * raduis;return PI * radius * raduis;}}

AbstraAbstract ct

classclass

AbstraAbstract ct

actionaction

ConcretConcrete classe class

OverridOverriden en

actionaction

OverridOverriden en

actionaction

FigureFigure

+CalcSurface() : +CalcSurface() :

doubledouble

SquareSquare-x : int-x : int-y : int-y : int-size : -size : intint

CircleCircle-x : int-x : int-y : int-y : int-radius: -radius: intint

45

Page 46: 20 Object-oriented programming principles

Polymorphism – Polymorphism – Example (2)Example (2)

46

abstract class Figure abstract class Figure { { public public abstractabstract double CalcSurface(); double CalcSurface(); }}

abstract class Square abstract class Square { { public public overrideoverride double CalcSurface() { return double CalcSurface() { return … }… }}}

Figure f1 = new Square(...);Figure f1 = new Square(...);Figure f2 = new Circle(...);Figure f2 = new Circle(...);

// This will call Square.CalcSurface()// This will call Square.CalcSurface()int surface = f1.CalcSurface();int surface = f1.CalcSurface();

// This will call Square.CalcSurface()// This will call Square.CalcSurface()int surface = f2.CalcSurface();int surface = f2.CalcSurface();

Page 47: 20 Object-oriented programming principles

PolymorphisPolymorphismm

Live DemoLive Demo

Page 48: 20 Object-oriented programming principles

Class Class Hierarchies:Hierarchies:Real World Real World ExampleExample

Page 49: 20 Object-oriented programming principles

Real World Example: Real World Example: CalculatorCalculator

Creating an application like the Creating an application like the Windows CalculatorWindows Calculator Typical scenario for applying the Typical scenario for applying the

object-oriented approachobject-oriented approach

49

Page 50: 20 Object-oriented programming principles

Real World Example: Real World Example: Calculator (2)Calculator (2)

The calculator consists of controls:The calculator consists of controls: Buttons, panels, text boxes, menus, Buttons, panels, text boxes, menus,

check boxes, radio buttons, etc.check boxes, radio buttons, etc. Class Class ControlControl – the root of our OO – the root of our OO

hierarchyhierarchy All controls can be painted on the screenAll controls can be painted on the screen

Should implement an interfaceShould implement an interface IPaintableIPaintable with a method with a method Paint()Paint()

Common properties: location, size, text, Common properties: location, size, text, face color, font, background color, etc.face color, font, background color, etc.

50

Page 51: 20 Object-oriented programming principles

Real World Example: Real World Example: Calculator (3)Calculator (3)

Some controls could contain other Some controls could contain other (nested) controls inside (e. g. panels and (nested) controls inside (e. g. panels and toolbars)toolbars) We should have class We should have class ContainerContainer that that

extends extends ControlControl holding a collection of holding a collection of child controlschild controls

The The CalculatorCalculator itself is a itself is a FormForm FormForm is a special kind of is a special kind of ContainerContainer Contains also border, title (Contains also border, title (texttext derived derived

from from ControlControl), icon and system buttons ), icon and system buttons How the How the CalculatorCalculator paints itself? paints itself?

Invokes Invokes Paint()Paint() for all child controls inside for all child controls inside itit 51

Page 52: 20 Object-oriented programming principles

Real World Example: Real World Example: Calculator (4)Calculator (4)

How a How a ContainerContainer paints itself? paints itself? Invokes Invokes Paint()Paint() for all controls inside itfor all controls inside it

Each control knows how to visualize Each control knows how to visualize itselfitself

What is the common between buttons, What is the common between buttons, check boxes and radio buttons?check boxes and radio buttons? Can be pressedCan be pressed

Can be selectedCan be selected We can define class We can define class AbstractButtonAbstractButton

and all buttons can derive from itand all buttons can derive from it52

Page 53: 20 Object-oriented programming principles

Calculator Classes Calculator Classes

53

TextBoxTextBox

Paint()Paint()

«interface»«interface» IPaintableIPaintable

-location-location-size-size-text-text-bgColor-bgColor-faceColor-faceColor-font-font

ControlControl

ContainerContainer

FormForm

CalculatorCalculator

AbstractButtonAbstractButton

ButtonButton CheckBoxCheckBox RadioButtonRadioButton

MainMenuMainMenu MenuItemMenuItem

PanelPanel

Page 54: 20 Object-oriented programming principles

Cohesion and Cohesion and CouplingCoupling

Page 55: 20 Object-oriented programming principles

CohesionCohesion Cohesion describes how closely all Cohesion describes how closely all

the routines in a class or all the code the routines in a class or all the code in a routine support a central purposein a routine support a central purpose

Cohesion must be strongCohesion must be strong Well-defined abstractions keep Well-defined abstractions keep

cohesion strongcohesion strong Classes must contain strongly related Classes must contain strongly related

functionality and aim for single functionality and aim for single purposepurpose

Cohesion is a useful tool for Cohesion is a useful tool for managing complexity managing complexity

55

Page 56: 20 Object-oriented programming principles

Good and Bad CohesionGood and Bad Cohesion

Good: hard disk, cdrom, floppyGood: hard disk, cdrom, floppy

BAD: spaghetti codeBAD: spaghetti code

56

Page 57: 20 Object-oriented programming principles

Strong CohesionStrong Cohesion Strong cohesion exampleStrong cohesion example

Class Class MathMath that has methods: that has methods:Sin()Sin(), , Cos()Cos(), , Asin()Asin()

Sqrt()Sqrt(), , Pow()Pow(), , Exp()Exp()

Math.PIMath.PI, , Math.EMath.E

57

double sideA = 40, sideB = 69;double sideA = 40, sideB = 69;double angleAB = Math.PI / 3;double angleAB = Math.PI / 3;

double sideC = double sideC = Math.Pow(sideA, 2) + Math.Pow(sideB, 2) Math.Pow(sideA, 2) + Math.Pow(sideB, 2) - 2 * sideA * sideB * Math.Cos(angleAB);- 2 * sideA * sideB * Math.Cos(angleAB);

double sidesSqrtSum = Math.Sqrt(sideA) + double sidesSqrtSum = Math.Sqrt(sideA) + Math.Sqrt(sideB) + Math.Sqrt(sideC);Math.Sqrt(sideB) + Math.Sqrt(sideC);

Page 58: 20 Object-oriented programming principles

Bad CohesionBad Cohesion Bad cohesion exampleBad cohesion example

Class Class MagicMagic that has these that has these methods:methods:

Another example:Another example:

58

public void PrintDocument(Document d);public void PrintDocument(Document d);

public void SendEmail(public void SendEmail(

string recipient, string subject, string text);string recipient, string subject, string text);

public void CalculateDistanceBetweenPoints(public void CalculateDistanceBetweenPoints(

int x1, int y1, int x2, int y2)int x1, int y1, int x2, int y2)

MagicClass.MakePizza("Fat Pepperoni");MagicClass.MakePizza("Fat Pepperoni");

MagicClass.WithdrawMoney("999e6");MagicClass.WithdrawMoney("999e6");

MagicClass.OpenDBConnection();MagicClass.OpenDBConnection();

Page 59: 20 Object-oriented programming principles

CouplingCoupling Coupling describes how tightly a Coupling describes how tightly a

class or routine is related to other class or routine is related to other classes or classes or routinesroutines

Coupling must be kept looseCoupling must be kept loose Modules must depend little on each Modules must depend little on each

other other

All classes and routines must have All classes and routines must have small, direct, visible, and flexible small, direct, visible, and flexible relations to other classes and routinesrelations to other classes and routines

One module must be easily used by One module must be easily used by other modulesother modules

59

Page 60: 20 Object-oriented programming principles

Loose and Tight Loose and Tight CouplingCoupling

Loose Coupling:Loose Coupling:

Easily replace old HDDEasily replace old HDD

Easily place this HDD to Easily place this HDD to

another motherboardanother motherboard

Tight Coupling:Tight Coupling:

Where is the video Where is the video

adapter?adapter?

Can you change the Can you change the

video controller?video controller?60

Page 61: 20 Object-oriented programming principles

Loose Coupling – Loose Coupling – ExampleExample

class Reportclass Report{{ public bool LoadFromFile(string fileName) {…}public bool LoadFromFile(string fileName) {…} public bool SaveToFile(string fileName) {…}public bool SaveToFile(string fileName) {…}}}

class Printerclass Printer{{ public static int Print(Report report) {…}public static int Print(Report report) {…}}}

class Programclass Program{ { static void Main()static void Main() {{ Report myReport = new Report(); Report myReport = new Report(); myReport.LoadFromFile("C:\\DailyReport.rep");myReport.LoadFromFile("C:\\DailyReport.rep"); Printer.Print(myReport);Printer.Print(myReport); }}}}

61

Page 62: 20 Object-oriented programming principles

Tight Coupling – Tight Coupling – ExampleExample

class MathParamsclass MathParams{{ public static double operand;public static double operand; public static double result;public static double result;}}

class MathUtilclass MathUtil{{ public static void Sqrt()public static void Sqrt() {{ MathParams.result = CalcSqrt(MathParams.operand);MathParams.result = CalcSqrt(MathParams.operand); }}} }

class MainClassclass MainClass{{ static void Main()static void Main() {{ MathParams.operand = 64;MathParams.operand = 64; MathUtil.Sqrt();MathUtil.Sqrt(); Console.WriteLine(MathParams.result);Console.WriteLine(MathParams.result); }}}}

62

Page 63: 20 Object-oriented programming principles

Spaghetti CodeSpaghetti Code Combination of bad cohesion and tight coupling:Combination of bad cohesion and tight coupling:

63

class Reportclass Report{{ public void Print() {…}public void Print() {…} public void InitPrinter() {…}public void InitPrinter() {…} public void LoadPrinterDriver(string fileName) public void LoadPrinterDriver(string fileName) {…}{…} public bool SaveReport(string fileName) {…}public bool SaveReport(string fileName) {…} public void SetPrinter(string printer) {…}public void SetPrinter(string printer) {…}}}

class Printerclass Printer{{ public void SetFileName() {…}public void SetFileName() {…} public static bool LoadReport() {…}public static bool LoadReport() {…} public static bool CheckReport() {…}public static bool CheckReport() {…}}}

Page 64: 20 Object-oriented programming principles

SummarySummary OOP fundamental principals are: OOP fundamental principals are:

inheritance, encapsulation, abstraction, inheritance, encapsulation, abstraction, polymorphismpolymorphism Inheritance allows inheriting members Inheritance allows inheriting members

form another classform another class

Abstraction and encapsulation hide Abstraction and encapsulation hide internal data and allow working through internal data and allow working through abstract interfaceabstract interface

Polymorphism allows working with objects Polymorphism allows working with objects through their parent interface and invoke through their parent interface and invoke abstract actionsabstract actions

Strong cohesion and loose coupling avoid Strong cohesion and loose coupling avoid spaghetti codespaghetti code 64

Page 65: 20 Object-oriented programming principles

Object-Oriented Object-Oriented Programming Programming

Fundamental ConceptsFundamental Concepts

Questions?Questions?http://academy.telerik.com

Page 66: 20 Object-oriented programming principles

ExercisesExercises1.1. We are given a school. In the school there are We are given a school. In the school there are

classes of students. Each class has a set of classes of students. Each class has a set of teachers. Each teacher teaches a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique disciplines. Students have name and unique class number. Classes have unique text class number. Classes have unique text identifier. Teachers have name. Disciplines identifier. Teachers have name. Disciplines have name, number of lectures and number have name, number of lectures and number of exercises. Both teachers and students are of exercises. Both teachers and students are people.people.

Your task is to identify the classes (in terms Your task is to identify the classes (in terms of OOP) and their attributes and operations, of OOP) and their attributes and operations, define the class hierarchy and create a class define the class hierarchy and create a class diagram with Visual Studio.diagram with Visual Studio.

66

Page 67: 20 Object-oriented programming principles

Exercises (2)Exercises (2)2.2. Define class Define class HumanHuman with first name and last with first name and last

name. Define new class name. Define new class StudentStudent which is which is derived from derived from HumanHuman and has new field – and has new field – gradegrade. Define class . Define class WorkerWorker derived from derived from HumanHuman with new field with new field weekSalaryweekSalary and work- and work-hours per day and method hours per day and method MoneyPerHourMoneyPerHour()() that returns money earned by hour by the that returns money earned by hour by the worker. Define the proper constructors and worker. Define the proper constructors and properties for this hierarchy. Initialize an properties for this hierarchy. Initialize an array of 10 students and sort them by array of 10 students and sort them by grade in ascending order. Initialize an array grade in ascending order. Initialize an array of 10 workers and sort them by money per of 10 workers and sort them by money per hour in descending order.hour in descending order. 67

Page 68: 20 Object-oriented programming principles

Exercises (3)Exercises (3)3.3. Define abstract class Define abstract class ShapeShape with only one with only one

virtual method virtual method CalculateSurface()CalculateSurface() and fields and fields widthwidth and and heightheight. Define two new classes . Define two new classes TriangleTriangle and and RectangleRectangle that implement the that implement the virtualvirtual method and return the surface of the method and return the surface of the figure (height*width for rectangle and figure (height*width for rectangle and height*width/2 for triangle). Define class height*width/2 for triangle). Define class CircleCircle and suitable constructor so that on and suitable constructor so that on initialization initialization heightheight must be kept equal to must be kept equal to widthwidth and implement the and implement the CalculateSurface()CalculateSurface() method. Write a program that tests the method. Write a program that tests the behavior of the behavior of the CalculateSurface(CalculateSurface()) method method for different shapesfor different shapes ((CircleCircle, , RectangleRectangle, , TriangleTriangle) stored in an array.) stored in an array.

68

Page 69: 20 Object-oriented programming principles

Exercises (4)Exercises (4)4.4. Create a hierarchy Create a hierarchy DogDog, , FrogFrog, , CatCat, , KittenKitten, ,

TomcatTomcat and define suitable constructors and and define suitable constructors and methods according to the following rules: methods according to the following rules: all of this are Animals. Kittens and tomcats all of this are Animals. Kittens and tomcats are cats. All animals are described by age, are cats. All animals are described by age, name and sex. Kittens can be only female name and sex. Kittens can be only female and tomcats can be only male. Each animal and tomcats can be only male. Each animal produce a sound. Create arrays of different produce a sound. Create arrays of different kinds of animals and calculate the average kinds of animals and calculate the average age of each kind of animal using static age of each kind of animal using static methods. Create static method in the methods. Create static method in the animal class that identifies the animal by animal class that identifies the animal by its sound.its sound. 69

Page 70: 20 Object-oriented programming principles

Exercises (5)Exercises (5)

5.5. A bank holds different types of A bank holds different types of accounts for its customers: deposit accounts for its customers: deposit accounts, loan accounts and mortgage accounts, loan accounts and mortgage accounts. Customers could be accounts. Customers could be individuals or companies.individuals or companies.

All accounts have customer, balance All accounts have customer, balance and interest rate (monthly based). and interest rate (monthly based). Deposit accounts are allowed to deposit Deposit accounts are allowed to deposit and with draw money. Loan and and with draw money. Loan and mortgage accounts can only deposit mortgage accounts can only deposit money.money.

70

Page 71: 20 Object-oriented programming principles

Exercises (6)Exercises (6)All accounts can calculate their interest All accounts can calculate their interest amount for a given period (in months). In the amount for a given period (in months). In the common case its is calculated as follows: common case its is calculated as follows: number_of_months * interest_rate.number_of_months * interest_rate.

Loan accounts have no interest for the first 3 Loan accounts have no interest for the first 3 months if are held by individuals and for the months if are held by individuals and for the first 2 months if are held by a company.first 2 months if are held by a company.

Deposit accounts have no interest if their Deposit accounts have no interest if their balance is positive and less than 1000.balance is positive and less than 1000.

Mortgage accounts have ½ interest for the Mortgage accounts have ½ interest for the first 12 months for companies and no interest first 12 months for companies and no interest for the first 6 months for individuals.for the first 6 months for individuals.

71

Page 72: 20 Object-oriented programming principles

Exercises (7)Exercises (7)

Your task is to write a program to Your task is to write a program to model the bank system by classes and model the bank system by classes and interfaces. You should identify the interfaces. You should identify the classes, interfaces, base classes and classes, interfaces, base classes and abstract actions and implement the abstract actions and implement the calculation of the interest functionality.calculation of the interest functionality.

72


Recommended