Intro to object oriented programming
-
Upload
david-giard -
Category
Technology
-
view
702 -
download
3
Transcript of Intro to object oriented programming
Principles of Object Oriented ProgrammingDavid GiardMCTS, MCSE, MCDBA, MCSD
DavidGiard.com
nPlus1.org
nPlus1.org is a site dedicated to helping Architects, aspiring Architects and Lead Developers learn, connect and contribute.
http://nplus1.org
Agenda
The ChallengeThe BasicsBringing Order To ChaosGuiding Principles
The Challenge
The Complexity of software derives from 4 elements:
Complexity of the problem domainDifficulty to manage the development processFlexibility possible through softwareSoftware problems often model discrete systems
How do you write great software every time??
Good question… lots of answers!
The customer–friendly programmer says:
“Great software always does what the customer wants it to. So even if the customer thinks of new ways to use the software, it doesn’t break or give them unexpected results.”
Good question… lots of answers!
The design–guru programmer says:
“Great software is when you use tried-and-true design patterns and principles. You’ve kept your objects loosely coupled, and your code opens for extension but closed for modification. That also helps keep the code more usable, so you don’t have to rework everything to use parts of your application over and over again.”
Good question… lots of answers!
The object-oriented programmer says:
“Great software is code that is object-oriented. So there's not a bunch of duplicate code, and each object pretty much controls its own behavior. It’s also easy to extend because your design is really solid and flexible.”
Make sure your software does what the customer wants
it to do.
Apply basic OO principles to add
flexibility
Strive for a maintainable,
reusable design
Answer: Simplify ComplexityAnswer: Eschew Obfuscation
The Basics
The BasicsObjectsClasses
MembersPropertiesMethodsEventsConstructors
InstancesMessage Passing
Defining Classesclass Name:BaseType{ // Members}
class MyType{ public String SomeString; public Int32 x; public Int32 y; public void DoSomething()
{…}
}
Class MembersFields
The state of an objectProperties
Also maintain stateMethods
ConstructorsFunctionsProperties (smart fields)
Members come in two basic formsInstanceStatic
FieldsMaintain state of an object
Accessing a field
class Point{ public Int32 X; public Int32 Y; private In32 _x;}
Point p = new Point();p.X = 100;p.Y = 200;Console.WriteLine(p.X);
PropertiesMethods that look like fields (smart fields)
Can have read-only or write-only properties
class Point{ Int32 _x; Int32 _y; public Int32 X { get{return _x;} set{_x = value;} } public Int32 Y { get{return _y;} set{_y = value;} }}
Methodsclass MyType{ public Int32 SomeMethod() { Int32 z = 0; // Code omitted… return z; }
public static void StaticMethod() { // Do something }}
MyType t = new MyType();t.SomeMethod();
Method Parametersclass MyType{ public Int32 AddNumbers(Int32 x, Int32 y) { Int32 z = x + y; return z; }
}
MyType t = new MyType();t.AddNumbers(1,2);
Types and Instances
Instantiating an Objectpublic class MyType{ public string MyStringField; public void InstanceMethod() { // Do something }}
MyType o = new MyType();o.MyStringField = “Hello”;String x = o.MyStringField;o.InstanceMethod();
Static Typespublic static class MyType{
public static void StaticMethod(){
// Do something}
}
MyType.StaticMethod();
ConstructorsConstructors are used to initialize fields
class Point{ private Int32 _x; private Int32 _y;
public Point() {
// Setup code }
public Point(Int32 xCoordinate, Int32 yCoordinate) { _x = xCoordinate; _y = yCoordinate; }}
Referencing an object
MyType obj1 = new MyType();obj2 = obj1;obj2.Color = “Red”;Console.WriteLine(obj1.Color)
Objects are reference typesPointer to memory
Event Handling
C# and VB have built in support for eventsGreat for dealing with objects in an event-driven operating systemMore than one type can register interest in a single eventA single type can register interest in any number of events
Event Handlingclass MyForm:Form{ MyForm(){ Button button = new Button(); button.Text = "Button"; button.Click += new EventHandler(HandleClick); Controls.Add(button); } void HandleClick(Object sender, EventArgs e){ MessageBox.Show("The Click event fired!"); } public static void Main(){ Application.Run(new MyForm()); } }
Designing Types: Accessibilities
public – Accessible to allprivate – Accessible to containing classprotected – Accessible to containing or derived classesinternal – Accessible to code in same assembly
Demo
Bringing Order to the ChaosObject Oriented Programming
Bringing Order to the Chaos Concepts of Object Orientation
EncapsulationAbstractionInheritancePolymorphismDecoupling
Bringing Order to the Chaos
EncapsulationandAbstraction
Bringing Order to the ChaosThe Role of Encapsulation
Car
EngineTransmission
Axel
Wheel
Wheel
Wheel
Wheel
Axel
Stop()
Drive()
Start()
Bringing Order to the ChaosThe Role of Abstraction
Layer 1
Module
Module
Layer 2
Module
Module
Layer 3Module Module
Demo
Bringing Order to the ChaosThe Role of Inheritance
Vehicle
Automobile
Car Truck
Plane
Jet Bi-Plane
InheritanceVehicle+Start()+Stop()+Steer()
Plane
Train
Automobile
+Start()+Stop()+Steer()+Fly()
+Start()+Stop()+Steer()+BlowHorn()
+Start()+Stop()+Steer()+Honk()
PolymorphismSportPlayerPlay()
BaseballPlayerPlay()Catch()
Catcherplay()Catch()
Outfielderplay()Catch()
FootballPlayerPlay()
ReceiverPlay()
Designing Types: PolymorphismUse the virtual keyword to make a method virtualIn derived class, override method is marked with the override keywordExample
ToString() method in Object class
Example derived class overriding ToString()
public virtual string ToString();
class SomeClass:Object{ public override String ToString(){ return “Some String Representing State”; }}
Demo
InterfacesDefine public membersNo ImplementationYour types can implement interfacesMust implement all methods in the interface
interface IName{ // Members}
Class ClassName : IName{}
Bringing Order to the ChaosThe Role of Decoupling
Demo
UML and Class Diagrams
Airplane
speed: int
getSpeed(): int
setSpeed(int)
Class Diagram
Member Variables
name:type
Name
Methods
name(parameters the method uses): return type
Visual Studio Class Designer
Demo
Guiding Principles
SOLID Principles
Single responsibilityOpen CloseLiskov Substitution.Interface Segregation Dependency Injection
Liskov substitution
public class Rectangle{ public virtual int Height { get; set; } public virtual int Width { get; set; }
public int Area() { return Height * Width; }}
Liskov substitution
rectangle.Height = 4;rectangle.Width = 5;int expectedArea = 20;int actualArea = rectangle.Area();Debug.Assert(expectedArea == actualArea);
Liskov substitutionpublic class Square : Rectangle { public override int Height { get { return base.Height; } set { base.Height = value; base.Width = value; } } public override int Width { get { return base.Width; } set { base.Width = value; base.Height = value; } }}
Liskov substitution
Rectangle square = new Square();square.Width = 4;square.Height = 5;int expectedArea = 20;int actualArea = rectangle.Area();Debug.Assert(expectedArea == actualArea);
Interface segregation principle
interface IWorker {public void work();public void eat();
}
Interface segregation principle
public class Customer { private IFoo _foo; public Customer(IFoo foo) { this._foo = foo; }}
David GiardDavidGiard.comTechnologyAndFriends.comDavidGiard@DavidGiard.comTwitter.com/DavidGiard
Special thanks to Chris Woodruff