Вы находитесь на странице: 1из 42

Prevent Oops With Efficient OOP Design in .

NET

Introduction

About Miguel

Personal Programming Project Management .NET Experience

About TekFokus, Inc.


Microsoft Certified Partner Microsoft Certified Technical Education Center (CTEC)

Back to Basics = Success

Sports

Super Bowl
Instead of selling product, addressing business issues Setting and Achieving Goals

Sales

Personal Success

Basics of Modern Software Design

Object Oriented Analysis and Design (OOAD) Proper application of OOP Principles
Abstraction Encapsulation Inheritance Polymorphism

Why Object Oriented Programming?

Code Reuse
Rapid Application Development Lower Cost of Development Shorter Application Development Cycle

Caveats
Design Phase More Critical Initially, Longer Design Phase

What is a class?

For the philosopher


An artifact of human classification! Classify based on common behavior or attributes Agree on descriptions and names of useful classes Create vocabulary; we communicate; we think!
A named syntactic construct that describes common behavior and information A data structure (type) that includes both data (fields) and behavior (methods)

For the object-oriented programmer


What is an object?

An object is an instance of a class Objects exhibit:

Identity: Objects are distinguishable from one another (Different reference means different object) Behavior: Objects can perform tasks (C#: methods, VB.NET: Subs, Functions) State: Objects store information (fields)

Value vs. Reference Type

A struct is a blueprint for a value

No identity, accessible state, no added behavior (behavior is allowed, just not extensible)

A class is a blueprint for an object

Identity, inaccessible state, added behavior

Comparing Value and Reference Types

Value types:

Reference types:

Directly contain their data Each has its own copy of data Operations on one cannot affect another

Store references to their data (known as objects) Two reference variables can reference same object Operations on one can affect another

int i, j; i=5; j=i; MyClass myObject1, myObject2; myObject1 = new MyClass(); myObject2 = myObject1;

Dim i, j As Integer i = 5 j = i Dim myObject1, _ myObject2 As MyClass myObject1 = NewMyClass() myObject2 = myObject1

Common Type System (CTS) Architecture

User-Defined Reference Types


Type
Interface Abstract Class Concrete Class Implemented Instantiable (Coded) NO NO NO Maybe

YES

YES

Stack vs. Managed Heap

All variables (value or reference) and their respective values are stored on the stack All classes and objects (instances of classes) are stored on managed heap Classes are loaded into the managed heap using the Class Loader of the Common Language Runtime (CLR)

Abstraction

Abstraction is selective ignorance


Decide what is important and what is not Focus and depend on what is important Ignore and do not depend on what is unimportant Implement classes (types) to support abstraction

The purpose of abstraction is not to be vague, but to create a new semantic level in which one can be absolutely precise. Edsger Dijkstra

Encapsulation

Encapsulation Is the Process of Hiding Internal Details of a Class Encapsulation Keywords

Logical Encapsulation

private protected public internal (Friend)

Physical Encapsulation

Combination

protected internal (Protected Friend)

Type-Level Accessibility Nesting of classes

Why Encapsulate?

Allows control

Withdraw( ) Deposit( )

Use of the object is solely through the public methods Use of the object is unaffected if the private data type changes

balance 12.56

Allows change

Withdraw( ) Deposit( ) dollars 12 cents 56

Using Access Modifiers


Keyword private protected public Definition
Accessible only within the type itself. Only for use on class members. Accessible within the class itself and any derived classes. Accessible everywhere. Accessible within the type itself and all namespaces and code within the same assembly. The union of protected and internal (Friend).

internal (Friend)
protected internal (Protected Friend)

Object (Instance) Data

Object data describes information for individual objects

For example, each bank account has its own balance. If two accounts have the same balance, it is only a coincidence.
Withdraw( ) Deposit( ) balance owner 12.56 "Fred"

Withdraw( ) Deposit( ) balance 12.56 owner "Bert"

Static (Shared) Data

Static data describes information for all objects of a class

For example, suppose all accounts share the same interest rate. Storing the interest rate in every account would be a bad idea. Why?
Withdraw( ) Deposit( )

Withdraw( ) Deposit( ) balance 12.56 interest 7%

balance

99.12

interest 7%

Static (Shared) Members

Static methods can only access static data

A static method is called on the class, not the object (i.e. Class.Method( ) )
An account object

The account class

InterestRate( )

interest 7%
Classes contain static data and

Withdraw( ) Deposit( ) balance owner 99.12 "Fred"

Objects contain object data and

Inheritance

Inheritance specifies an is a kind of" relationship


Inheritance is a class relationship New classes specialize existing classes

Generalization

Musician

Base class

Specialization

Violin Player

Derived class

Is this a good example of inheritance ?

Single and Multiple Inheritance


Single inheritance: deriving from one base class Multiple inheritance: deriving from two or more base classes
Stringed Instrument Musical Instrument Pluckable

Violin Violin has a single direct base class

Stringed Instrument Stringed Instrument has two direct base classes

Inheritance (cont.)

Inheritance Is the Reuse of Class Members in Other Classes The Common Type System (CTS) Only Supports Single Inheritance for Classes Member Hiding

Redefine the same method in the derived class Use the new (Shadows) keyword

Abstract Members Sealed Classes

Class Hierarchies

Classes related by inheritance form class hierarchies


Musician
plays Musical Instrument

String Musician

plays

Stringed Instrument

???

Violin Player

plays

Violin

???

Polymorphism

The method name resides in the base class The method implementations reside in the derived classes Polymorphism Allows a Reference Variable to Call the Correct Method Virtual Methods Enable Polymorphism in the Common Type System
String Musician TuneYourInstrument( ) A method with no implementation is called an operation

Guitar Player TuneYourInstrument( )

Violin Player TuneYourInstrument( )

Abstract Base Classes

Some classes exist solely to be derived from


It makes no sense to create instances of these classes These classes are abstract

Stringed Musician { abstract } You cannot create instances of abstract classes

Guitar Player concrete

Violin Player concrete

You can create instances of concrete classes

Interfaces

Interfaces contain only operations (noncoded methods), not implementation Interfaces are a way of sharing behavior between different classes
Musician interface Nothing but operations. You cannot create instances of an interface.

String Musician { abstract }

May contain some implementation. You cannot create instances of an abstract class.

Violin Player concrete

Must implement all inherited operations. You can create instances of a concrete class.

Early and Late Binding


Normal method calls are resolved at compile time Polymorphic method calls are resolved at run time
Musician interface TuneYourInstrument( )

Late binding

runtime
Violin Player concrete

TuneYourInstrument( )

Early binding

Binding Example
IFly TakeOff( ) Land( )

Plane: IFly TakeOff( ) { } Land( ) { }

Bird: IFly
TakeOff( ) { } Land( ) { }

Plane p = new Plane(); Bird b = new Bird(); IFly flier = (IFly) p; flier.TakeOff(); flier.Land();

Methods with Interface Reference Variables


public class MyClass { public static void Method(IFly f) { f.TakeOff( ); f.Land( ); } } // Client code public static void Main( ){ Plane p = new Plane( ); MyClass.Method(p); }

Designing Classes Using Use Case Diagrams

Use cases

Provide a functional description of major processes Use a non-technical language to describe the process Show a boundary around the problem to be solved
Graphically describe who or what will use the processes Is not limited to persons

Actors

Use Case Diagram


Sales System
Retrieve Customer Orders

Internet Client

Add Customer

Database

Telesales Agent

Remove Customer

Use Case Description


A user requests the orders for a customer by using a particular customer ID. The ID is validated by the database, and an error message is displayed if the customer does not exist. If the ID matches a customer, the customers name, address, and date of birth are retrieved, in addition to any outstanding orders for the customer. Details about each order are retrieved, including the ID, the date, and the individual order items that make up an order.

Converting Use Cases into Classes

Use case descriptions provide the basis for initial class design

Nouns = classes or attributes

A user requests the orders for a customer by using a particular customer ID. The ID is validated by the database, and an error message is displayed if the customer does not exist. If the ID matches a customer, the customers name, address, and date of birth are retrieved, in addition to any outstanding orders for the customer. Details about each order are retrieved, including the ID, the date, and the individual order items that make up an order.

Verbs = operations (methods)

Example: ValidateCustomer, RetrieveOrders, RetrieveOrderItems

Extending Use Cases

uses - reuses an existing use case


Add Customer <<uses>> Check Customer Exists

Extends - enhances an existing use case


Remove Inactive Customers

<<extends>>

Remove Customer

Advanced Object-Oriented Programming Concepts

Association Aggregation

Association

A class depends on another class to perform some functionality Roles are the direction of the association Multiplicity determines how many objects can participate in a relationship
Multiplicity

Customer

0..*

Order

Association

Aggregation

A complex class containing other classes A part-of relationship Example:


An Order class contains an OrderItem class An OrderItem class is a part of an Order class *
Aggregation

Order

OrderItem

Class Diagrams

Customer * Order

1..*

Order Item *

Product

Class Diagram with Attributes and Operations


Class is a defined set of data and behavior Attributes are the data contained in a class Operations are the actions performed on that data Accessibility: Public (+), Private (-), Protected (#)

Customer
-CustomerID: Long +Name: String +DOB: Date +AddCustomer( ) +GetDetails(ID: Integer) -CheckValid( ): Boolean
Attributes (Fields)

Save Operation No parameters

Load Operation Integer parameter CheckValid Operation Boolean return value

Real World OOAD


Design phase of development process is more critical Good OOAD in the design phase can consume up to 60% of development process Initial move to OOAD increases immediate cost ROI is seen in later application or component development

Observations

New programmers and current VB 6.0 developers find it more difficult to shift to OOAD OOAD and OOP should have more emphasis in .NET development

Additional Resources

OOP with Microsoft Visual Basic .NET and Microsoft Visual C# .NET Step by Step, Robin A. Reynolds-Haertle, Microsoft Press, 2002, ISBN: 0735615683 Object Oriented Software Construction, 2nd Edition, Bertrand Meyer, Prentice Hall, 1997, ISBN: 0136291554 Professional UML with Visual Studio .NET, John Slater, et al, Wrox Press, 2002, ISBN: 1861007957 Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design, and the Unified Process, Craig Larman, Prentice Hall, 2001, ISBN: 0130925691

Вам также может понравиться