Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left....

116
SOFTWARE DEVELOPMENT I 3rd lecture

Transcript of Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left....

Page 1: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

SOFTWARE DEVELOPMENT I

3rd lecture

Page 2: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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)

• KahootSoftware Engineering 1. VU MIF

Page 3: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Software Engineering 1. VU MIF

Page 4: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Themes

• #1 WORKING REMOTELY. The past situation brought a lot of challenges for

organizations 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

Page 5: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 6: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 7: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 8: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 9: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Bad example – what are reasons to change?

Software Engineering 1. VU MIF

Page 10: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 11: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Better example

Software Engineering 1. VU MIF

Page 12: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 13: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 14: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Possible inheritance

Inheritance Example

None class ClassA { }

Unitary class DerivedClass: BaseClass { }

None, implementing interfaces class ImplClass: IFace1, IFace2 { }

Unitary and implementing

interfacesclass ImplDerivedClass: BaseClass, IFace1 { }

Software Engineering 1. VU MIF

Page 15: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Access modifiersAccessibility 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

Page 16: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Default accessibility (1)

• Top level types (not nested) can only be

internal or public. Default – internal.

Members of Default accessibilityOther allowed

accessibility levels

interface public internal

struct private public

internal

private

Software Engineering 1. VU MIF

Page 17: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Default accessibility (2)

Members of Default accessibilityOther allowed

accessibility levels

enum public internal

class private public

protected

internal

private

protected internal

private protected

Software Engineering 1. VU MIF

Page 18: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 19: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Constructor

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

initialized.

Software Engineering 1. VU MIF

Page 20: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 21: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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 override).

Look abstractMethod.cs

• Virtual method: allows (optional) to override it and must have

implementation.Software Engineering 1. VU MIF

Page 22: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 23: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 24: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 25: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Optional parameters

• Must be placed in the end

of 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

Page 26: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

only 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

Page 27: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Encapsulation

Software Engineering 1. VU MIF

Page 28: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 29: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 30: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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.csSoftware Engineering 1. VU MIF

Page 31: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 32: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Generic method

• Accepts specified T type parameters:

• It is possible to have more types

• ref specifies that reference is passed

• Look generics2.csSoftware Engineering 1. VU MIF

Page 33: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Generics

Software Engineering 1. VU MIF

Page 34: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

object.

Software Engineering 1. VU MIF

Page 35: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Generics

Software Engineering 1. VU MIF

Page 36: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Generics

• Faster than using object 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

Page 37: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

SOLID

SOLID - design principles for more understandable, flexible

and maintainable software.

Software Engineering 1. VU MIF

Page 38: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 39: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 40: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 41: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Good example

Software Engineering 1. VU MIF

Page 42: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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 open

for extension).

Software Engineering 1. VU MIF

Page 43: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Good example

Software Engineering 1. VU MIF

Page 44: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 45: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 46: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 47: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 48: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

ISP (Interface segregation principle)

“Clients should not be forced to implement

interfaces they do not use”

Software Engineering 1. VU MIF

Page 49: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 50: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Better example

Software Engineering 1. VU MIF

Page 51: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 52: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 53: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

SOLID: DIP

Dependency injection – most common

way to implement DIP.

Others:

• Service Locator

• Delegates

• Events

• Etc.

Software Engineering 1. VU MIF

Page 54: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 55: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Converting integer values

Software Engineering 1. VU MIF

Page 56: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 57: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 58: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 59: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 60: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

IS

• is returns true, if objects 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

Page 61: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

AS

• as operator 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

Page 62: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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 out

parameter containing parse result or null (if parse

failed).

• Parse requires pre-validation of data.

• Difficult to work with different culture information.

• Look parsing.csSoftware Engineering 1. VU MIF

Page 63: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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:

ToBooleanToByteToChar ToDateTimeToDecimal ToDoubleToInt16 ToInt32ToInt64 ToSByteToSingle ToStringToUInt16 ToUInt32ToUInt64

Software Engineering 1. VU MIF

Page 64: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 65: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Boxing/unboxing (2)

• Boxing is implicit; unboxing is explicit.

• Sometimes is happens silently:

Software Engineering 1. VU MIF

Page 66: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Boxing/unboxing (3)

• What will be printed out?

1 and 2 2 and 5

Software Engineering 1. VU MIF

Page 67: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 68: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 69: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Constructor

• What constructors can do:

4. Call same class different constructors using: this

Look constructor(good).cs

constructor(bad).csSoftware Engineering 1. VU MIF

Page 70: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Constructor

• What constructors cant do:

5. Can not call multiple other constructors.

Look constructor(bad2).cs,

constructor(good2).cs

Software Engineering 1. VU MIF

Page 71: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Can constructor be non-public?

Software Engineering 1. VU MIF

Page 72: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 73: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Software Engineering 1. VU MIF

Page 74: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

What is

still wrong

with this

implement-

ation?

Software Engineering 1. VU MIF

Page 75: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Best way to implement singleton

Software Engineering 1. VU MIF

Page 76: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 77: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Software Engineering 1. VU MIF

Page 78: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 79: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Software Engineering 1. VU MIF

Page 80: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Questions about constructors?

Software Engineering 1. VU MIF

Page 81: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Inheritance

C# allowed C# not allowed:

Software Engineering 1. VU MIF

Page 82: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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: interfaceSoftware Engineering 1. VU MIF

Page 83: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 84: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 85: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Can a class implement two interfaces which has methods with

same signatures?

Software Engineering 1. VU MIF

Page 86: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 87: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Software Engineering 1. VU MIF

Page 88: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 89: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

only 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

Page 90: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 91: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 92: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 93: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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 operators, to check if interface type is

implemented:

– AS: ICat cat = objSomething as ICat;

– IS: if (possibleCat is ICat)Software Engineering 1. VU MIF

Page 94: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Software Engineering 1. VU MIF

Page 95: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Interfaces advantages

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

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

object?

• Answer:

Software Engineering 1. VU MIF

Page 96: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 97: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Generic Interface

• where is used to specify constraints of the types

• new() specifies that new instances can be created

Software Engineering 1. VU MIF

Page 98: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 99: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

obj.

Greater than zero This instance follows obj in the sort order.

Software Engineering 1. VU MIF

Page 100: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

IComparable

• Simple:

look IComparable.cs

• Generics:

Errors better seen

by compiler

Software Engineering 1. VU MIF

Page 101: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 102: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

IComparer

• Look

IComparer.cs

Software Engineering 1. VU MIF

Page 103: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 104: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

IEquatable

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

not work.

• Look IEquatable.cs

Software Engineering 1. VU MIF

Page 105: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

IEnumerable

• Allows to iterate (e.g. using foreach) through collection

• Has simple and generic version:

Software Engineering 1. VU MIF

Page 106: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 107: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 108: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Software Engineering 1. VU MIF

Page 109: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 110: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

ICloneable

• Deep vs shallow (Look ICloneable.cs)

Software Engineering 1. VU MIF

Page 111: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 112: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 113: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 114: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

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

Page 115: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Next time

• Software system construction.

• Key goals and challenges.

• Business needs analysis.

• Software system modification and maintenance (introduction)

Software Engineering 1. VU MIF

Page 116: Applied object oriented programming · N. •University Advisor –team Laurynas R., one slot left. •MoodDetector –one slot, not yet filled •Meetup –today, 20:00 Saulėtekioal.

Questions

Software Engineering 1. VU MIF