View
218
Download
2
Category
Tags:
Preview:
Citation preview
Inheritance and Polymorphism
Namespaces, Cohesion and Coupling
Veselin GeorgievNational Academy for
Software Developmentacademy.devbg.org
Svetlin NakovTelerik
Corporationwww.telerik.com
Cohesion Cohesion describes how closely all the routines in a class or all the code in a routine support a central purpose Cohesion must be strong Classes must contain strongly
related functionality and aim for single purpose
Cohesion is a useful tool for managing complexity
Well-defined abstractions keep cohesion strong
4
Strong Cohesion Strong cohesion example
Class Math that has methods:
Sin(), Cos(), Asin(), Sqrt(), Pow(), Exp()
Math.PI, Math.Edouble sideA = 40, sideB = 69;double angleAB = Math.PI / 3;
double sideC = Math.Pow(sideA, 2) + Math.Pow(sideB, 2)
- 2 * sideA * sideB * Math.Cos(angleAB);
double sidesSqrtSum = Math.Sqrt(sideA) + Math.Sqrt(sideB) + Math.Sqrt(sideC);
6
Bad Cohesion Example of bad cohesion Class Magic that has all these methods:
Another example:MagicClass.MakePizza("Fat Pepperoni");
MagicClass.WithdrawMoney("999e6");
MagicClass.OpenDBConnection();
public void PrintDocument(Document d);
public void SendEmail(string recipient, string subject, string text);
public void CalculateDistanceBetweenPoints(int x1, int y1, int x2, int y2)
7
Coupling 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
All classes and routines must have small, direct, visible, and flexible relations to other classes and routines
One module must be easily used by other modules
8
Loose and Tight Coupling
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?
9
Loose Coupling – Example
class Report{ public bool LoadFromFile(string fileName) {…} public bool SaveToFile(string fileName) {…}}
class Printer{ public static int Print(Report report) {…}}
class Program{ static void Main() { Report myReport = new Report(); myReport.LoadFromFile("C:\\DailyReport.rep"); Printer.Print(myReport); }}
10
Tight Coupling – Example
class MathParams{ public static double operand; public static double result;}class MathUtil{ public static void Sqrt() { MathParams.result = CalcSqrt(MathParams.operand); }} class Example{ static void Main() { MathParams.operand = 64; MathUtil.Sqrt(); Console.WriteLine(MathParams.result); }}
11
Spaghetti Code
Combination of bad cohesion and tight couplingclass Report{ public void Print() {…} public void InitPrinter() {…} public void LoadPrinterDriver(string fileName) {…}
public bool SaveReport(string fileName) {…} public void SetPrinter(string printer) {…}}
class Printer{ public void SetFileName() {…} public static bool LoadReport() {…} public static bool CheckReport() {…}}
12
Inheritance Inheritance is the ability of a class to implicitly gain all members from another class
Inheritance is fundamental concept in OOP The class whose methods are inherited is called base (parent) class The class that gains new functionality is called derived (child) class
14
Inheritance (2) All class members are inherited
Fields, methods, properties, … In C# classes could be inherited
The structures in C# could not be inherited Inheritance allows creating deep inheritance hierarchies In .NET there is no multiple inheritance, except when implementing interfaces
15
Polymorphism Polymorphism is fundamental concept in OOP The ability to handle the objects of a specific class as instances of its parent class and to call abstract functionality
Polymorphism allows creating hierarchies with more valuable logical structure Allows invoking abstract functionality without caring how and where it is implemented
18
Polymorphism (2) Polymorphism is usually implemented through:
Virtual methods (virtual)
Abstract methods (abstract)
Methods from an interface (interface)
In C# to override virtual method the keyword override is used C# allows hiding virtual methods in derived classes by the keyword new
19
Polymorphism – Example
class Person { public virtual void PrintName() { Console.WriteLine("I am a person."); }}
class Trainer : Person{ public override void PrintName() { Console.WriteLine("I am a trainer."); }}
class Student : Person{ public override void PrintName() { Console.WriteLine("I am a student."); }}
20
Polymorphism – Example (2)
static void Main(){ Person person = new Person(); person.PrintName(); // I am a person.
Person trainer = new Trainer(); trainer.PrintName(); // I am a trainer.
Person student = new Student(); student.PrintName(); // I am a student.}
21
Namespaces Similar to namespaces in C++ and
packagesin Java
Ensure logical grouping of type definition aggregations
May contain classes, structures, interfaces, enumerators and other namespaces
Can not contain methods and data Allows definition of types with equal
names (they must be in different namespaces)
Can be allocated in one or several files
24
Namespaces (2) To include a namespace – using directive is used
using allows direct use of all types in the namespace
Including is applied to the current file
The directive is written at the begging of the file
When includes a namespace with using its subset of namespaces is not included
using System.Windows.Forms;
25
Namespaces (3)
Types, placed in namespaces, can be used and without using directive, by their full name:
using can create allies for namespaces :
using IO = System.IO;using WinForms = System.Windows.Forms;
IO.StreamReader reader = IO.File.OpenText("file.txt");
WinForms.Form form = new WinForms.Form();
System.IO.StreamReader reader = System.IO.File.OpenText("file.txt");
26
Namespaces – Practices
Divide the types in your applications in namespaces always when they are too much (above 15-20)
Classify the types logically in namespaces according to their purpose
If the types are too much use subsets of namespaces
27
Namespaces – Practices (2)
Distribute all public types in files identical with their names
Arrange the files in directories, corresponding to their namespaces
The directory structure from your project course-code have to reflect the structure of the defined namespaces
28
Namespaces – ExampleNamespaces – Examplenamespace SofiaUniversity.Data{ public struct Faculty { // ... } public class Student { // ... } public class Professor { // ... } public enum Specialty { // ... }}
Namespaces – Example (2)
Namespaces – Example (2)
namespace SofiaUniversity.UI{ public class StudentAdminForm :
System.Windows.Forms.Form { // ... } public class ProfessorAdminForm :
System.Windows.Forms.Form { // ... }}namespace SofiaUniversity { public class AdministrationSystem { public static void Main() { // ... } }}
Namespaces – Example (3)
Recommended directory structure and classes organization in them
Recommended directory structure and classes organization in them
31
Exercises
1. A bank holds different types of accounts for its customers: deposit accounts, loan accounts and mortgage accounts. Customers could be physical persons or companies.
All accounts have customer, balance and interest rate (monthly based). Deposit accounts are allowed to deposit and withdraw money. Loan and mortgage accounts can only deposit money.
All customers have name. Persons have social security number and monthly income. Companies have Bulstat.
33
Exercises (2)
All accounts can calculate their interest amount for a given period (in months). In the common case it is calculated as follows:
numberOfMonths * interestRate.
Loan accounts have no interest for the first 3 months if are held by persons 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 1000.
34
Exercises (3)
Mortgage accounts have ½ interest for the first 12 months for companies and no interest for the first 6 months for persons.
Your task is to write a program to model the bank system. You should identify the classes, base classes and abstract actions and implement the calculation of the interest for the different accounts.
35
Recommended