Invariants & inversions

Post on 16-Mar-2018

69 views 2 download

transcript

Invariants and InversionsNaveen Muguda

Invariants

• logical assertions that are true for a certain phase of execution

• no matter whatever changes or whoever uses/transforms it.

Singleton

• invariant?

example

• final String s = “hello, world”

• assertion: s == “hello, world”

• Duration: as long as s is visible (s’s life time)

data invariants

• Date

• day <= 31

• month <= 12

• if month == 2, day < 30

• ….

Information hiding

• If date was a structure we can’t have invariants

• Date has to be a class/type

void selectionSort(int arr[], int n){

int i, j, min_idx;

// One by one move boundary of sorted subarrayfor (i = 0; i < n-1; i++){

// Find the minimum element in unsorted arraymin_idx = i;for (j = i+1; j < n; j++)if (arr[j] < arr[min_idx])

min_idx = j;

swap(arr, min_idx, i);}

}

Loop invariants

• arr[0, i) is sorted

• arr[min_idx] = min(arr[i,j))

• True before the first iteration, after every iteration

Loop invariants

• Invariants are generalizations of your goal

• Bubble sort, Selection sort: A[0,i) are in their eventual positions

• Insertion sort: A[0,i) is locally sorted

• Quick sort: A[0, i) < A[mid], A[j + 1, N) > A[mid]

• Merge: A[0, i), B[0, j) are in their eventual positions in C

Inversion

Responsibility division

• Heavy lifting done by Play

• a narrow and well defined responsibility given to hello world

Railway Oriented Programming

Optional:Invariants and Inversion

• Invariant: What is null, is never invoked

• Inversion: methods which operate on the wrapped value are called

t1:T1 t2:T2 t3:T3 t4:T4

null:T1 null:T2 null:T3 null:T4

t1:T1 t2:T2 t3:T3 t4:T4

v1:V1 v2:V2 v3:V3 v4:V4

Either

true true true true

falsefalse false false

Validation