Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Svetlin Nakov Telerik Corporation
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
Svetlin Nakov Telerik Corporation
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Chapter 10 Classes Continued
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
C++ fundamentals.
Namespaces, Cohesion and Coupling Veselin Georgiev National Academy for Software Development academy.devbg.org Svetlin Nakov Telerik Corporation
2.5 OOP Principles Part 2 academy.zariba.com 1. Lecture Content 1.Polymorphism 2.Cohesion 3.Coupling 2.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Svetlin Nakov Telerik Corporation
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Module 7: Essentials of Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Lecture 9 Polymorphism Richard Gesick.
CONCEPTS OF OBJECT ORIENTED PROGRAMMING. Topics To Be Discussed………………………. Objects Classes Data Abstraction and Encapsulation Inheritance Polymorphism.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Advanced Concepts Svetlin Nakov Telerik Corporation
Inheritance, Abstraction, Encapsulation, Polymorphism
High-Quality Classes and Class Hierarchies Best Practices in Object-Oriented Design SoftUni Team Technical Trainers Software University
Encapsulation and Polymorphism Encapsulation, Polymorphism, Class Hierarchies, Cohesion and Coupling SoftUni Team Technical Trainers Software University.
Best Practices in the Object-Oriented Design Learning & Development Telerik Software Academy.
Svetlin Nakov Telerik Software Academy Manager Technical Trainer
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object-Oriented Programming Chapter Chapter
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Introduction to Object-Oriented Programming Lesson 2.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling Telerik Software Academy Object-Oriented Programming.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Object-Oriented Programming: Inheritance and Polymorphism.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Object-Oriented Programming: Polymorphism Chapter 10.
Best Practices in the Object-Oriented Design Vesko Kolev Telerik Corporation
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Encapsulation and Polymorphism
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Abstract Classes, Abstract Methods, Override Methods
Modern Programming Tools And Techniques-I
Object-Oriented Programming Concepts
Inheritance and Polymorphism
Object-Oriented Programming
Classes in C++ C++ originally called "C with classes":
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object Oriented Programming
Object Oriented Analysis and Design
Lecture 23 Polymorphism Richard Gesick.
Classes in C++ C++ originally called "C with classes":
Week 6 Object-Oriented Programming (2): Polymorphism
Object-Oriented Programming: Inheritance and Polymorphism
Final and Abstract Classes
Computer Science II for Majors
Presentation transcript:

Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling

1. Polymorphism 2. Class Hierarchies: Real World Example 3. Exception Handling and Exception Classes 4. Cohesion and Coupling 2

 Polymorphism = ability to take more than one form (objects have more than one type)  A class can be used through its parent interface  A child class may override some of the behaviors of the parent class  Polymorphism allows abstract operations to be defined and invoked  Abstract operations are defined in the base class' interface and implemented in the child classes  Declared as abstract or virtual 4

 Why handle an object of given type as object of its base type?  To invoke abstract operations  To mix different related types in the same collection  E.g. List can hold anything  To pass more specific object to a method that expects a parameter of a more generic type  To declare a more generic field which will be initialized and "specialized" later 5

 Virtual method is  Defined in a base class and can be changed (overridden) in the descendant classes  Can be called through the base class' interface  Virtual methods are declared through the keyword virtual  Methods declared as virtual in a base class can be overridden using the keyword override 6 public virtual void Draw() { … } public override void Draw() { … }

Live Demo

 Abstract methods are purely virtual  If a method is abstract  it is virtual as well  Abstract methods are designed to be changed (overridden) later  Interface members are also purely virtual  They have no default implementation and are designed to be overridden in a descendent class  Virtual methods can be hidden through the new keyword: 8 public new double CalculateSurface() { return … }

 Using override we can modify a method or property  An override method provides a replacement implementation of an inherited member  You cannot override a non-virtual or static method  The overridden base method must be virtual, abstract, or override 9

 Polymorphism ensures that the appropriate method of the subclass is called through its base class' interface  Polymorphism is implemented using a technique called late method binding  The exact method to be called is determined at runtime, just before performing the call  Applied for all abstract / virtual methods  Note: Late binding is a bit slower than normal (early) binding 10

override … CalcSurface() { return size * size; return size * size;} override double CalcSurface() { return PI * radius * raduis; return PI * radius * raduis;} Abstract class Abstract action Concrete class Overriden action Figure Square -x : int -y : int -size : int Circle -x : int -y : int -radius: int 11 +CalcSurface() : double

12 abstract class Figure { public abstract double CalcSurface(); public abstract double CalcSurface();} abstract class Square { public override double CalcSurface() { return … } public override double CalcSurface() { return … }} Figure f1 = new Square(...); Figure f2 = new Circle(...); // This will call Square.CalcSurface() int surface = f1.CalcSurface(); // This will call Square.CalcSurface() int surface = f2.CalcSurface();

Live Demo

 Creating an application like the Windows Calculator  Typical scenario for applying the object- oriented approach 15

 The calculator consists of controls:  Buttons, panels, text boxes, menus, check boxes, radio buttons, etc.  Class Control – the root of our OO hierarchy  All controls can be painted on the screen  Should implement an interface IPaintable with a method Paint()  Common properties: location, size, text, face color, font, background color, etc. 16

 Some controls could contain other (nested) controls inside (e. g. panels and toolbars)  We should have class Container that extends Control holding a collection of child controls  The Calculator itself is a Form  Form is a special kind of Container  Contains also border, title ( text derived from Control ), icon and system buttons  How the Calculator paints itself?  Invokes Paint() for all child controls inside it 17

 How a Container paints itself?  Invokes Paint() for all controls inside it  Each control knows how to visualize itself  What is the common between buttons, check boxes and radio buttons?  Can be pressed  Can be selected  We can define class AbstractButton and all buttons can derive from it 18

19 TextBox Paint() «interface» IPaintable IPaintable -location-size-text-bgColor-faceColor-font Control Container Form Calculator AbstractButton ButtonCheckBoxRadioButton MainMenuMenuItem Panel

User-Defined Exception Classes

 In OOP exception handling is the main paradigm for error handling  Exceptions are special classes that hold information about an error or unusual situation  Exceptions are thrown (raised) through the throw keyword  Exceptions are handled though the try- catch-finally and using(…) constructs 21 throw new InvalidCalculationException( "Cannot calculate the size of the specified object"); "Cannot calculate the size of the specified object");

 Exceptions in.NET Framework are organized in a object-oriented class hierarchy 22

 To define an exception class, inherit from ApplicationException and define constructors 23 using System; public class InvalidCalculationException : ApplicationException : ApplicationException{ public InvalidCalculationException(string msg) public InvalidCalculationException(string msg) : base(msg) : base(msg) { } { } public InvalidCalculationException(string msg, public InvalidCalculationException(string msg, Exception innerEx) : base(msg, innerEx) Exception innerEx) : base(msg, innerEx) { } { }}

Live Demo

 Cohesion describes  How closely the routines in a class or the code in a routine support a central purpose  Cohesion must be strong  Well-defined abstractions keep cohesion strong  Classes must contain strongly related functionality and aim for single purpose  Cohesion is a powerful tool for managing complexity 26

 Good cohesion: HDD, CR-ROM, remote control  Bad cohesion: spaghetti code, single-board computer 27

 Strong cohesion (good cohesion) example  Class Math that has methods: Sin(), Cos(), Asin() Sqrt(), Pow(), Exp() Math.PI, Math.E 28 double sideA = 40, sideB = 69; double angleAB = Math.PI / 3; 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) + Math.Sqrt(sideB) + Math.Sqrt(sideC);

 Weak cohesion (bad cohesion) example  Class Magic that has these methods:  Another example: 29 public void PrintDocument(Document d); public void Send ( string recipient, string subject, string text); string recipient, string subject, string text); public void CalculateDistanceBetweenPoints( int x1, int y1, int x2, int y2) int x1, int y1, int x2, int y2) MagicClass.MakePizza("Fat Pepperoni"); MagicClass.WithdrawMoney("999e6");MagicClass.OpenDBConnection();

 Coupling describes how tightly a class or routine is related to other classes or routines  Coupling must be kept loose  Modules must depend little on each other  Or be entirely independent (loosely coupled)  All classes / routines must have small, direct, visible, and flexible relationships to other classes / routines  One module must be easily used by other modules 30

 Loose Coupling:  Easily replace old HDD  Easily place this HDD to another motherboard  Tight Coupling:  Where is the video adapter?  Can you change the video controller? 31

class Report { public bool LoadFromFile(string fileName) {…} public bool LoadFromFile(string fileName) {…} public bool SaveToFile(string fileName) {…} public bool SaveToFile(string fileName) {…}} class Printer { public static int Print(Report report) {…} public static int Print(Report report) {…}} class 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); }} 32

class MathParams { public static double operand; public static double operand; public static double result; public static double result;} class MathUtil { public static void Sqrt() public static void Sqrt() { MathParams.result = CalcSqrt(MathParams.operand); MathParams.result = CalcSqrt(MathParams.operand); }} class 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); }} 33

 Combination of bad cohesion and tight coupling: 34 class 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 Printer { public void SetFileName() {…} public void SetFileName() {…} public static bool LoadReport() {…} public static bool LoadReport() {…} public static bool CheckReport() {…} public static bool CheckReport() {…}}

 OOP fundamental principals are: inheritance, encapsulation, abstraction, polymorphism  Inheritance allows inheriting members from another class  Abstraction and encapsulation hide internal data and allow working through abstract interface  Polymorphism allows working with objects through their parent interface and invoke abstract actions  Exception classes are natural to OOP  Strong cohesion and loose coupling avoid spaghetti code 35

Questions?

1. Define abstract class Shape with only one abstract method CalculateSurface() and fields width and height. Define two new classes Triangle and Rectangle that implement the virtual method and return the surface of the figure (height*width for rectangle and height*width/2 for triangle). Define class Circle and suitable constructor so that at initialization height must be kept equal to width and implement the CalculateSurface() method. Write a program that tests the behavior of the CalculateSurface() method for different shapes ( Circle, Rectangle, Triangle ) stored in an array. 37

2. A bank holds different types of accounts for its customers: deposit accounts, loan accounts and mortgage accounts. Customers could be individuals or companies. All accounts have customer, balance and interest rate (monthly based). Deposit accounts are allowed to deposit and with draw money. Loan and mortgage accounts can only deposit money. All accounts can calculate their interest amount for a given period (in months). In the common case its is calculated as follows: number_of_months * interest_rate. 38

Loan accounts have no interest for the first 3 months if are held by individuals and for the first 2 months if are held by a company. Deposit accounts have no interest if their balance is positive and less than Mortgage accounts have ½ interest for the first 12 months for companies and no interest for the first 6 months for individuals. Your task is to write a program to model the bank system by classes and interfaces. You should identify the classes, interfaces, base classes and abstract actions and implement the calculation of the interest functionality through overridden methods. 39

3. Define a class InvalidRangeException that holds information about an error condition related to invalid range. It should hold error message and a range definition [start … end]. Write a sample application that demonstrates the InvalidRangeException and InvalidRangeException by entering numbers in the range [1..100] and dates in the range [ … ]. 40

 C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com