(4) c sharp introduction_object_orientation_part_i

download (4) c sharp introduction_object_orientation_part_i

If you can't read please download the document

description

This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/4-c-sharp-introductionobjectorientationparti-38639639 Check out these exercises: http://de.slideshare.net/nicolayludwig/4-c-sharp-introductionobjectorientationpartiexercises - Simulation of Reality - "is-a" and "has-a" Relationship - Classes - Specialization and Generalization - Fields - Methods - Constructors - Unified Modeling Language (UML)

Transcript of (4) c sharp introduction_object_orientation_part_i

  • 1. (4) Introduction of C# object-oriented Programming Part INico Ludwig (@ersatzteilchen)

2. 2TOC (4) Introduction of C# object-oriented Programming Part I Simulation of Reality "is-a" and "has-a" Relationship Classes Specialization and Generalization Fields Methods Constructors Unified Modeling Language (UML) 3. 3Programming a Simulation of the real World Programs simulate a real world situation to solve a problem. It is complicated to solve a problem in an imperative programing language. Classic languages are good to express mathematical problems. The syntaxes are rather complicated and specialized. These languages work on a rather low level. Examples: Classic Fortran, Assembler and early Basic dialects. Procedural languages introduced features that added expressibility. There we have functions and procedures as first class citizens. Also structures, records and variant records are first class citizens. These languages act as multipurpose programming languages. Examples: Pascal, C and Algol. 4. 4Real World Simulation the procedural Way 1. Introduce a description of data found in the real world. Programmers call these data items User Defined Types (UDTs) or simply types. E.g. in C, types are defined with structs, in Pascal with RECORDs. Instances of types are called objects, structs or RECORDs as well. E.g. in C, there exists a struct FILE, which acts as a handle to a real file. 2. Introduce a set of global procedures, which operate upon objects. Procedures work with passed arguments and can have side effects. Procedures can return values, then they're called functions. E.g. in C, the functions fopen(), fprintf() and fclose() operate on FILE objects. 5. 5Limitations of the procedural Paradigm The "belonging together" of procedures and types is not obvious. The object, which is "passed around" is not encapsulated. Access and manipulation of the object is possible outside of "its" procedures. There is a separation of data and procedures. This makes maintenance and extension of such APIs very hard. Refactoring is almost impossible. => But some concepts of the procedural notion should be retained: Objects are needed to simulate "things" (the data) existent in the real world. Procedures are needed to simulate operations (the behavior) with objects. Effectively, the combination of self contained data and behavior is our aim. 6. 6Expressing Objects in C# Before there are objects, types must be described. Types (classes, interfaces, structs etc. in C#) describe a blueprint for objects. Instances of types are called "objects", they are created with new and a constructor. Often type definitions are defined in separate files. 1. State: Types "contain" instances of other types to cover the whole-part Concept. Types can contain other objects (so called fields) for each of its instances. Types can contain static fields shared among all its instances. 2. Behavior: Types publish a set of procedures to operate on instances. The procedures published by a type are called "methods" in C#. Methods access and manipulate the state (i.e. the fields) of the type. Mere accessor and setter methods can be expressed with "properties". It is also possible to define static methods. 7. 7What Concepts are needed to simulate Reality? So, let's retain the concepts object and procedure from the procedural notion. Other concepts, which describe (re-)usage associations of objects are needed: Abstraction by combining data and functions into a type. Encapsulation to protect data from unwanted access and modification: The day-part of a Date instance should not be modifiable from "outside". The whole part (aggregation or composition) association: We can say "A car object has an engine object.". The specialization generalization association: We can say "three cars drive in front of me", rather then saying that there "drives a van, a bus and a sedan in front of me". The generalization ispossible, because e.g. a van is a car. "Object-orientation" (oo) is the umbrella term for these concepts. Oo languages provide features, which allow expressing these concepts. 8. 8Expressing Generalization and Specialization in C# Present types can be used as base types for new types. More special types inherit from more general types. This is called inheritance. The behavior of the base type is inherited by the new type. The new type inherits the public, protected and internal interface from its base type. The new type can add more members to the inherited one. Where an object of base type was used, an object of the derived type can be used also. => This is called substitution principle. In C# a new type can inherit from exactly one type! New types can adopt additional public interfaces. This principle is expressed with interface types. In C# there can be only one base type, but multiple interfaces can be implemented. Technically interfaces allow expressing another way of the substitution principle. 9. 9Defining new Types in C# with Classes Definition of the type Car: It has two fields: _theEngine _spareTyre Car has an Engine and a SpareTyre. And three methods: StartEngine() SetSpareTyre() GetSpareTyre() In C# all methods are defined with an inline notation (non-inline members like in C++ can't be defined in C#). Rule: one type definition (e.g. class) per file.public class Car { // Classes Engine and Tyre// elided.private Engine _theEngine;public void StartEngine() {_theEngine.Start();}private Tyre _spareTyre;public void SetSpareTyre(Tyre spareTyre) {_spareTyre = spareTyre;}public Tyre GetSpareTyre() {return _spareTyre;}}// Creation and usage of a Car instance:Car fordFocus = new Car();fordFocus.SetSpareTyre(new SpareTyre());fordFocus.StartEngine(); 10. 10public class Car {private Engine _theEngine;public void StartEngine() {_theEngine.Start();}private Tyre _spareTyre;public Tyre SetSpareTyre(Tyre spareTyre) {_spareTyre = spareTyre;}public void GetSpareTyre() {return _spareTyre;}}Simplifying the Type Car with Propertiespublic class Car {private Engine _theEngine;public void StartEngine() {_theEngine.Start();}private Tyre _spareTyre;public Tyre SpareTyre {get { return _spareTyre; }set { _spareTyre = value; }}} Getter/Setter methods can be simplified with properties.// Using Car's property SpareTyre:Car fordFocus = new Car();fordFocus.SpareTyre = new SpareTyre();fordFocus.StartEngine(); 11. 11Expressing Generalization and Specialization in C# Present types can be used as base types for new types. More special types inherit from more general types. This is called inheritance. The behavior of the base type is inherited by the new type. The new type inherits the public, protected and internal interface from its base type. The new type can add more members to the inherited one. Where an object of base type was used, an object of the derived type can be used also. => This is called substitution principle. In C# a new type can inherit from exactly one type! New types can adopt additional public interfaces. This principle is expressed with interface types. In C# there can be only one base type, but multiple interfaces can be implemented. Technically interfaces allow expressing another way of the substitution principle. 12. 12UML Notation of Car with Whole-Part Associations A Unified Modeling Language (UML) "class diagram" to design aggregated types. A class diagram underscoring structure, emphases Car's associations:CarCar has Engine and has Tyre. The hollowdiamond means "aggregation": the Car is "the whole",but Engine and Tyre are "the parts".This is a note.The class Car. A class diagram underscoring contents, emphases Car's details:Car- _theEngine : Engine- _spareTyre : Tyre+ StartEngine()+ GetSpareTyre() : Tyre+ SetSpareTyre()EngineTyreCar expandedThe fields ("attributes" inUML lingo) of Car. The fieldsare private, mind the "-" notation.The member functions ("operations" inUML lingo) of Car. The member functionsare public, mind the "+" notation. A Car instance aggregates an Engine instance (Not: the UDT Car aggregates the UDT Engine!) 13. 13Type Specialization in C#// Bus inherits from Car:public class Bus : Car { // (members hidden)private SeatBench[] _presentSeatBenches = new SeatBench[42];private SeatBench[] _occupiedSeatBenches;public bool NewPassengerCanEnter() {return(null == _occupiedSeatBenches)|| (_occupiedSeatBenches.Length < _presentSeatBenches.Length);}}// Using Bus:Bus bus = new Bus();// Accessing a method of Bus:bool hasVacantSeats = bus.NewPassengerCanEnter();// Accessing a property of Bus' base type Car:Tyre spareType = bus.SpareTyre; // Bus inherited all members of Car. A Bus is a Car. 14. 14UML Notation of Car with the Specialization Bus UML to design specialized types.CarBusSeatBench- _presentSeatBenches : SeatBench[42]- _occupiedSeatBenches : SeatBench[]+ NewPassengerCanEnter() : boolBus inherits Car. The triangular hollowarrow-tip means "inheritance".Bus has SeatBenches. 15. 15Special Fields and Methods in C# Types Referencing: We can reference the current instance's members with the this keyword. We can reference members of the base type with the base keyword. Constructors (ctors) of types. Methods that have the name of the respectively type w/o return type (not even void). Ctors have the function to initialize new instances of a type. Plain-vanilla types always have a default ctor (dctor) automatically. User defined ctors override automatically generated dctors! User defined ctors can have parameters and overloads. Ctors won't be inherited. There can also exist a finalizer (also called "destructor" (dtor)) in a type. Finalizers are automatically called by the GC to dispose of stale instances. There is no delete-operator in C#! - The GC cares for the heap automatically! 16. 16So what is oo Programming all about? The reality can be simulated to a good degree with oo-types! Most real associations can be expressed with aggregation and specialization. Even customers can understand, how oo-types function (UML)! Thinking in type interfaces rather than in algorithms and procedures. Interface and implementation can be separated, but types are complete. First define all interfaces, then (let) implement the type completely. Instead of algorithms, with types, architectures can be built. Recurring type architectures are called design patterns. There exist simple and complex design patterns. Successful (oo) programmers identify and use design patterns. 17. 17More C# Means to control Fields Access modifiers control encapsulation. Important field access modifiers: private, public and internal. The access modifier protected constrains access to derived types. The mutability of fields can be controlled. The keyword const is used for compile time constants. It's useful to avoid magic numbers! The keyword readonly is used for initialization time constants. The scope of fields can be controlled. Instance fields are individual for each object. In opposite, static fields are shared among all objects of a type. The memory strategy of fields can be controlled via the volatile keyword. 18. 18More C# Means to control Type Methods As for fields, access modifiers can be used. It is possible to define multiple overloads for methods. I.e. methods with the same name but different parameters. Parameters may vary in type, order and count. Also optional parameters can be defined. The return type may not vary! As for fields the scope of methods can be controlled (instance or static). C# provides specifiers controlling inheritance and polymorphism. These are the keywords abstract, virtual, override, new and sealed. 19. 19Example: static Fields and Methods revisitedpublic class Car { // (members hidden)private static readonly double[] AllowedWeights = new double[] { 1.0, 2.0, 3.5 };public static bool IsWeightValid(double weight) {return AllowedWeights.Contains(weight);}public double Weight { get; set; }}public class Bus : Car { // (members hidden)private new static readonly double[] AllowedWeights = new double[] { 4.0, 5.0, 8.5 };public new static bool IsWeightValid(double weight) {return AllowedWeights.Contains(weight);}}// Usage of static members (No instance of Car/Bus is required!):bool isOk = Car.IsWeightValid(2.0); // Static members are accessed with the dot.bool notOk = Bus.IsWeightValid(1.0); 20. 20Application of Documentation Comments Documentation comments can be used to generate interface descriptions. They can be used for types and its members. Use the /// (triple slash) or /** */ comment notation to enable them for each member. Within that comments XML tags can be used to markup the comment text:/// /// Returns a value indicating, whether more passengers can enter the Bus./// public bool NewPassengerCanEnter() { /* pass */ } Important tags: , , , , The contents of these comments can be used as description text within the tooltips in the VS editor (it is displayed automatically), and as XML output document, to be used as a base for a printed documentation. 21. 21Thank you!