+ All Categories
Home > Documents > (4) c sharp introduction_object_orientation_part_i

(4) c sharp introduction_object_orientation_part_i

Date post: 24-Jun-2015
Category:
Upload: nico-ludwig
View: 34 times
Download: 4 times
Share this document with a friend
Description:
- Simulation of Reality - "is-a" and "has-a" Relationship - Classes - Specialization and Generalization - Fields - Methods - Constructors - Unified Modeling Language (UML)
Popular Tags:
21
Nico Ludwig (@ersatzteilchen) (4) Introduction of C# – object-oriented Programming – Part I
Transcript
Page 1: (4) c sharp introduction_object_orientation_part_i

Nico Ludwig (@ersatzteilchen)

(4) Introduction of C# – object-oriented Programming

– Part I

Page 2: (4) c sharp introduction_object_orientation_part_i

2

TOC

● (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)

Page 3: (4) c sharp introduction_object_orientation_part_i

3

Programming 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.

● How would you describe what software does?● Software solves problems by simulating the

reality.● Simulation of reality with imperative languages is

difficult.● Procedural languages can simulate the reality

better, but there are still "impedancemismatches".

● The transition from imperative to procedurallanguages is smooth.

Page 4: (4) c sharp introduction_object_orientation_part_i

4

Real 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.

Page 5: (4) c sharp introduction_object_orientation_part_i

5

Limitations 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.

● E.g. the belonging together of global types andfunctions of the Win32 is difficult to grasp.

● E.g. the FILE struct of the C language could beinvalidly modified "outside" of the "responsible" Cfunctions (for example the file descriptor of theFILE struct could be modified).

● What is refactoring?

Page 6: (4) c sharp introduction_object_orientation_part_i

6

Expressing 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.

● Object and type:● What does this mean?

● A type describes the blueprint of objects and the objectsrequire memory for the "material" as described in theblueprint.

● Do you know more types?● enum, delegate

● What is new and what is a ctor?● The new operator allocates memory on the heap, the ctor

initializes the new object.● Similar to C++ can we create instances of classes on the

heap with new (C#'s value types (e.g. structs) are a differentstory). There is no need to call an operator like C++' delete,as C# is a .Net language, where unreferenced heap memoryis managed by the GC automatically.

● Why should we use separate files to define types?● Behavior:

● How do we "publish" methods?● All the public members (fields and methods) make up the

interface of the type.

Page 7: (4) c sharp introduction_object_orientation_part_i

7

What 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.

Page 8: (4) c sharp introduction_object_orientation_part_i

8

Expressing 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.

● According interfaces:● However, in C# it is not possible to inherit from

more than one class.● Why do we need an additional substitution

principle expressed with interfaces?● E.g. IComparable

Page 9: (4) c sharp introduction_object_orientation_part_i

9

Defining 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();

Page 10: (4) c sharp introduction_object_orientation_part_i

10

public 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 Properties

public 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();

● Properties support what is called the Uniform Access Principle (UAP, described by Bertrand Meyer). UAP advocates thatreading and writing data of an object should be done with allthe same and predictable syntax.

● Type Car aggregates _theEngine; i.e. it has an Engine.● Why is _theEngine not static?

● Because every Car has an individual engine!● The method StartEngine() encapsulates the procedure to start

the engine.● Why was that done?

● Type Car aggregates _spareTyre; i.e. it has a spare Tyre.● The spare Tyre is accessible as a property.

● Which fields of a Car could be defined as static?● As can be seen, instances of Car can be created with the new

operator. Similar to C++ can we create instances of the class Car on the heap with new (C#'s value types (e.g. structs) are adifferent story). Notice that there is no need to call an operatorlike C++' delete, as C# is a .Net language, whereunreferenced heap memory is managed by the GCautomatically.

Page 11: (4) c sharp introduction_object_orientation_part_i

11

Expressing 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.

● According interfaces:● However, in C# it is not possible to inherit from

more than one class.● Why do we need an additional substitution

principle expressed with interfaces?● E.g. IComparable

Page 12: (4) c sharp introduction_object_orientation_part_i

12

UML 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:

– A class diagram underscoring contents, emphases Car's details:

– A Car instance aggregates an Engine instance (Not: the UDT Car aggregates the UDT Engine!)

Car

- _theEngine : Engine- _spareTyre : Tyre

+ StartEngine()+ GetSpareTyre() : Tyre+ SetSpareTyre()

Engine

Car

Tyre

Car 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.

Car expanded

The fields ("attributes" inUML lingo) of Car. The fieldsare private, mind the "-" notation.

The member functions ("operations" inUML lingo) of Car. The member functions are public, mind the "+" notation.

● UML is a language to describe oo systems.● The class diagram in the structural notation

shows the associations.● The conciser notation shows the details of the

types (members, their accessibility etc.).● The static fields and methods are represented

with underlined texts in UML.

Page 13: (4) c sharp introduction_object_orientation_part_i

13

Type 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.

● The type Bus is derived from Car. So a Bus is aCar.

● A Bus has 42 seat benches. This means that thecount of seat benches is limited.

● A certain count of seat benches(_occupiedSeatBenches) is occupied bypassengers.

● Bus introduces a new public methodNewPassengerCanEnter(). This method is notpresent in the base type Car. The interface of Bus then consists of all public member of Car as wellas the new public methodNewPassengerCanEnter().● Is the type Bus allowed to access _theEngine in

Car?

Page 14: (4) c sharp introduction_object_orientation_part_i

14

UML Notation of Car with the Specialization Bus

● UML to design specialized types.

Car

Bus

- _presentSeatBenches : SeatBench[42]- _occupiedSeatBenches : SeatBench[]

+ NewPassengerCanEnter() : bool

SeatBench

Bus inherits Car. The triangular hollowarrow-tip means "inheritance".

Bus has SeatBenches.

● Inheritance in oo is different from inheritanceknow from family affairs: the children select theirparents in oo!

Page 15: (4) c sharp introduction_object_orientation_part_i

15

Special 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!

● The keyword this is context sensitive and always refers to the instanceof the type, in which it is used.

● Why is the this keyword needed?● To resolve naming conflicts w/ parameter names.● To use IntelliSense on the "own" instance.● To pass the "own" instance to a method.● To call other instance ctors from a ctor.

● Why is the base keyword needed?● To resolve naming conflicts w/ parameter names or names of the

derived type's fields.● To call bases' methods, when they're overridden in the derived type.

● A call to base.Method() will never be resolved virtually.● To call bases' instance ctors from a ctor.● The notation "base.base" isn't supported (e.g. to access the base's

base type).● The special term "default constructor" is used in the C# ECMA

standardization paper side by side with the term "parameterlessconstructor". But the special term "default constructor" is commonsense in many languages and frameworks. Special terms "standardconstructor" or "common constructor" do simply not exist officially.

● Finalizer: If manual freeing of unmanaged resources is needed; itshould be done in the finalizer. - Often the implementation of theinterface IDisposable is to be recommended additionally.

Page 16: (4) c sharp introduction_object_orientation_part_i

16

So 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.

Page 17: (4) c sharp introduction_object_orientation_part_i

17

More 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.

● Don't use public fields!● Why?

● Immutability:● const – for locals also, but only for primitive

types or null for references.● readonly – can only be initialized in ctors.

Page 18: (4) c sharp introduction_object_orientation_part_i

18

More 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.

● All access modifiers are allowed for methods, butthe modifiers public and protected are mainlyused.

Page 19: (4) c sharp introduction_object_orientation_part_i

19

Example: static Fields and Methods revisited

// 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);

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

}

● An example to explain static fields and methods:● Each Car, and each Bus instance (a Bus is a

Car) has its own individual Weight accessibleas non-static property.

● The static field Car.AllowedWeights contains allweights being valid for all Cars and the static field Bus.AllowedWeights contains all weightsbeing valid for all Buses. The static IsWeightValid() methods allow to access andcheck against the AllowedWeights.

● Important to remark: we need no instance ofCar/Bus to use these fields/methods, as they donot belong to a specific Car/Bus, but to allinstances of these types.

● static members can not be accessed viainstances, but only via type names.

Page 20: (4) c sharp introduction_object_orientation_part_i

20

Application 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:

– Important tags: <summary>, <returns>, <param>, <see>, <code>

● 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.

/// <summary>/// Returns a value indicating, whether more passengers can enter the Bus./// </summary>public bool NewPassengerCanEnter() { /* pass */ }

Page 21: (4) c sharp introduction_object_orientation_part_i

21

Thank you!


Recommended