Closures & Functional Programing

download Closures & Functional Programing

of 41

Transcript of Closures & Functional Programing

  • 7/31/2019 Closures & Functional Programing

    1/41

    1/41

    Closures & FunctionalPrograming

    They are a block of code plus thebindings to the environment they camefrom (Ragusa Idiom).

    Refactoring is improving the design of code after ithas been written

  • 7/31/2019 Closures & Functional Programing

    2/41

    2/41

    Agenda 05.06.2012 Closure as a Code Block

    Long History

    Dynamic Languages

    Functional Programming Examples

    Closures & Refactoring

    Case Study Experiences with a Polygraph Design

    Links

  • 7/31/2019 Closures & Functional Programing

    3/41

    3/41

    Code Blocks

    How many times have you written a piece of

    code and thought I wish I could reuse thisblock of code?

    How many times have you refactored existing

    code to remove redundancies?How many times have you written the same

    block of code more than once beforerealising that an abstraction exists?

  • 7/31/2019 Closures & Functional Programing

    4/41

    4/41

    Why Closures?Languages that support closures allow you to

    define functions with very little syntax.While this might not seem an importantpoint, I believe it's crucial - it's the key to

    make it natural to use them frequently.Look at Lisp, Smalltalk, or Ruby code andyou'll see closures all over the place.

    UEB: demos/threads/thrddemo.exe

  • 7/31/2019 Closures & Functional Programing

    5/41

    5/41

    Closure Improves

    automatisation and integration of new

    methods, better testability and readability

    (simplification)

    SourceSourcefindfind

    FunctionFunction

    nUnitnUnit

    test

    test

    RefactorRefactor

    change

    change

    PatternPattern

    block

    block

    idiom

    idiom

  • 7/31/2019 Closures & Functional Programing

    6/41

    6/41

    Whats a closure ?Never touch a running system ?!://Calls n times a value:

    Ruby

    def n_times(a_thing)

    return proc{ |n| a_thing * n} end

    c1 = n_times(23) puts c1.call(1) # -> 23 puts c1.call(3) # -> 69

  • 7/31/2019 Closures & Functional Programing

    7/41

    7/41

    Closure Counter def counter(start)

    return proc {start *= 3}end

    k = counter(1)

    g = counter(10)

    puts k.call # -> 3 puts k.call # -> 9

    puts g.call # -> 30 puts k.call # -> 27

    UEB: 8_pas_verwechselt.txt

  • 7/31/2019 Closures & Functional Programing

    8/41

    8/41

    Closure: Definition Closures are reusable blocks of code that

    capture the environment and can be passedaround as method arguments for immediateor deferred execution.

    Simplification: Your classes are small andyour methods too; youve said everything and

    youve removed the last piece of unnecessarycode.

  • 7/31/2019 Closures & Functional Programing

    9/41

    9/41

    Closure in PHP def times(n):

    def _f(x):return x * n

    return _f

    t3 = times(3)

    print t3 # print t3(7) # 21

  • 7/31/2019 Closures & Functional Programing

    10/41

    10/41

    Closure in Pythondef generate_power_func(n):

    def nth_power(x): //closurereturn x**n

    return nth_power

    >>> raised_to_4 = generate_power_func(4)

    debug:

    id(raised_to_4) == 0x00C47561 == id(nth_power)).

    >>> raised_to_4(2) 16

  • 7/31/2019 Closures & Functional Programing

    11/41

    11/41

    History Lisp started in 1959

    Scheme as a dialect of Lisp

    One feature of the language was function-

    valued expressions, signified by lambda. Smalltalk with Blocks.

    Lisp used something called dynamic

    scoping.

  • 7/31/2019 Closures & Functional Programing

    12/41

    12/41

    Dynamic LanguagesThe increase in importance of web services, however, has

    made it possible to use dynamic languages (where

    types are not strictly enforced at compile time) for largescale development. Languages such as Python, Ruby,and PHP.

    Scheme was the first language to introduce closures,allowing full lexical scoping, simplifying many types ofprogramming style.

    for i:= 0 to SourceTable.FieldCount - 1 do

    DestTable.Fields[i].Assign(SourceTable.Fields[i]);DestTable.Post;

  • 7/31/2019 Closures & Functional Programing

    13/41

    13/41

    Closure in Math Optimization

  • 7/31/2019 Closures & Functional Programing

    14/41

  • 7/31/2019 Closures & Functional Programing

    15/41

    15/41

    Function Pointer IIAre Business Objects available (Closure Extensions)?

    In a simple business object (without fields in the class),you do have at least 4 tasks to fulfil:

    1. The Business-Class inherits from a Data-Provider2. The closure query is part of the class3. A calculation or business-rule has to be done4. The object is independent from the GUI, GUI calls the

    objectBusiness objects are sometimes referred to as conceptual objects,

    because they provide services which meet business requirements,

    regardless of technology.

  • 7/31/2019 Closures & Functional Programing

    16/41

    16/41

    DelegatesMethod Pointers (Object Organisation) ppform:= TForm.Create(self);

    with ppform do begin caption:= 'LEDBOX, click to edit, dblclick write out pattern'+ ' Press to run the Sentence'; width:= (vx*psize)+ 10 + 300; height:= (vy*psize)+ 30;

    BorderStyle:= bsDialog; Position:= poScreenCenter; OnKeyPress:= @FormKeyPress OnClick:= @Label1Click; OnClose:= @closeForm; Show;

    end

    UEB: 15_pas_designbycontract.txt

  • 7/31/2019 Closures & Functional Programing

    17/41

    17/41

    Closure as Parameter Consider the difference

    def managers(emps) return emps.select {|e| e.isManager}

    endSelect is a method defined on the Ruby collection class. It takes ablock of code, a closure, as an argument.

    In C or Pascal you think as a function pointer In Java as an anonymous inner class

    In Delphi or C# you would consider a delegate.

  • 7/31/2019 Closures & Functional Programing

    18/41

    18/41

    Function ConclusionStep to Closure Callback

    A block of code plus the bindings to theenvironment they came from.

    This is the formal thing that setsclosures apart from function pointers

    and similar techniques.UEB: 14_pas_primetest.txt

  • 7/31/2019 Closures & Functional Programing

    19/41

    19/41

    Closure as Object When a function is written enclosed in another

    function, it has full access to local variables from theenclosing function; this feature is called lexical scoping.

    Evaluating a closure expression produces a closure

    object as a reference.

    The closure object can later be invoked, which resultsin execution of the body, yielding the value of theexpression (if one was present) to the invoker.

  • 7/31/2019 Closures & Functional Programing

    20/41

    20/41

    Closure as Callback function AlertThisLater(message, timeout)

    {function fn() { alert(message); }window.setTimeout(fn, timeout);

    }AlertThisLater("Hi, JScript", 3000);

    A closure is created containing the message parameter, fn isexecuted quite some time after the call to AlertThisLater hasreturned, yet fn still has access to the original content of message!

  • 7/31/2019 Closures & Functional Programing

    21/41

    21/41

    Closure SEQ

  • 7/31/2019 Closures & Functional Programing

    22/41

    22/41

    Closure as Threadgroovy> Thread.start { ('A'..'Z').each {sleep 100;

    println it} }groovy> Thread.start { (1..26).each {sleep 100;

    println it} }

    >>> A>>> 1

    >>> B>>> 2

  • 7/31/2019 Closures & Functional Programing

    23/41

    23/41

    Lambda Expression There are three main parts of a function.

    1. The parameter list2. The return type

    3. The method body

    A Lambda expression is just a shorthandexpression of these three elements.

    // C#

    string s => Int.Parse(s)

  • 7/31/2019 Closures & Functional Programing

    24/41

    24/41

    Closure SyntaxWe should keep 3 things in mind:

    The ability to bind to local variables is partof that, but I think the biggest reason isthat the notation to use them is simple

    and clear.Java's anonymous inner classes can

    access locals - but only if they are final.

  • 7/31/2019 Closures & Functional Programing

    25/41

    25/41

    Syntax Schema>>> def outer(x):

    ... def inner(y):... return x+y

    ... return inner

    ... >>> customInner=outer(2)

    >>> customInner(3) result: 5

  • 7/31/2019 Closures & Functional Programing

    26/41

    26/41

    Lets practice 1

    11

    21

    1211

    111221 312211

    ???

    Try to find the next pattern, look for a rule orlogic behind !

  • 7/31/2019 Closures & Functional Programing

    27/41

    27/41

    Before C.

    function runString(Vshow: string): string;var i: byte;Rword, tmpStr: string;

    cntr, nCount: integer;begincntr:=1; nCount:=0;Rword:=''; //initializetmpStr:=Vshow; // input last result

    for i:= 1 to length(tmpStr) do beginif i= length(tmpstr) then beginif (tmpStr[i-1]=tmpStr[i]) then cntr:= cntr +1;if cntr = 1 then nCount:= cntrRword:= Rword + intToStr(ncount) + tmpStr[i]

    end else

    if (tmpStr[i]=tmpStr[i+1]) then begincntr:= cntr +1;nCount:= cntr;

    end else beginif cntr = 1 then cntr:=1 else cntr:=1; //reinit counter!

    Rword:= Rword + intToStr(ncount) + tmpStr[i] //+ last char(tmpStr)end;end; // end for loopresult:=Rword;end;

    UEB: 9_pas_umlrunner.txt

  • 7/31/2019 Closures & Functional Programing

    28/41

    28/41

    After C.function charCounter(instr: string): string;var i, cntr: integer;

    Rword: string;begincntr:= 1;

    Rword:=' ';for i:= 1 to length(instr) do begin

    //last number in lineif i= length(instr) thenconcatChars()

    elseif (instr[i]=instr[i+1]) then cntr:= cntr +1else begin

    concatChars()//reinit counter!cntr:= 1;

    end;end; //for

    result:= Rword;end; UEB: 009_pas_umlrunner_solution_2step.txt

  • 7/31/2019 Closures & Functional Programing

    29/41

    29/41

    Top 7 to avoid with Closures1. Duplicated or Dead Code2. Long Method3. Large Class (Too many responsibilities)4. Long Parameter List (Object or closure is missing)5. Shotgun Surgery (Little changes distributed over

    too many objects or procedures patternsmissed)

    6. Data Clumps (Data always together (x,y -> point))

    7. Middle Man (Class with too many delegatingmethods)

  • 7/31/2019 Closures & Functional Programing

    30/41

    30/41

    Closure Advantage Wecan avoid:

    Bad Naming (no naming convention)

    Duplicated Code (side effects)Long Methods (to much code)

    Temporary Fields (confusion)

    Long Parameter List (Object is missing)Data Classes (no methods)

    Large Class

    Class with too many delegating methods

    Coupled classes UEB: 33_pas_cipher_file_1.txt

  • 7/31/2019 Closures & Functional Programing

    31/41

    31/41

    Refactoring Closure

    Delete a class with referenceSafe DeleteModel

    Getter- und Setter einbauenEncapsulate FieldsClass

    Ersetze vererbte Methoden durch Delegationin innere KlasseReplace Inheritance withDelegationComponent

    Erzeuge Referenzen auf Klasse mitReferenz auf implementierte Schnittstelle

    Use InterfaceInterface

    Aus Methoden ein Interface erzeugenExtract InterfaceInterface

    Extract a Codepassage or define a ClosureExtract MethodClass

    Ersetzen eines Ausdrucks durch einenMethodenparameter

    Introduce ParameterClass

    Aus Methoden, Eigenschaften eineOberklasse erzeugen und verwenden

    Extract SuperclassClass

    Verschieben eines PackagesMove PackagePackage

    Umbenennen eines PackagesRename PackagePackage

    DescriptionRefactoring FunctionUnit

  • 7/31/2019 Closures & Functional Programing

    32/41

    32/41

    Case Study: The Polygraph Design Case Study PolypAn easy one states that only one statement should exists for every source

    line, like next and put a Var lifetime as short as possible.

    Can you read (Yes-No)?if YES then OK

    if NO then you are a Liar!

    var Rec: TMyRec;begin ..

    with Rec do begin.. title:= Hello Implikation';

    end;end;

  • 7/31/2019 Closures & Functional Programing

    33/41

    33/41

    Polyp Design

    Dependency Inversion

  • 7/31/2019 Closures & Functional Programing

    34/41

    34/41

    Polyp OptimizationsSome tips and hints to optimize your code:

    1. one statement and short var2. assert call, IfThen()3. use closure snippets

    4. naming convention5. $IF-directive6. Const instead of var parameters7. extract code from idioms

    8. comment your closure code

  • 7/31/2019 Closures & Functional Programing

    35/41

    35/41

    Polyp Packages

  • 7/31/2019 Closures & Functional Programing

    36/41

    36/41

    Polyp - Demeter konkret1. [M1] an Objekt O selbst

    Bsp.: self.initChart(vdata);

    2. [M2] an Objekte, die als Parameter in der Nachricht mvorkommenBsp.: O.acceptmemberVisitor(visitor)

    visitor.visitElementChartData;3. [M3] an Objekte, die O als Reaktion auf m erstelltBsp.: visitor:= TChartVisitor.create(cData, madata);

    4. [M4] an Objekte, auf die O direkt mit einem Member

    zugreifen kannBsp.: O.Ctnr:= visitor.TotalStatistic

  • 7/31/2019 Closures & Functional Programing

    37/41

    37/41

    Polyp Demeter Test as SEQ

    UEB: 56_pas_demeter.txt

  • 7/31/2019 Closures & Functional Programing

    38/41

    38/41

    Polyp GUI Optimization

    function digitButton (digit)

    return Button { label = digit,

    action = function ()

    add_to_display(digit)

    end}

    end

    Each button has a callback function to be called when the user

    presses the button; Closures are useful for callback functions, too.

  • 7/31/2019 Closures & Functional Programing

    39/41

    39/41

    Final - $Closure Test

  • 7/31/2019 Closures & Functional Programing

    40/41

    40/41

    Closure Links: http://gafter.blogspot.com/2007/01/definition-of-

    closures.html

    Michael Bolin, Closure: The Definitive Guide", O'ReillyMedia; Auflage: 1 (20. Oktober 2010).

    http://www.javac.info/

    http://sourceforge.net/projects/maxbox/

    RefactoringMartin Fowler (1999, Addison-Wesley)

    http://www.softwareschule.ch/download/closures_report.pdf

    http://www.refactoring.com

  • 7/31/2019 Closures & Functional Programing

    41/41

    41/41

    This is not The End:Q&A?

    [email protected]