null is the saruman of static typing

Post on 15-Jan-2015

327 Views

Category:

Engineering

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

This presentation is about the problem of Null, the system of types and monads usage. Presentation by Anton Moldovan (Lead Software Engineer, GlobalLogic, Київ), delivered at Lviv .Net TechTalk, August 20, 2014. More details - http://www.globallogic.com.ua/press-releases/lviv-dotnet-techtalk-coverage

TRANSCRIPT

Null is the Saruman of static typing

by @AntyaDev

class EmailContact { public string EmailAddress { get; set; } public bool IsEmailVerified { get; set; } }

anyone can set this to true

Rule 1: If the email is changed, the verified flag must be reset to false.

Rule 2: The verified flag can only be set by a special verification service

abstract class EmailContact { public string EmailAddress { get; set; } }

class VerifiedEmail : EmailContact { }

class UnverifiedEmail : EmailContact { }

void SendEmail(VerifiedEmail email)

Our API

public Process GetProcessByName(string name)

var process = _winApiService.GetProcessByName(name)

if (process != null)

Unfortunately nothing forces us to handle this

Can be null?

Can return null?

var id = process.Id

Concentrating on where the problem

is???

API ???

Type System

Our API

public Nullable<Process> GetProcessByName(string name)

var process = _winApiService.GetProcessByName(name)

explicit nullable value

var id = process.Id // compile time error, process.Value.Id

Avoid forcing errorsif (process != null)

Unfortunately nothing forces us to handle this

F# (pattern match expression)

match potentialValue with| None -> 0 // if you forget this line, the compiler complains| Some value -> value * value

if (process.IsSome)

var customer = _customerService.GetCustomerById(12345);

if (customer != null){ var account = customer.GetAccount("blablabla"); if (account != null) { var interest = account.GetLastInterest(); if (interest != null) { ……..

Nested if’s problem

Why?

What?How?

MONAD

Our API

public Process StartProcess(string filePath)

Can throw exception?

public Exception<Process> StartProcess(string filePath)

explicit exception value

var process = _winApiService.StartProcess(filePath)

if (process.HasException) Logger.Log(process.Exception)

http://habrahabr.ru/post/200100/

Proof

By using Maybe{T} in my code I promise that all the code will be following good citizenship principles and will keep all object references non-null (initialized to some value from the default). This promise is to be uphold by a self-discipline and unit tests.This helps to avoid all null references completely.

Optional<T> in Java 8

Thanks@AntyaDev

top related