Best Practices in the Object-Oriented Design Learning & Development Telerik Software Academy.

Slides:



Advertisements
Similar presentations
Software Engineering Class design. Class design – ADT Abstract Data Types:  Why use ADT? Hidden implementation details Changes do not affect whole program.
Advertisements

Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
OBJECT-ORIENTED PROGRAMMING. What is an “object”? Abstract entity that contains data and actions Attributes (characteristics) and methods (functions)
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Object-Oriented PHP (1)
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
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.
Svetlin Nakov Telerik Corporation
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 12 Object-Oriented Design.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Lecture 9 Polymorphism Richard Gesick.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Quality Code academy.zariba.com 1. Lecture Content 1.Software Quality 2.Code Formatting 3.Correct Naming 4.Documentation and Comments 5.Variables, Expressions.
Advanced Concepts Svetlin Nakov Telerik Corporation
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
High-Quality Classes and Class Hierarchies Best Practices in Object-Oriented Design SoftUni Team Technical Trainers Software University
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Encapsulation and Polymorphism Encapsulation, Polymorphism, Class Hierarchies, Cohesion and Coupling SoftUni Team Technical Trainers Software University.
Best Practices. Contents Bad Practices Good Practices.
Design.ppt1 Top-down designs: 1. Define the Problem IPO 2. Identify tasks, Modularize 3. Use structure chart 4. Pseudocode for Mainline 5. Construct pseudocode.
Good Design of Classes Classes let us create Abstract Data Types Should be well aware of benefits – Hide implementation details – Localize changes – Interface.
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Object-Oriented Programming Chapter Chapter
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
Object Oriented Programming
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
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.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling Telerik Software Academy Object-Oriented Programming.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Lecture 12 Implementation Issues with Polymorphism.
Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling.
Best Practices in the Object-Oriented Design Vesko Kolev Telerik Corporation
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Encapsulation and Polymorphism
Working Classes SCMP Special Topic: Software Development
Object-Oriented Programming Concepts
Module Road Map Refactoring Why Refactoring? Examples
MPCS – Advanced java Programming
Inheritance and Polymorphism
Data Abstraction: The Walls
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Lecture 23 Polymorphism Richard Gesick.
Object-Oriented Programming
CIS 199 Final Review.
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Best Practices in the Object-Oriented Design Learning & Development Telerik Software Academy

1. Basic Principles  Cohesion, Coupling, Inheritance, Polymorphism 2. High-Quality Classes  Good Abstraction, Correct Encapsulation, Correct Inheritance  Class Methods, Constructors, Data  Good Reasons to Create a Class 3. Typical Mistakes to Avoid in OO Design

Cohesion, Coupling, Inheritance and Polymorphism

 Cohesion measures how closely are all the routines in a class/module  Cohesion must be strong  Classes must contain strongly related functionality and aim for single purpose  Strong cohesion is a useful tool for managing complexity  Well-defined abstractions keep cohesion strong  Bad abstractions have weak cohesion 4

 Good: hard disk, CD-ROM, floppy  Bad: spaghetti code 5

 Strong cohesion example  Class System.Math  Sin(), Cos(), Asin()  Sqrt(), Pow(), Exp()  Math.PI, Math.E 6 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);

 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 relationships to other classes and routines  One module must be easily used by other modules, without complex dependencies 7

 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 on this MB? 8

9 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); }}

10 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); }}… MathParams.operand = 64; MathUtil.Sqrt();Console.WriteLine(MathParams.result);

 Inheritance is the ability of a class to implicitly gain all members from another class  Inheritance is principal 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  Use inheritance to:  Reuse repeating code: data and program logic  Simplify code maintenance 11

 In C# all class members are inherited  Fields, methods, properties, etc.  Structures cannot be inherited, only classes  No multiple inheritance is supported  Only multiple interface implementations  In JS inheritance is supported indirectly  Several ways to implement inheritance  Multiple inheritance is not supported  There are no interfaces (JS is typeless language) 12

 Polymorphism is a principal concept in OOP  The ability to handle the objects of a specific class as instances of its parent class  To call abstract functionality  Polymorphism allows to create hierarchies with more valuable logical structure  Polymorphism is a tool to enable code reuse  Common logic is taken to the base class  Specific logic is implemented in the derived class in a overridden method 13

 In C# polymorphism is implemented through:  Virtual methods ( virtual )  Abstract methods ( abstract )  Interfaces methods ( interface )  In C# override overrides a virtual method  In JavaScript all methods are virtual  The child class can just "override" any method from any object  There are no interfaces (JS is typeless language) 14

15 class Person { public virtual void PrintName() public virtual void PrintName() { Console.Write("I am a person."); Console.Write("I am a person."); }} class Trainer : Person { public override void PrintName() public override void PrintName() { Console.Write( Console.Write( "I am a trainer. " + base.PrintName()); "I am a trainer. " + base.PrintName()); }} class Student : Person { public override void PrintName() public override void PrintName() { Console.WriteLine("I am a student."); Console.WriteLine("I am a student."); }}

How to Design High-Quality Classes? Abstraction, Cohesion and Coupling

 Present a consistent level of abstraction in the class contract (publicly visible members)  What abstraction the class is implementing?  Does it represent only one thing?  Does the class name well describe its purpose?  Does the class define clear and easy to understand public interface?  Does the class hide all its implementation details? 17

18 public class Font { public string Name { get; set; } public string Name { get; set; } public float SizeInPoints { get; set; } public float SizeInPoints { get; set; } public FontStyle Style { get; set; } public FontStyle Style { get; set; } public Font( public Font( string name, float sizeInPoints, FontStyle style) string name, float sizeInPoints, FontStyle style) { this.Name = name; this.Name = name; this.SizeInPoints = sizeInPoints; this.SizeInPoints = sizeInPoints; this.Style = style; this.Style = style; } public void DrawString(DrawingSurface surface, public void DrawString(DrawingSurface surface, string str, int x, int y) { … } string str, int x, int y) { … } public Size MeasureString(string str) { … } public Size MeasureString(string str) { … }}

19 public class Program { public string title; public string title; public int size; public int size; public Color color; public Color color; public void InitializeCommandStack(); public void InitializeCommandStack(); public void PushCommand(Command command); public void PushCommand(Command command); public Command PopCommand(); public Command PopCommand(); public void ShutdownCommandStack(); public void ShutdownCommandStack(); public void InitializeReportFormatting(); public void InitializeReportFormatting(); public void FormatReport(Report report); public void FormatReport(Report report); public void PrintReport(Report report); public void PrintReport(Report report); public void InitializeGlobalData(); public void InitializeGlobalData(); public void ShutdownGlobalData(); public void ShutdownGlobalData();} Does this class really represents a "program"? Is this name good? Does this class really have a single purpose?

 Define operations along with their opposites, e.g.  Open() and Close()  Move unrelated methods in another class, e.g.  In class Employee if you need to calculate Age by given DateOfBirth  Create а static method CalcAgeByBirthDate(…) in a separate class DateUtils  Group related methods intro a single class  Does the class name correspond to the class content? 20

 Beware of breaking the interface abstraction due to evolution  Don't add public members inconsistent with abstraction  Example: in class called Employee at some time we add method for accessing the DB with SQL 21 class Employee { public string FirstName { get; set; } public string FirstName { get; set; } public string LastName; { get; set; } public string LastName; { get; set; } … public SqlCommand FindByPrimaryKeySqlCommand(int id); public SqlCommand FindByPrimaryKeySqlCommand(int id);}

 Minimize visibility of classes and members  In C# start from private and move to internal, protected and public if required  Classes should hide their implementation details  A principle called encapsulation in OOP  Anything which is not part of the class interface should be declared private  Classes with good encapsulated classes are: less complex, easier to maintain, more loosely coupled  Classes should keep their state clean  throw an exception if invalid data is being assigned 22

 Never declare fields public (except constants)  Use properties / methods to access the fields  Don't put private implementation details in the public interface  All public members should be consistent with the abstraction represented by the class  Don't make a method public just because it calls only public methods  Don't make assumptions about how the class will be used or will not be used 23

 Don't violate encapsulation semantically!  Don't rely on non-documented internal behavior or side effects  Wrong example:  Skip calling ConnectToDB() because you just called FindEmployeeById() which should open connection  Another wrong example:  Use String.Empty instead of Titles.NoTitle because you know both values are the same 24

 Containment is "has a" relationship  Example: Keyboard has a set of Key s  Inheritance is "is a" relationship  Design for inheritance: make the class abstract  Disallow inheritance: make the class sealed  Subclasses must be usable through the base class interface  Without the need for the user to know the difference 25

 Don't hide methods in a subclass  Example: if the class Timer has private method Start(), don't define Start() in AtomTimer  Move common interfaces, data, and behavior as high as possible in the inheritance tree  This maximizes the code reuse  Be suspicious of base classes of which there is only one derived class  Do you really need this additional level of inheritance? 26

 Be suspicious of classes that override a routine and do nothing inside  Is the overridden routine used correctly?  Avoid deep inheritance trees  Don't create more than 6 levels of inheritance  Avoid using a base class’s protected data fields in a derived class  Provide protected accessor methods or properties instead 27

 Prefer inheritance to extensive type checking:  Consider inheriting Circle and Square from Shape and override the abstract action Draw() 28 switch (shape.Type) { case Shape.Circle: case Shape.Circle: shape.DrawCircle(); shape.DrawCircle(); break; break; case Shape.Square: case Shape.Square: shape.DrawSquare(); shape.DrawSquare(); break; break;......}

 Keep the number of methods in a class as small as possible  reduce complexity  Minimize direct methods calls to other classes  Minimize indirect methods calls to other classes  Less external method calls == less coupling  Also known as "fan-out"  Minimize the extent to which a class collaborates with other classes  Reduce the coupling between classes 29

 Initialize all member data in all constructors, if possible  Uninitialized data is error prone  Partially initialized data is even more evil  Incorrect example: assign FirstName in class Person but leave LastName empty  Initialize data members in the same order in which they are declared  Prefer deep copies to shallow copies ( ICloneable should make deep copy) 30

 Use private constructor to prohibit direct class instantiation  Use design patterns for common design situations  Creational patterns like Singleton, Factory Method, Abstract Factory  Structural patterns like Adapter, Bridge, Composite, Decorator, Façade  Behavioral patterns like Command, Iterator, Observer, Strategy, Template Method 31

 Model real-world objects with OOP classes  Model abstract objects, processes, etc.  Reduce complexity  Work at higher level  Isolate complexity  Hide it in a class  Hide implementation details  encapsulation  Limit effects of changes  Changes affect only their class 32

 Hide global data  Work through methods  Group variables that are used together  Make central points of control  Single task should be done at single place  Avoid duplicating code  Facilitate code reuse  Use class hierarchies and virtual methods  Package related operations together 33

 Group related classes together in namespaces  Follow consistent naming convention 34 namespace Utils { class MathUtils { … } class MathUtils { … } class StringUtils { … } class StringUtils { … }} namespace DataAccessLayer { class GenericDAO { … } class GenericDAO { … } class EmployeeDAO { … } class EmployeeDAO { … } class AddressDAO { … } class AddressDAO { … }}

Lessons Learned from the OOP Exam at Telerik Software Academy

 Never use plural in class names unless they hold some kind of collection!  Bad example:  Good example: 36 public class Teachers : ITeacher { public string Name { get; set; } public string Name { get; set; } public List Courses { get; set; } public List Courses { get; set; }} Singular: Teacher (a single teacher, not several). public class GameFieldConstants { public const int MIN_X = 100; public const int MIN_X = 100; public const int MAX_X = 700; public const int MAX_X = 700;}

 Don't throw exception without parameters: 37 public ICourse CreateCourse(string name, string town) { if (name == null) if (name == null) { throw new ArgumentNullException(); throw new ArgumentNullException(); } if (town == null) if (town == null) { throw new ArgumentNullException(); throw new ArgumentNullException(); } return new Course(name, town); return new Course(name, town);} Which parameter is null here?

 Check for invalid data in the setters and constructors, not in the getter! 38 public string Town { get get { if (string.IsNullOrWhiteSpace(this.town)) if (string.IsNullOrWhiteSpace(this.town)) throw new ArgumentNullException(); throw new ArgumentNullException(); return this.town; return this.town; } set set { this.town = value; this.town = value; }} Put this check in the setter!

 Always use this.XXX instead of XXX to access members within the class: 39 public class Course { public string Name { get; set; } public string Name { get; set; } public Course(string name) public Course(string name) { Name = name; Name = name; }} Use this.Name

 Use null when a value is missing, not 0 or ""  Make a field / property nullable to access null values or just disallow missing values  Bad example:  Correct alternatives: 40 Teacher teacher = new Teacher(""); Teacher teacher = new Teacher(); Teacher teacher = new Teacher(null); Empty name is very bad idea! Use null.

 Don't use "magic" numbers  Especially when the class has members related to those numbers: 41 public class Wolf : Animal { … bool TryEatAnimal(Animal animal) bool TryEatAnimal(Animal animal) { if (animal.Size <= 4) if (animal.Size <= 4) { return true; return true; } }} This if statement is very wrong. 4 is the size of the Wolf, which has a Size property inherited from Animal. Why not use this.Size instead of 4 ?

 Call the base constructor to reuse the object's state initialization code: 42 public class Course { public string Name { get; set; } public string Name { get; set; } public Course(string name) public Course(string name) { this.Name = name; } { this.Name = name; }} public class LocalCourse { public string Lab { get; set; } public string Lab { get; set; } public Course(string name, string lab) public Course(string name, string lab) { this.Name = name; this.Name = name; this.Lab = lab; this.Lab = lab; }} : base (name) Call the base constructor instead!

 Never copy-paste the code of the base in the inherited class 43 public class Course { public string Name { get; set; } public string Name { get; set; } public ITeacher Teacher { get; set; } public ITeacher Teacher { get; set; }} public class LocalCourse { public string Name { get; set; } public string Name { get; set; } public ITeacher Teacher { get; set; } public ITeacher Teacher { get; set; } public string Lab { get; set; } public string Lab { get; set; }} Why are these fields duplicated and not inherited?

 Be careful to keep fields well encapsulated 44 public class Course { public string Name { get; private set; } public string Name { get; private set; } public ITeacher Teacher { get; private set; } public ITeacher Teacher { get; private set; } public Course(string name, ITeacher teacher) public Course(string name, ITeacher teacher) { if (name == null) if (name == null) throw ArgumentNullException("name"); throw ArgumentNullException("name"); if (teacher == null) if (teacher == null) throw ArgumentNullException("teacher"); throw ArgumentNullException("teacher"); this.Name = name; this.Name = name; this.Teacher = teacher; this.Teacher = teacher; } public Course() { } public Course() { }} Breaks encapsulation: Name & Teacher can be left null.

 Base class should never know about its children! 45 public class Course { public override string ToString() public override string ToString() { StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder(); … if (this is ILocalCourse) if (this is ILocalCourse) { result.Append("Lab = " + ((ILocalCourse)this).Lab); result.Append("Lab = " + ((ILocalCourse)this).Lab); } if (this is IOffsiteCourse) if (this is IOffsiteCourse) { result.Append("Town = " + ((IOffsiteCourse)this).Town); result.Append("Town = " + ((IOffsiteCourse)this).Town); } return result.ToString(); return result.ToString(); }}

 Don't define IEnumerable fields and use them as List (broken abstraction) 46 public class Container public class Container { public IEnumerable Items { get; } public IEnumerable Items { get; } public Container() public Container() { this.Items = new List (); this.Items = new List (); } public void AddItem (T item) public void AddItem (T item) { (this.Items as List ).Add(item); (this.Items as List ).Add(item); }} Bad practice: hidden List Bad practice: hidden List

 Use List in the field and return it where IEnumerable is required: 47 public class Container public class Container { private List items = new List (); private List items = new List (); public IEnumerable Items public IEnumerable Items { get { return this.items; } get { return this.items; } } public void AddItem (T item) public void AddItem (T item) { this.Items.Add(item); this.Items.Add(item); }} This partially breaks encapsulation. Think about cloning to keep your items safe.

48 public abstract class Course : ICourse { public string Name { get; set; } public string Name { get; set; } public ITeacher Teacher { get; set; } public ITeacher Teacher { get; set; }} public class LocalCourse : Course, ILocalCourse { public string Lab { get; set; } public string Lab { get; set; } public override string ToString() public override string ToString() { StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(); sb.Append(this.GetType().Name); sb.Append(this.GetType().Name); sb.AppendFormat("(Name={0}", this.Name); sb.AppendFormat("(Name={0}", this.Name); if (!(this.Teacher == null)) if (!(this.Teacher == null)) sb.AppendFormat("; Teacher={0}", this.Teacher.Name); sb.AppendFormat("; Teacher={0}", this.Teacher.Name); sb.AppendFormat("; Lab={0})", this.Lab); sb.AppendFormat("; Lab={0})", this.Lab); return sb.ToString(); return sb.ToString(); }} // continues at the next slide Repeating code

 When overriding methods, call the base method if you need its functionality, don't copy-paste it! 49 public class OffsiteCourse : Course, ILocalCourse { public string Town { get; set; } public string Town { get; set; } public override string ToString() public override string ToString() { StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(); sb.Append(this.GetType().Name); sb.Append(this.GetType().Name); sb.AppendFormat("(Name={0}", this.Name); sb.AppendFormat("(Name={0}", this.Name); if (!(this.Teacher == null)) if (!(this.Teacher == null)) sb.AppendFormat("; Teacher={0}", this.Teacher.Name); sb.AppendFormat("; Teacher={0}", this.Teacher.Name); sb.AppendFormat("; Town={0})", this.Town); sb.AppendFormat("; Town={0})", this.Town); return sb.ToString(); return sb.ToString(); }} Repeating code

50 public abstract class Course : ICourse { public string Name { get; set; } public string Name { get; set; } public ITeacher Teacher { get; set; } public ITeacher Teacher { get; set; } public override string ToString() public override string ToString() { StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(); sb.Append(this.GetType().Name); sb.Append(this.GetType().Name); sb.AppendFormat("(Name={0}", this.Name); sb.AppendFormat("(Name={0}", this.Name); if (!(this.Teacher == null)) if (!(this.Teacher == null)) sb.AppendFormat("; Teacher={0}", this.Teacher.Name); sb.AppendFormat("; Teacher={0}", this.Teacher.Name); return sb.ToString(); return sb.ToString(); }} // continues at the next slide

51 public class LocalCourse : Course, ILocalCourse { public string Lab { get; set; } public string Lab { get; set; } public override string ToString() public override string ToString() { return base.ToString() + "; Lab=" + this.Lab + ")"; return base.ToString() + "; Lab=" + this.Lab + ")"; }} public class OffsiteCourse : Course, ILocalCourse { public string Town { get; set; } public string Town { get; set; } public override string ToString() public override string ToString() { return base.ToString() + "; Town=" + this.Town + ")"; return base.ToString() + "; Town=" + this.Town + ")"; }}

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

 Use the provided source code "High-Quality- Classes-Homework.zip". High-Quality- Classes-Homework.zipHigh-Quality- Classes-Homework.zip 1.Take the VS solution " Abstraction " and refactor its code to provide good abstraction. Move the properties and methods from the class Figure to their correct place. Move the common methods to the base class's interface. Remove all duplicated code (properties / methods / other code). 2.Establish good encapsulation in the classes from the VS solution " Abstraction ". Ensure that incorrect values cannot be assigned in the internal state of the classes. 53

3.Take the VS solution " Cohesion-and-Coupling " and refactor its code to follow the principles of good abstraction, loose coupling and strong cohesion. Split the class Utils to other classes that have strong cohesion and are loosely coupled internally. 4.Redesign the classes and refactor the code from the solution " Inheritance-and-Polymorphism " to follow the best practices in high-quality classes. Extract abstract base class and move all common properties in it. Encapsulate the fields and make sure required fields are not left without a value. Reuse the repeating code though base methods. 54

 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