Intro to object oriented programming


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Photo by meganpru(Creative Commons License)
  • Complexity of the problem domainThe problems we try to solve in software often involve elements of inescapable complexity, in which we find a myriad of competing, perhaps even contradictory, requirementsDifficulty to manage the development processThe fundamental task of the software development team is to engineer the illusion of simplicity – to shield users from this vast and often arbitrary external complexityFlexibility possible through softwareSoftware offers the ultimate flexibility, so it is possible for a developer to express almost any kinf of abstractionCharacterizing the behavior of discrete systemsA lot of software is designed to model discrete systems. Discrete systems are not easily modeled in procedural code.
  • Photo by All Glass Photo's photostream(Creative Commons License)
  • Sample Dialog:In C# like any other object oriented language, the members in a type are basically either fields or methods. However, C# has a rich selection of field and method options.Fields are the data or state of an object or type, and methods are the functionality.Members come in two basic forms, instance and static. Instance members are the most common, and there will be one per instance or object. Static members are shared amongst instances and are one per type.Instance methods require an instance to be called, but static methods can be called directly just using the name of the type. The automatic “this” parameter is passed to instance methods, but not static methods.In .NET or managed code it is a common design pattern to create a class that cannot be instantiated, with nothing but static methods. This is a way of creating methods that are sort-of global, but are still logically grouped with other related methods. The System.Console class is an example of this design pattern.Speaker Instructions:You don’t have to say the stuff in that last paragraph, but concrete examples like these do help to nail down the ideas for the listeners.
  • As an object oriented programmer you will first and foremost create instances of types. This means that you will use a definition for a type, which has a name such as String or ArrayList, to create an actual object in memory. This object is structured based on the details described in the type’s definition.After you have created an object, you can use it by calling methods and/or referencing fields on the object. When you are finished with the object it must be cleaned up. Is some environments you do this explicitly; in others, such as C# or Java, cleanup is done for you by the system.Creating instances is a nice introduction to OO programming, but eventually you will have to define your own type. By doing so you create a new classification for a kind of object that can be created. You give the type a name, and you create members of the type such as methods and fields.It is important to distinguish between types and instances, so I will make an analogy. Think of the type as a descriptive tool (like a cookie cutter), while an instance is an object created from that description (in the same way that a cookie is created from a cookie cutter).
  • Static typesare most often used when you need to call a method repeatedly.It doesn’t make sense to waste the overhead of instantiating an object just to call a method.When using a static type, only one instance of the class is created.
  • Sample Dialog:C# supports constructor syntax much like C++. However, unlike C++ it is invalid to call a constructor method directly, so if you wish to implement a constructor in terms of another constructor you must use the special colon-this notation you see here.In this example, the simpler Point() constructor automatically calls the more complex constructor with the default x and y values of 0.You can indicate which base constructor to callUse the base keywordYou can implement simpler constructors in terms of more complex ones with the this keyword (suggested)Speaker Instructions:FYI, it is recommended that you have only one constructor for a type, and that the rest of the constructors be implemented in terms of this one. However, this is not always possible and must be handled on a type-by-type bases.
  • An object is a reference type.This means that variables that refer to an object are simply pointing to that object. Multiple variables can be pointing to the same object, which can cause confusion. Accessing any of these variables will access or modify the object.From the computer’s point of view, objects are data. They are the culmination of their fields and enough information to indicate their type. Often this data is complex and sizeable, and it is stored in the memory heap of the program that created the instance.Because objects so often live in the heap-memory of a program, the most common way of dealing with an instance is through a reference variable. The reference variable can be a global or local variable, or it can be a field in another object. Either way, there are some rules of reference variables.Reference variables have a type associated with them. For every object-type defined in an object oriented system, there is a matching reference variable type that is used to refer to instances of the type.Reference variables can refer to an instance or object, or they can refer to null (in most OO languages anyway). A null reference simply indicates that this variable does not refer to any object, but could have an object reference assigned to it.Reference variables do not always refer to objects of the exact sametype as the reference variable. This can be confusing, but in fact the rules are simple. A reference variable must refer to an object of matching type or it must refer to an object that is ultimately derived from the matching type.Looking back to the relationship between Automobile and Machine, a reference variable of type Automobile can only refer to an instance of Automobile; however a reference variable of type Machine can refer to an instance of Machine or an instance of Automobile. You can look at this as being possible, because Automobile is a Machine through the affect of derivation.Reference variables are your means of access to an object or instance. There are two related rules of reference variables.Regardless of what type of instance your reference variable refers to, it is the type of the variable that constrains how you can touch or affect the instance. Regardless of what type of reference variable you are using to refer to an object, the type of the object never changes for the life of the object.
  • Sample Dialog:C# has built in support for event notification and handling, which is great for dealing with OSs that are becoming increasingly event driven.Events in C# are very flexible compared to the virtual-function method of responding to system events.Speaker Instructions:We have several slides on this, so you don’t have to say everything on this slide.
  • Sample Dialog:The source code on this slide shows a simple class derived from Form. The interesting part, however, is how the class registers its interest in the Click event defined by an instance of the Button class. The MyForm class indicates which of its methods (in this case the HandleClick method) should be called when the event is fired.
  • Sample Dialog:Like C++ and Java, C# supports member and class accessibility. The default accessibility is private, and you must decorate members with an accessibility modifier to set a different accessibility.The most common accessibilities are public, private, and protected. However, C# introduces the idea of an internal accessibility which allows access by any class in the same binary assembly file. This is similar to, but more flexible than the C++ friend class.Speaker Instructions:You could spend forever talking about accessibility. If you like you can edge into the direction of design by saying that fields should be private, and methods can be public, etc. But be careful, because you could sink ten minutes on this slide alone.
  • Encapsulation and Abstraction are related concepts
  • Encapsulation is the hiding of the internal mechanisms and data structures of a software component behind a defined interface.We don’t need to understand the details of how the component works internally in order to use that component.Increases integrity by preventing external users from setting internal state of a component to an invalid state.
  • Abstraction is simplifying complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.
  • The object structure is important because it illustrates how different objects collaborate with one another through patterns of interaction.
  • A type defines a number of fields and methods. A derived type inherits the base type’s fields and methods, and adds more of its own, to become a new type (extending from the exisiting one).
  • Polymorphism is closely related to type-derivation and reference variables. But it is an advanced topic, and can be difficult to describe. The goal is to allow a generic piece of code to work with objects or instances generically; meanwhile we want the objects themselves to do the right thing based on their respective types.
  • Sample Dialog:To create a virtual function in C# you must attribute your method with the virtual keyword. Virtual methods can be public, protected, or protected internal.To override a virtual method in a derived class you must explicitly indicate your intent using the override keyword. Your derived method must also match the base method signature exactly.Speaker Instructions:The override keyword is actually part of the versioning story in the .NET Framework. But this is probably a bit too much to explain in the discussion. However, for your own study you may want to look up the “override” and “new” keywords in the documentation, as this is an example of a feature that is much more well thought out than the equivalent feature in Java.Another Example:using System; class App{ public static void Main(String[] args){ Object[] objects = new Object[]{ new Lemon(), new Grapefruit(), new Truck(), new Lemon(), new Lime() };foreach(Object o in objects){Console.WriteLine(o.ToString()); } }} class Citrus{ public override String ToString(){ return "I am a "+this.GetType().ToString(); }} class Lime:Citrus{} class Lemon:Citrus{} class Grapefruit:Citrus{} class Truck{ public override String ToString(){ return "Truck here"; }}
  • Sample Dialog:Interfaces are an excellent way for a type to take on a role without being derived from a type that defines this role. For example, two totally unrelated types can be sortable and therefore take on the well-defined ability to be sorted, even though they are not derived in the same derivation hierarchy. This is possible through interfaces.In C# you cannot have multiple base classes, but a type can implement any number of interfaces.You will find that you implement pre-existing interfaces often, but from time to time you will have to define your own interface. Interfaces can include only methods, properties, and events. It is not valid for an interface to include a field. Interfaces are defined using the interface keyword as shown here.
  • Interfaces are a great feature of object oriented programming. Some languages such as C++ support a concept called multiple derivation. The .NET Framework does not allow for multiple inheritance, and as a result neither does C#. Sometimes, it is nice, however, for a type to be able to take on several roles. This is where Interfaces come in.
  • When Designing a complex software project, it is essential to decompose it into smaller and smaller parts, each of which we may then refine independently.
  • Poster by Derrick Bailey
  • Poster by Derrick Bailey
  • Poster by Derrick Bailey
  • Code sample from Chander Dahl’s presentation, based on writings of Robert Martin
  • Poster by Derrick Bailey
  • Poster by Derrick Bailey
  • Intro to object oriented programming

    1. 1. Principles of Object Oriented Programming<br />David GiardMCTS, MCSE, MCDBA, MCSD<br /> <br />
    2. 2.<br /> is a site dedicated to helping Architects, aspiring Architects and Lead Developers learn, connect and contribute.<br /><br />
    3. 3. Agenda<br />The Challenge<br />The Basics<br />Bringing Order To Chaos<br />Guiding Principles<br />
    4. 4. The Challenge<br />
    5. 5. The Complexity of software derives from 4 elements:<br />Complexity of the problem domain<br />Difficulty to manage the development process<br />Flexibility possible through software<br />Software problems often model discrete systems<br />
    6. 6. ?<br />How do you write great software every time?<br />
    7. 7. Good question… lots of answers!<br />The customer–friendly programmer says:<br />“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.”<br />
    8. 8. Good question… lots of answers!<br />The design–guru programmer says:<br />“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.”<br />
    9. 9. Good question… lots of answers!<br />The object-oriented programmer says:<br />“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.”<br />
    10. 10. Answer: Simplify Complexity<br />Answer: Eschew Obfuscation<br />
    11. 11. The Basics<br />
    12. 12. The Basics<br />Objects<br />Classes<br />Members<br />Properties<br />Methods<br />Events<br />Constructors<br />Instances<br />Message Passing<br />
    13. 13. Defining Classes<br />class Name:BaseType{<br /> // Members<br />}<br />class MyType{<br /> public String SomeString;<br /> public Int32 x;<br /> public Int32 y; public void DoSomething() { … }<br />}<br />
    14. 14. Class Members<br />Fields<br />The state of an object<br />Properties<br />Also maintain state<br />Methods<br />Constructors<br />Functions<br />Properties (smart fields)<br />Members come in two basic forms<br />Instance<br />Static<br />
    15. 15. Fields<br />Maintain state of an object<br />Accessing a field<br />class Point{<br />public Int32 X;<br /> public Int32 Y;<br /> private In32 _x;<br />} <br />Point p = new Point();<br />p.X = 100;<br />p.Y = 200;<br />Console.WriteLine(p.X);<br />
    16. 16. Properties<br />Methods that look like fields (smart fields)<br />Can have read-only or write-only properties<br />class Point{<br /> Int32 _x;<br /> Int32 _y;<br />public Int32 X {<br /> get{return _x;}<br /> set{_x = value;}<br />}<br /> public Int32 Y {<br /> get{return _y;}<br /> set{_y = value;}<br />}<br />} <br />
    17. 17. Methods<br />class MyType{<br /> public Int32 SomeMethod() {<br /> Int32 z = 0;<br /> // Code omitted…<br />return z;<br /> }<br /> public static void StaticMethod() {<br /> // Do something<br /> }<br />}<br />MyType t = new MyType();<br />t.SomeMethod();<br />
    18. 18. Method Parameters<br />class MyType{<br /> public Int32 AddNumbers(Int32 x, Int32 y) {<br /> Int32 z = x + y;<br />return z;<br /> }<br />}<br />MyType t = new MyType();<br />t.AddNumbers(1,2);<br />
    19. 19. Types and Instances<br />
    20. 20. Instantiating an Object<br />public class MyType<br />{<br /> public string MyStringField;<br />public void InstanceMethod() {<br /> // Do something<br /> }<br />}<br />MyType o = new MyType();<br />o.MyStringField = “Hello”;<br />String x = o.MyStringField;<br />o.InstanceMethod();<br />
    21. 21. Static Types<br />public static class MyType{<br /> public static void StaticMethod()<br />{<br /> // Do something<br /> }<br />}<br />MyType.StaticMethod();<br />
    22. 22. Constructors<br />Constructors are used to initialize fields<br />class Point<br />{<br />private Int32 _x;<br />private Int32 _y;<br /> public Point() { // Setup code }<br /> public Point(Int32 xCoordinate, Int32 yCoordinate) {<br /> _x = xCoordinate;<br />_y = yCoordinate;<br /> }<br />}<br />
    23. 23. Referencing an object<br />Objects are reference types<br />Pointer to memory<br />MyType obj1 = new MyType();<br />obj2 = obj1;<br />obj2.Color = “Red”;<br />Console.WriteLine(obj1.Color)<br />
    24. 24. Event Handling<br />C# and VB have built in support for events<br />Great for dealing with objects in an event-driven operating system<br />More than one type can register interest in a single event<br />A single type can register interest in any number of events<br />
    25. 25. Event Handling<br />class MyForm:Form{<br />MyForm(){<br /> Button button = new Button();<br />button.Text = "Button";<br />button.Click += new EventHandler(HandleClick);<br />Controls.Add(button);<br /> }<br /> void HandleClick(Object sender, EventArgs e){<br />MessageBox.Show("The Click event fired!");<br /> }<br /> public static void Main(){<br />Application.Run(new MyForm());<br /> } <br />} <br />
    26. 26. Designing Types: Accessibilities<br />public – Accessible to all<br />private – Accessible to containing class<br />protected – Accessible to containing or derived classes<br />internal – Accessible to code in same assembly<br />
    27. 27. Demo<br />
    28. 28. Bringing Order to the ChaosObject Oriented Programming<br />
    29. 29. Bringing Order to the ChaosConcepts of Object Orientation<br />Encapsulation<br />Abstraction<br />Inheritance<br />Polymorphism<br />Decoupling<br />
    30. 30. Bringing Order to the Chaos<br />Encapsulation<br />and<br />Abstraction<br />
    31. 31. Bringing Order to the ChaosThe Role of Encapsulation<br />Car<br />Transmission<br />Engine<br />Stop()<br />Start()<br />Axel<br />Axel<br />Drive()<br />Wheel<br />Wheel<br />Wheel<br />Wheel<br />
    32. 32. Bringing Order to the ChaosThe Role of Abstraction<br />
    33. 33. Demo<br />
    34. 34. Bringing Order to the ChaosThe Role of Inheritance<br />
    35. 35. Inheritance<br />Vehicle<br />Plane<br />+Start()<br />+Stop()<br />+Steer()<br />+Fly()<br />+Start()<br />+Stop()<br />+Steer()<br />Train<br />+Start()<br />+Stop()<br />+Steer()<br />+BlowHorn()<br />Automobile<br />+Start()<br />+Stop()<br />+Steer()<br />+Honk()<br />
    36. 36. Polymorphism<br />
    37. 37. Designing Types: Polymorphism<br />Use the virtual keyword to make a method virtual<br />In derived class, override method is marked with the override keyword<br />Example<br />ToString() method in Object class<br />Example derived class overriding ToString()<br />public virtual string ToString(); <br />class SomeClass:Object{<br /> public override String ToString(){<br /> return “Some String Representing State”;<br /> }<br />}<br />
    38. 38. Demo<br />
    39. 39. Interfaces<br />Define public members<br />No Implementation<br />Your types can implement interfaces<br />Must implement all methods in the interface<br />interface IName{<br /> // Members<br />}<br />Class ClassName: IName{<br />}<br />
    40. 40. Interfaces<br />using System;<br /> <br />class SomeType{};<br /> <br />class SortType:SomeType, IComparable{<br /> Int32 val;<br /> public SortType(Int32 val){<br /> this.val = val;<br /> }<br /> public Int32 CompareTo(Object obj){<br /> return this.val - ((SortType)obj).val;<br /> }<br /> <br /> public override string ToString(){<br /> return val.ToString();<br /> }<br />}<br /> <br />class App{<br /> public static void Main(){<br />SomeType[] objs = new SomeType[]{<br /> new SortType(3), new SortType(1), new SortType(2)};<br /> <br />Array.Sort(objs);<br />foreach(SomeType o in objs){<br />Console.WriteLine(o.ToString());<br /> } <br /> }<br />}<br />
    41. 41. Bringing Order to the ChaosThe Role of Decoupling<br />
    42. 42. Demo<br />
    43. 43. Airplane<br /> speed: int<br />getSpeed(): int<br />setSpeed(int)<br />UML and Class Diagrams<br />Class Diagram<br />Name<br />Member Variables<br /> name:type<br />Methods<br /> name(parameters the method uses): return type<br />
    44. 44. Visual Studio Class Designer<br />
    45. 45. Demo<br />
    46. 46. Guiding Principles<br />
    47. 47. SOLIDPrinciples<br />Single responsibility<br />Open Close<br />Liskov Substitution.<br />Interface Segregation <br />Dependency Injection<br />
    48. 48.
    49. 49.
    50. 50.
    51. 51. Liskovsubstitution<br />public class Rectangle{  public virtual int Height { get; set; }  public virtual int Width { get; set; }  public int Area()  {    return Height * Width;  }}<br />
    52. 52. Liskovsubstitution<br />rectangle.Height = 4;rectangle.Width = 5;int expectedArea = 20;int actualArea = rectangle.Area();Debug.Assert(expectedArea == actualArea);<br />
    53. 53. Liskovsubstitution<br />public 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;    }  }}<br />
    54. 54. Liskovsubstitution<br />Rectangle square = new Square();square.Width = 4;square.Height = 5;int expectedArea = 20;int actualArea = rectangle.Area();Debug.Assert(expectedArea == actualArea);<br />
    55. 55.
    56. 56. Interfacesegregationprinciple<br />interface IWorker { public void work(); public void eat();}<br />
    57. 57.
    58. 58. Interfacesegregationprinciple<br />public class Customer <br />{<br /> private IFoo _foo;<br /> public Customer(IFoo foo) <br /> {<br />this._foo= foo; <br /> }<br />}<br />
    59. 59. David Giard<br /><br /><br /><br /><br />Special thanks to Chris Woodruff<br />