SOFTWARE DEVELOPMENT I 3rd lecture Today Type conversions Three - - PowerPoint PPT Presentation

software development i
SMART_READER_LITE
LIVE PREVIEW

SOFTWARE DEVELOPMENT I 3rd lecture Today Type conversions Three - - PowerPoint PPT Presentation

SOFTWARE DEVELOPMENT I 3rd lecture Today Type conversions Three main OOP pillars Constructors in depth Classes: Class inheritance fields, properties, methods, actions, delegates, nested types Interfaces Access


slide-1
SLIDE 1

SOFTWARE DEVELOPMENT I

3rd lecture

slide-2
SLIDE 2

Today

  • Three main OOP pillars
  • Classes:

– fields, properties, methods, actions, delegates, nested types – Access modifiers

  • Generics
  • SOLID
  • Type conversions
  • Constructors in depth
  • Class inheritance
  • Interfaces
  • Standard .NET interfaces

– IComparable – IComparer – IEquatable – IEnumerable – ICloneable (and cloning)

  • Kahoot

Software Engineering 1. VU MIF

slide-3
SLIDE 3

Software Engineering 1. VU MIF

slide-4
SLIDE 4

Themes

  • #1 WORKING REMOTELY. The past situation brought a lot of challenges for
  • rganizations on how to set-up, embrace and support remote work. Your smart

hacks are needed to help utilize offices and resources – how to use them effectively? How to increase trust in each other?

  • #2 DIGITAL WORKPLACE. It’s not just about apps, tools or next generation devices.

We are looking into hacks that tackle collaboration, mobility and productivity in the future digital workplace. How to use digital tools in a full capacity? How to increase productivity?

  • #3 EMPLOYEE ENGAGEMENT – Stretch your brain with fundamental challenges and

how they should change in the future! How to onboard new employees effectively? How to keep team bonds?

Software Engineering 1. VU MIF

slide-5
SLIDE 5

Prizes

  • 1st place:

– Oculust Quest S all-in-one gaming system – Amazon gift coupons 5 x 150 Eur.

  • 2nd place – Amazon gift coupons 5 x 125 Eur.
  • Most creative – Arduino Uno starter kit.
  • Register here until 4th of October: https://bit.ly/2XU6oga

Software Engineering 1. VU MIF

slide-6
SLIDE 6

OOP basics

  • Encapsulation – programming methodology,

– Forbids access to specifics of the class. – Allows modify class properties and fields only through exposed methods.

  • Inheritance:

– Possibility to reuse, extend or modify class implementation.

  • Polymorphism:

– At run time objects of derived class may be treated as objects of a base class in methods, parameters or collections. Also, derived classes may implement different methods behaviour than base class, if base class methods are marked as virtual

Software Engineering 1. VU MIF

slide-7
SLIDE 7

Classes

  • Class:

– Description, specifying some sort of object data structure and behavior.

  • Single responsibility – classes are created using this principle!
  • Class can contain:

– constructor, constants, fields, methods, properties, delegates, classes and more.

Software Engineering 1. VU MIF

slide-8
SLIDE 8

SRP (Single responsibility principle)

„A class should only have one reason to change“ ~ „A class should only have one responsibility“

If a class has more than one responsibility, then the responsibilities become coupled. Changes to one responsibility may break the class’ ability to fulfil other responsibilities.

Can be applied to:

  • Methods
  • Modules
  • Etc.

Software Engineering 1. VU MIF

slide-9
SLIDE 9

Bad example – what are reasons to change?

Software Engineering 1. VU MIF

slide-10
SLIDE 10

Possible reasons to change

What if I decide to read from DB? What if I decide to change validation logic? What if I change generation logic?

Software Engineering 1. VU MIF

slide-11
SLIDE 11

Better example

Software Engineering 1. VU MIF

slide-12
SLIDE 12

Bad example – many responsibilities

class Customer { public void Add() { try { // Database code goes here } catch (Exception ex) { System.IO.File.WriteAllText(@"c:\Error.txt", ex.ToString()); } } }

Software Engineering 1. VU MIF

slide-13
SLIDE 13

Better example

class FileLogger { public void Log(string error) { System.IO.File.WriteAllText(@"c:\Error.txt", error); } } class Customer { private FileLogger _logger = new FileLogger(); public virtual void Add() { try { // Database code goes here } catch (Exception ex) { _logger.Log(ex.ToString()); } } }

Software Engineering 1. VU MIF

slide-14
SLIDE 14

Possible inheritance

Inheritance Example None class ClassA { } Unitary class DerivedClass: BaseClass { } None, implementing interfaces class ImplClass: IFace1, IFace2 { } Unitary and implementing interfaces class ImplDerivedClass: BaseClass, IFace1 { }

Software Engineering 1. VU MIF

slide-15
SLIDE 15

Access modifiers

Accessibility Description public Access is not restricted. protected Access is limited to the containing class or types derived from the containing class. internal Access is limited to the current assembly (same .dll). Look internal.cs protected internal Access is limited to the current assembly or types derived from the containing class. private Access is limited to the containing type. private protected Access is limited to the containing class or types derived from the containing class within the current assembly.

Software Engineering 1. VU MIF

slide-16
SLIDE 16

Default accessibility (1)

  • Top

level types (not nested) can

  • nly

be internal or public. Default – internal.

Members of Default accessibility Other allowed accessibility levels interface public internal struct private public internal private

Software Engineering 1. VU MIF

slide-17
SLIDE 17

Default accessibility (2)

Members of Default accessibility Other allowed accessibility levels enum public internal class private public protected internal private protected internal private protected

Software Engineering 1. VU MIF

slide-18
SLIDE 18

Static vs instance

  • Static class is in a way the same as non static, difference is that

there is no possibility to create static class object. (no new).

  • Static classes should be used, when you don’t need to save state.
  • Similar with fields, look static.cs
  • Static class can only have static methods, non static class can have

both.

  • Memory is divided to three parts when its loaded: Stack, Heap, and

Static (in .NET it is known as High Frequency Heap).

Software Engineering 1. VU MIF

slide-19
SLIDE 19

Constructor

  • Constructor is a method that is being called when class is being

initialized.

Software Engineering 1. VU MIF

slide-20
SLIDE 20

Methods (1)

  • Syntax:

modifier returnType name (parameters) { statements; }

  • For value types as a parameters the copy of a value is passed, for

reference types as a parameters – reference is passed. Look refvsvalue.cs

Software Engineering 1. VU MIF

slide-21
SLIDE 21

Methods (2)

  • Method overloading:

– Different signatures (return type is not counted in signature)

  • Abstract method:

– Defined method signature, but there is no implementation. – Only possible in abstract class. – Inherit class must implement abstract method (using

  • verride).

Look abstractMethod.cs

  • Virtual

method: allows

(optional) to

  • verride

it and must have implementation.

Software Engineering 1. VU MIF

slide-22
SLIDE 22

Methods (3)

  • Extensions:

– Possibility to extend standard class. – Syntax: public static type MethodName(this typeToExtend str) – Look extensionMethod.cs – Cannot override standard extension methods: – Works in same namespace or by importing namespace with „using“

Software Engineering 1. VU MIF

slide-23
SLIDE 23

Named parameters

  • Allows to pass parameters in different order than method signature.
  • Brings more clarity.
  • Named parameters can be passed after standard ones, but not before.

Software Engineering 1. VU MIF

slide-24
SLIDE 24

Optional parameters

  • Syntax:

– Providing default (or constant) value to a parameter – „new ValType()“, if parameter is reference type (class) – default(ValType), if parameter is value type (e.g enum or struct).

  • Allowed to be used in:

– methods, constructors, indexed properties and delegates

Software Engineering 1. VU MIF

slide-25
SLIDE 25

Optional parameters

  • Must be placed in the end
  • f parameters list.
  • If the caller provides an

argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.

Software Engineering 1. VU MIF

slide-26
SLIDE 26

Encapsulation

  • OOP encapsulation term means that some entity members, behavior and

fields can be wrapped in a class.

  • That is that internal (private) fields are hidden from the user and you can
  • nly modify those using exposed (public) methods.
  • Encapsulation allows to be loosely coupled from the actual implementation,

and that allows us:

– To change from one type of object to another; – Refactor/change class without changing usages.

Software Engineering 1. VU MIF

slide-27
SLIDE 27

Encapsulation

Software Engineering 1. VU MIF

slide-28
SLIDE 28

Properties

  • Property – method to access private field.
  • Can be: public, private, protected, internal or protected internal.
  • Can be static – enables to access it without creating instance of a

class.

Software Engineering 1. VU MIF

slide-29
SLIDE 29

Auto-properties

  • If you don’t need additional logic inside.
  • Compiler creates hidden private backing field:
  • Properties can have restricted access:
  • Look property.cs

Software Engineering 1. VU MIF

slide-30
SLIDE 30

Indexer (indexed properties)

  • Indexers enable objects to be indexed in a similar manner to

arrays.

  • Takes index as a parameter.
  • Defined with „this“, has

get and set, just like normal properties:

  • Can be used in both class and struct.
  • Possible to have only one indexer in class/struct.
  • Look indexer1.cs and indexer2.cs

Software Engineering 1. VU MIF

slide-31
SLIDE 31

Generics

  • Generics: enables specifying

type of class or method only when creating it.

  • Advantages: code reusability,

types safe, efficiency (no need for unboxing).

  • C# syntax <T> (letter(s) can

be different).

  • Look generics1.cs

Software Engineering 1. VU MIF

slide-32
SLIDE 32

Generic method

  • Accepts specified T type parameters:
  • It is possible to have more types
  • ref specifies that reference is passed
  • Look generics2.cs

Software Engineering 1. VU MIF

slide-33
SLIDE 33

Generics

Software Engineering 1. VU MIF

slide-34
SLIDE 34

Generics

  • Ensure types safety:

– List<string> must be filled with only string values.

  • Compiler would display an error if you would try

to add integer to a List<string>. If you would use ArrayList – it would not, because it accepts

  • bject.

Software Engineering 1. VU MIF

slide-35
SLIDE 35

Generics

Software Engineering 1. VU MIF

slide-36
SLIDE 36

Generics

  • Faster

than using

  • bject

because it prevents boxing/unboxing to happen or casting to required type/value from object.

  • Promotes code reusability:

– More: MSDN - When to Use Generic Collections – Look generics3.cs

Software Engineering 1. VU MIF

slide-37
SLIDE 37

SOLID

SOLID - design principles for more understandable, flexible and maintainable software.

Software Engineering 1. VU MIF

slide-38
SLIDE 38

S – Single responsibility principle (SRP) O – Open/closed principle (OCP) L – Liskov substitution principle (LSP) I – Interface segregation principle (ISP) D – Dependency inversion principle (DIP)

Software Engineering 1. VU MIF

slide-39
SLIDE 39

OCP (Open/closed principle)

“You should be able to extend a classes behavior, without modifying it”

~

“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”

Achieved via OOP (e.g. polymorphism) We start thinking about OCP, as soon as there is a need "add one more..."

Software Engineering 1. VU MIF

slide-40
SLIDE 40

Bad example

class Customer { public int CustomerType {get; set;} public double GetDiscount(double TotalSales){ { if(CustomerType == 1) { return TotalSales – 100; } else { return TotalSales – 50; } } }

Software Engineering 1. VU MIF

slide-41
SLIDE 41

Good example

Software Engineering 1. VU MIF

slide-42
SLIDE 42

Bad example

  • AreaCalculator

not closed for modification – if logic change is needed, code change is needed

  • e.g. it is not possible to

adress logic change with adding (not changing) the code (not

  • pen

for extension).

Software Engineering 1. VU MIF

slide-43
SLIDE 43

Good example

Software Engineering 1. VU MIF

slide-44
SLIDE 44

LSP (Liskov substitution principle)

"objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program“ ~ “ subtype behavior should match base type behavior as defined in the base type specification” In simple terms: Derived classes must be substitutable for their base classes.

Software Engineering 1. VU MIF

slide-45
SLIDE 45

Example

public class Rectangle { public int Width { get; protected set; } public int Height { get; protected set; } public void SetWidth(int width) => Width = width; public void SetHeight(int height) => Height = height; public int GetArea() { return Width * Height; } } public class Square : Rectangle { public void SetWidth(int width) { Width = width; Height = width; } public void SetHeight(int height) { Width = height; Height = height; } } Software Engineering 1. VU MIF

slide-46
SLIDE 46

public class LspTest { private static Rectangle CreateRectangle() { return new Square(); } public static void Main(string[] args) { Rectangle rect = CreateRectangle(); rect.SetWidth(5); rect.SetHeight(10); // User assumes that rect is a rectangle. // They assume that they are able to set the width and height as for the base class Assert.AreEqual(rect.GetArea(), 50); // This check fails for a square! We get 100 } } Software Engineering 1. VU MIF

slide-47
SLIDE 47

LSP Checklist

  • No new exceptions should be thrown in derived class: If your base

class threw ArgumentException then your subclasses are only allowed to throw exceptions of type ArgumentException or any exceptions derived from it. Throwing IndexOutOfRangeException is a violation of LSP.

  • Pre-conditions cannot be strengthened: Assume your base class works

with a member int. Now your subtype requires that int to be positive. This is strengthened pre-conditions, and now any code that worked perfectly fine before with negative ints is broken.

  • Post-conditions cannot be weakened: Assume your base class required

all connections to database to be closed before the method returned. In your subclass you overrode that method and left connection open for further reuse.

Software Engineering 1. VU MIF

slide-48
SLIDE 48

ISP (Interface segregation principle)

“Clients should not be forced to implement interfaces they do not use”

Software Engineering 1. VU MIF

slide-49
SLIDE 49

Bad example

– All code needs to be recompiled for even the smallest changes. – What if device wants only to print? – This is a fat interface.

Software Engineering 1. VU MIF

slide-50
SLIDE 50

Better example

Software Engineering 1. VU MIF

slide-51
SLIDE 51

ISP summary

  • We favor:

– Composition instead of Inheritance

  • Separating by roles (responsibilities)

– Decoupling over Coupling

  • Not coupling derivative classes with unneeded responsibilities inside a monolith

Software Engineering 1. VU MIF

slide-52
SLIDE 52

DIP (Dependency inversion principle)

“Depend on abstractions, not on concretions” – High level modules should not depend upon low level

  • modules. Both should depend upon abstractions.

– Abstractions should not depend upon details. Details should depend upon abstractions.

Software Engineering 1. VU MIF

slide-53
SLIDE 53

SOLID: DIP

Dependency injection – most common way to implement DIP. Others:

  • Service Locator
  • Delegates
  • Events
  • Etc.

Software Engineering 1. VU MIF

slide-54
SLIDE 54

Types conversion (1)

  • Widening vs narrowing:

– Widening: type that we are converting to can store more values than type from which we are converting (short -> int). – Narrowing: vice versa(int -> short).

  • C# does not throw an exception, if narrowing

conversion fails for integers or floating point numbers.

– For integer values value is decreased – For floating point numbers infinity value is set.

Software Engineering 1. VU MIF

slide-55
SLIDE 55

Converting integer values

Software Engineering 1. VU MIF

slide-56
SLIDE 56

Types conversion (2): solutions

  • Integers:

using checked statement, which throws OverflowException

  • Integers: project settings configuration:
  • Properties -> Build tab -> Advanced -> Check For Arithmetic Overflow (true).
  • Disadvantage – code does not reflect program behavior.
  • Floating point numbers:

Software Engineering 1. VU MIF

slide-57
SLIDE 57

Implicit vs explicit conversion

  • Implicit: conversion without using additional code.
  • Explicit: using additional code (like cast or parsing)

methods.

  • Converting

floating point numbers to integers, everything after “.” is cut:

– (int)10.9 returns 10.

Software Engineering 1. VU MIF

slide-58
SLIDE 58

Reference types conversion

  • Reference types conversion to a base class or interface is possible implicitly.
  • If Employee class inherits from Person class, then Employee object can be

converted to Person object implicitly:

Software Engineering 1. VU MIF

slide-59
SLIDE 59

Reference types conversion

  • Reference types conversion to a base class or interface does not change the

actual value, just makes it look as a new type.

– person1 is Person type variable, but points to Employee object. – Code can use person1 object as Person type, but in memory it stays as Employee type object.

  • Look refConversion.cs

Software Engineering 1. VU MIF

slide-60
SLIDE 60

IS

  • is

returns true, if

  • bjects

are compatible (if casting/conversion is possible)

  • „person is Employee“ returns true not only when

person is Employee type, but also when person is Manager type (because Manager is Employee)

Software Engineering 1. VU MIF

slide-61
SLIDE 61

AS

  • as
  • perator

work as cast. If conversion fails, as returns null instead of throwing an exception.

  • Syntax suggar
  • Arrays conversion: arrayCast1.cs

– cast does not create new arrays! – As this would not create as well:

Software Engineering 1. VU MIF

slide-62
SLIDE 62

Parse and tryParse

  • All primitive C# data types (int, bool, double, and so

forth) has Parse method.

  • bool.Parse("yes") will throw FormatException
  • bool.Parse("true") returns bool type true value.
  • parse

throws exceptions, tryParse returns

  • ut

parameter containing parse result or null (if parse failed).

  • Parse requires pre-validation of data.
  • Difficult to work with different culture information.
  • Look parsing.cs

Software Engineering 1. VU MIF

slide-63
SLIDE 63

System.Convert

  • “bankers rounding”:

– Rounds to the closest integer value. – If it ends with .5, then it rounds to closest even number.For example below would result in 10:

  • You can also do it like that:

ToBoolean ToByte ToChar ToDateTime ToDecimal ToDouble ToInt16 ToInt32 ToInt64 ToSByte ToSingle ToString ToUInt16 ToUInt32 ToUInt64

Software Engineering 1. VU MIF

slide-64
SLIDE 64

Boxing/unboxing (1)

  • Process when value type is converted to object or interface type, which value types

implements.

– Lets say we are converting int or bool (or similar) to object type, or to interface, which is supported by that value type (e.g. struct).

  • Unboxing is a process, when boxed value is converted back from reference type to value

type.

  • Both processes are slow:

– Boxing – because of heap usage – Unboxing – because of casting

Software Engineering 1. VU MIF

slide-65
SLIDE 65

Boxing/unboxing (2)

  • Boxing is implicit; unboxing is explicit.
  • Sometimes is happens silently:

Software Engineering 1. VU MIF

slide-66
SLIDE 66

Boxing/unboxing (3)

  • What will be printed out?

1 and 2 2 and 5

Software Engineering 1. VU MIF

slide-67
SLIDE 67

Constructors

  • Constructor – it is a method that is being called first when an instance of a

class or struct being created.

  • Same for static constructor – but only for the first time.
  • What constructors can do:
  • 1. Overload

Software Engineering 1. VU MIF

slide-68
SLIDE 68

Constructor

  • What constructors can do:
  • 2. Call base class constructor using keyword : base

(look constructor(intro).cs)

  • 3. If there are no explicit constructor defined – the

default constructor is being created implicitly:

  • There are no parameters.
  • Field values are initialized to default value.
  • Causes problems when changes are needed.

Software Engineering 1. VU MIF

slide-69
SLIDE 69

Constructor

  • What constructors can do:
  • 4. Call same class different constructors using: this

Look constructor(good).cs constructor(bad).cs

Software Engineering 1. VU MIF

slide-70
SLIDE 70

Constructor

  • What constructors cant do:
  • 5. Can not call multiple other constructors.

Look constructor(bad2).cs, constructor(good2).cs

Software Engineering 1. VU MIF

slide-71
SLIDE 71

Can constructor be non-public?

Software Engineering 1. VU MIF

slide-72
SLIDE 72

Constructors

What constructors can do:

  • 6. Private/public constructors:

1. Public is standard 2. Private constructors are not allowed to be called from other classes, so if we want to create an instance of such class, there is a special implementation that we have to provide.

Look singleton.cs

Software Engineering 1. VU MIF

slide-73
SLIDE 73

Software Engineering 1. VU MIF

slide-74
SLIDE 74

What is still wrong with this implement- ation?

Software Engineering 1. VU MIF

slide-75
SLIDE 75

Best way to implement singleton

Software Engineering 1. VU MIF

slide-76
SLIDE 76

Constructors

What constructors can do:

  • 7. Static constructor (Look static.cs)

– Is called implicitly when:

  • Class instance is created
  • Class static fields or methods are used for the first time

– Class can have only one static constructor – Has to be parameter-less, becase CLR is calling it – Can access only static fields/methods of this class – Static constructor does not have access modifiers – Slow

Software Engineering 1. VU MIF

slide-77
SLIDE 77

Software Engineering 1. VU MIF

slide-78
SLIDE 78

Initializer

  • Explicit creation of an object by setting all the properties

manually.

  • Only the standard constructor is called
  • Example in the next slide

Software Engineering 1. VU MIF

slide-79
SLIDE 79

Software Engineering 1. VU MIF

slide-80
SLIDE 80

Questions about constructors?

Software Engineering 1. VU MIF

slide-81
SLIDE 81

Inheritance

C# allowed C# not allowed:

Software Engineering 1. VU MIF

slide-82
SLIDE 82

Multiple inheritance

Diamond problem:

If A has a method, which B and C classes have overridden, but D did not, then which method will D inherit – from B or from C? From A method is called successfully, but from D – not necessarily.

C# solution: interface

Software Engineering 1. VU MIF

slide-83
SLIDE 83

Interface

  • Interface

exposes a contract, specifying characteristics that a class must implement.

  • Can state required: properties, methods and

actions.

  • Interface can not contain any static members
  • Interface can not have implementation of the

methods (different from abstract class, because abstract class can have implementation).

Software Engineering 1. VU MIF

slide-84
SLIDE 84

Interface

  • Since it is similar to inheritance, sometimes it is

being called interface inheritance

  • Class can inherit from ONE base class, and

MANY interfaces

  • Look interface.cs – TeachingAssistant

Software Engineering 1. VU MIF

slide-85
SLIDE 85

Can a class implement two interfaces which has methods with same signatures?

Software Engineering 1. VU MIF

slide-86
SLIDE 86

Explicit and implicit interface implementation

  • If class implements an interface explicitly, then to access

implemented method you will need a object of interface type, if and interface is implemented implicitly – then you can access method with class type object.

  • Explicitly implementing interface requires to write interface

method before method name like:

– void Interface.Method

  • In interface.cs look at TeachingAssistant3 which implements

Istudent interface implicitly, and TeachingAssistant4 – explicitly.

Software Engineering 1. VU MIF

slide-87
SLIDE 87

Software Engineering 1. VU MIF

slide-88
SLIDE 88

Explicit and implicit interface implementation

  • Explicit is better, because:

– When working with interface type there is no coupling with a class that implements it.

  • Loose coupling allow to scale and change system easier.

– You can have members in your class with same names as in implemented interface:

  • If we have a class with property Name, and we want to

implement interface, which has in a contract property Name – we can do it by using explicit interface implementation.

Software Engineering 1. VU MIF

slide-89
SLIDE 89

Explicit and implicit interface implementation

  • If you are implementing interface implicitly then the

methods will be available for class that implements this interface type objects, and for interface type objects. Sometimes this is not a desired functionality.

  • If you are implementing interface explicitly, then access

modifier must be private, because your method can

  • nly be accessed via interface.
  • When implementing explicitly, we don’t have duplicate

names problems.

  • In reality – 90% of implicit implementation.

Software Engineering 1. VU MIF

slide-90
SLIDE 90

Interface delegation

  • If both Student and TeachingAssistant implements IStudent

interface, then both have a code,which ensures that contract is fulfilled.

  • Duplication of code can be avoided by using interface delegation.

– That means that implementation of interface in TeachingAssistant class is being delegated to Student class.

Software Engineering 1. VU MIF

slide-91
SLIDE 91

Interface delegation

  • In the delegation process a object of type Student is being

created in TeachingAssistant class.

– When TeachingAssistant object has to perform methods, which are in IStudent interface, then Student object is called to do that.

  • Look interface.cs: TeachingAssistant (bad, because of

code duplication), TeachingAssistant2

Software Engineering 1. VU MIF

slide-92
SLIDE 92

Indexers in interfaces

  • Differs from indexers in the

class:

– No access modifiers. – No implementation.

  • Class can implement multiple

interfaces with indexers only if interfaces are being implemented explicitly.

Software Engineering 1. VU MIF

slide-93
SLIDE 93

Interface is a TYPE

  • You can specify it as a parameter to a method

– interface2.cs – takeSpeaker() – If you are passing a class object, that implement an interface, then this object is implicitly being casted to a interface type.

  • Return type can be an interface:

– interface2.cs – giveSpeaker()

  • Casting
  • perators,

to check if interface type is implemented:

– AS: ICat cat = objSomething as ICat; – IS: if (possibleCat is ICat)

Software Engineering 1. VU MIF

slide-94
SLIDE 94

Software Engineering 1. VU MIF

slide-95
SLIDE 95

Interfaces advantages

  • Question: why should we define interface, implement it in a class

and then create interface type of object, instead of class type

  • bject?
  • Answer:

Software Engineering 1. VU MIF

slide-96
SLIDE 96

Generic Interface

  • Interface can be generic (have a type passed as parameter)

public class Farmer : IRememberMostRecent<Joke>

  • Class can only implement generic interface, if the class itself is

generic.

– In that case type to an interface is passed when constructing class: public class Dog<T> : ICanEat<T>

  • Look interfaceGeneric.cs

Software Engineering 1. VU MIF

slide-97
SLIDE 97

Generic Interface

  • where is used to specify constraints of the types
  • new() specifies that new instances can be created

Software Engineering 1. VU MIF

slide-98
SLIDE 98

Standard interface implementation

  • Benefit – contract implementation
  • .NET behaves “better” with types, that implement:

– IComparable interface, Array.Sort() method can sort an array of that class members. – IEquatable interface, then list.Contains() can check, whether an object is really in the list(instead of checking if same pointer is in the list)

Software Engineering 1. VU MIF

slide-99
SLIDE 99

IComparable

  • Used for comparing this object to a given object.
  • Has one method: CompareTo (one param., obj)
  • Has both simple and generic version

Value Meaning Negative This instance precedes obj in the sort order. Zero This instance occurs in the same position in the sort order as

  • bj.

Greater than zero

This instance follows obj in the sort order.

Software Engineering 1. VU MIF

slide-100
SLIDE 100

IComparable

  • Simple:

look IComparable.cs

  • Generics:

Errors better seen by compiler

Software Engineering 1. VU MIF

slide-101
SLIDE 101

IComparer

  • IComparable<T> says I’m comparable.
  • IComparer<T> says I’m comparer.
  • Method: compare(two params)

Value Meaning Less than zero First object is less than the second. Zero Both object are equal. Greater than zero First object is more than the second.

Software Engineering 1. VU MIF

slide-102
SLIDE 102

IComparer

  • Look

IComparer.cs

Software Engineering 1. VU MIF

slide-103
SLIDE 103

IEquatable

  • Is used for comparing if two objects are equal.
  • Has method Equals.
  • Generic collections: List, Dictionary, Stack, Queue

(etc.) has Contains method, which compares objects for equality.

  • If

Iequatable interface is implemented then List.Contains check by using our implemented Equals method.

  • Microsoft recommends that every class that has a

possibility to be added to a list would implement IEquatable interface.

Software Engineering 1. VU MIF

slide-104
SLIDE 104

IEquatable

  • If IEquatable<> would be removed – Contains method would

not work.

  • Look IEquatable.cs

Software Engineering 1. VU MIF

slide-105
SLIDE 105

IEnumerable

  • Allows to iterate (e.g. using foreach) through collection
  • Has simple and generic version:

Software Engineering 1. VU MIF

slide-106
SLIDE 106

IEnumerable

  • Has method GetEnumerator, which returns an object,

which implements an interface IEnumerator.

  • IEnumerator has:

– Current property, which returns current object from the list – MoveNext method, which moves enumerator one position forward. – Reset which moves enumerator to the initial position. – Dispose (only generics) – inherited from IDisposable.

  • Look IEnumerator.cs

Software Engineering 1. VU MIF

slide-107
SLIDE 107

IEnumerable

  • Can be simplified with yield. Look Ienumerable*.cs
  • Must:

– Return IEnumerable type – Be called from iteration loop(e.g foreach)

Software Engineering 1. VU MIF

slide-108
SLIDE 108

Software Engineering 1. VU MIF

slide-109
SLIDE 109

ICloneable

  • From JAVA lectures: new object copy creationis

when object is same type as a type that it is being cloned from and has same state.

  • Possible:

– Shallow cloning – Deep cloning

  • C#: class that implements ICloneable interface must

implement Clone method.

– Returns cloned object (seriously, object type)

Software Engineering 1. VU MIF

slide-110
SLIDE 110

ICloneable

  • Deep vs shallow (Look ICloneable.cs)

Software Engineering 1. VU MIF

slide-111
SLIDE 111

ICloneable

  • Since Clone method returns object type object, then whoever called Clone

method has to take care of casting returned object to required type.

  • Implementation is hidden (deep vs shallow):

– Microsoft does not recommend to implement Icloneable for exposed APIs, because consumers will not know how your Clone method will behave. – More: MSDN ICloneable Interface.

Software Engineering 1. VU MIF

slide-112
SLIDE 112

Other popular .NET interfaces

  • IQueryable (or IQueryProvider): allows to form queries for datasources, that are

queryable.

  • INotifyPropertyChange: is used to display data in WPF, Windows Forms and

Silverlight applications.

  • IEqualityComparer (similar to IEquatable)
  • IList and ICollection: for collections
  • IDictionary: for collections, in which you can search using key/value principle.
  • ISerializable – allows for an object to control how it is being serialized/deserialized.
  • IFormatter / IFormatProvider – used for formatting.

Software Engineering 1. VU MIF

slide-113
SLIDE 113

Literature for reading

  • A must: C# in depth. Why Properties Matter (online)
  • Types (C# Programming Guide). MSDN
  • MCSD sertification toolkit:

– 3rd chapter second side – 4th chapter. Converting between types. – MSDN: When to Use Generic Collections

  • More: MSDN - When to Use Generic Collections

Software Engineering 1. VU MIF

slide-114
SLIDE 114

Literature for own reading

  • MCSD sertification toolkit:

– 5th chapter until “Managing object lifecycle”

  • MSDN
  • MSDN: Boxing and Unboxing (C# Programming Guide)
  • On you own: IEnumerable and IEnumerator

– How simple and generic version are different?

Software Engineering 1. VU MIF

slide-115
SLIDE 115

Next time

  • Software system construction.
  • Key goals and challenges.
  • Business needs analysis.
  • Software system modification and maintenance (introduction)

Software Engineering 1. VU MIF

slide-116
SLIDE 116

Questions

Software Engineering 1. VU MIF