Covariance - ETH Z

Covariance - ETH Z

-8- Event-Driven programming, agents & tuples 1 Our goal for this session Extend our control structures with a more flexible mechanism, supporting in particular the needs of interactive, graphical programming (GUI) The resulting mechanism, agents, has many other exciting applications Other languages have facilities such as delegates (C#), closures (functional languages) 2 Handling input through traditional techniques

Program drives user: from i := 0 read_line until end_of_file loop i := i + 1 Result [i ] := last_line read_line end 3 Handling input with modern GUIs User drives program: When a user presses this button, execute that action from my program

4 Event-driven programming: an example Specify that when a user clicks this button the system must execute find_station (x, y) where x and y are the mouse coordinates and find_station is a specific procedure of your system. CLICK START STATION ABOVE 5 Some issues 1. Keeping the business model and the GUI separate

Business model (or just model ): core functionality of the application GUI: interaction with users 2. Minimizing glue code between the two 3. Making sure we keep track of whats going on 6 Event-driven programming: a metaphor Publishers Subscribers Routine Routine Routine

Routine 7 Subject Observe rs Observing a value VIEW A = 50% B = 30% C = 20% 8

Model-View Controller (Trygve Reenskaug, 1979) 9 Our example Specify that when a user clicks this button the system must execute find_station (x, y) where x and y are the mouse coordinates and find_station is a specific procedure of your system. CLICK START STATION ABOVE

10 Alternative terminologies Observed / Observer Subject / Observer Publish / Subscribe In this presentation: Publisher and Subscriber Event-driven design/programming 11 A solution: the Observer Pattern publish +

* PUBLISHER attach detach * update SUBSCRIBER * subscribe subscribed: LIST [] + unsubscrib e+ +

PUB2 + PUB1 + SUB1 update + * Deferred (abstract) + Effective (implemented) + SUB2

update + Inherits from Client (uses) 12 Design patterns A design pattern is an architectural scheme a certain organization of classes and features that provides applications with a standardized solution to a common problem. Since 1994, various books have catalogued important patterns. Best known is Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Addison-Wesley 1994 13

A solution: the Observer Pattern publish + * PUBLISHER attach detach * update SUBSCRIBER * subscribe subscribed: LIST [] + unsubscrib e+

+ PUB1 + SUB1 update + * Deferred (abstract) + Effective (implemented) Inherits from Client (uses) 14 Observer pattern Publisher keeps a (secret) list of observers:

subscribed : LINKED_LIST [SUBSCRIBER] s1 s2 s3 s4 To register itself, an observer executes subscribe (some_publisher) where subscribe is defined in SUBSCRIBER : subscribe (p: PUBLISHER) -- Make current object observe p. do p attach (Current) end

. 15 Attaching an observer Why? In class PUBLISHER : feature {SUBSCRIBER} attach (s : SUBSCRIBER) -- Register s as subscriber to this publisher. require subscriber_exists : s /= Void do subscribed extend (s ) end .

Note that the invariant of PUBLISHER includes the clause subscribed /= Void (List subscribed is created by creation procedures of PUBLISHER) 16 Triggering an event attach detac h publish + publish -- Ask all observers to -- react to current event. do

from . . . . subscribed start until subscribed after loop subscribed item updat e subscribed forth end end *

PUBLISHER subscribed * SUBSCRIBER update* + PUB1 + SUB1 update+ Dynamic binding .

subscrib ed Each descendant of OBSERVER defines its own version of update s1 s2 s3 s4 after item sub Cursor

forth 17 Observer pattern (in basic form) Publishers know about subscribers Handling arguments is messy Not reusable must be coded anew for each application 18 Another approach: event-context-action table Set of triples [Event type, Context, Action] Event type: any kind of event we track Example: left mouse click

Context: object for which these events are interesting Example: a particular button Action: what we want to do when an event occurs in the context Example: save the file Event-context-action table may be implemented as e.g. a hash table 19 Event-context-action table More precisely: Event_type Action Table More precisely: Event_type - Context Action Table Event type Context Action

Left_click Save_butt on Cancel_butt on Map Save_file Left_click Left_click Left_click Right_click

Reset Find_stati on Display_Me nu 20 Event-action-context table Set of triples [Event, Context, Action] CLICK START STATION ABOVE Event: any occurrence we track Example: a left click

Context: object for which the event is interesting Example: the map widget Action: what we want to do when the event occurs in context Example: find the station closest to coordinates Action-event table may have various implementations, e.g. hash table. 21 In EiffelVision CLICK START STATION ABOVE Paris_map.click.action_list.extend (agent find_station) 22

Mechanisms in other languages C and C++: function pointers C#: delegates (more limited form of agents) 23 Language note In non-O-O languages, e.g. C and Matlab, there is no notion of agent, but you can pass a routine as argument to another routine, as in integral (& f, a, b) where f is the function to integrate. & f (C notation, one among many possible ones) is a way to refer to the function f. (We need some such syntax because just `f could be a function call.) Agents (or delegates in C#) provide a higher-level, more abstract and safer technique by wrapping the routine into an object with all the associated properties.

24 A little language quiz What does this do? f : INTEGER do Result := g (f ) end g (x : INTEGER ): INTEGER do Result := x end 25 Using the Eiffel Event Library Event: each event type will be an object Example: left click Context: an object, usually

representing a user interface element Example: the map Action: an agent representing a routine Example: find_station 26 The Event library Basis: One generic class: ACTION_SEQUENCE Two features: put and call For example: A map widget Paris_map that reacts in a way defined in find_station when clicked (event left_click):

27 Example using the Event library The publisher (subject) creates an action sequence object: left_click : ACTION_SEQUENCE [TUPLE [INTEGER, INTEGER]] -- Left mouse click events once create Result ensure exists: Result /= Void end The publisher triggers the event: find_station (x: INTEGER; y: INTEGER) .

left_click call ([x_positition, y_position]) The subscribers (observers) subscribe to events: . . Paris_map left_click put (agent find_station) 28 Observer pattern vs. Event Library In case of an existing class MY_CLASS : With the Observer pattern: Need to write a descendant of SUBSCRIBER and MY_CLASS Useless multiplication of classes

With the Event Library: Can reuse the existing routines directly as agents 29 Subscriber variants click.put (agent find_station) . Paris_map click put (agent find_station) . click.put (agentyour_procedure (a, ?, )?, b)

click.put (agent other_object.other_procedure ) 30 Tuples Tuple types (for any types A, B, C, ... ): TUPLE TUPLE [A] TUPLE [A, B] TUPLE [A, B, C ] ... A tuple of type TUPLE [A, B, C ] is a sequence of at least three values, first of type A, second of type B, third of type C. Tuple values: e.g. [a1, b1, c1, d1] 31 Tuple type inheritance

TUPLE TUPLE [A ] TUPLE [A, B ] 32 Labeled tuple types TUPLE [author : STRING ; year : INTEGER ; title : STRING] Restricted form of class A labeled tuple type denotes the the same type as unlabeled form, here TUPLE [STRING , INTEGER , STRING] but facilitates access to individual elements To denote a particular tuple (labeled or not): [Tolstoy, 1865, War and Peace ]

. To access tuple elements: use e.g. t year 33 What you can do with an agent a Call the associated routine through the feature whose argument is a single tuple: call , A manifest tuple . a call ( [horizontal_position, vertical_position] ) .

If a is associated with a function, a item ([ ..., ...]) gives the result of applying the function. 34 Tuples: Procedures vs. Functions Features applicable to an agent a: . If a represents a procedure, a call ([argument_tuple]) calls the procedure .

If a represents a function, a item ([argument_tuple]) calls the function and returns its result 35 Example using the Event library The publisher (subject) creates an action sequence object: left_click : ACTION_SEQUENCE [TUPLE [INTEGER, INTEGER]] -- Left mouse click events once create Result ensure exists: Result /= Void end The publisher triggers the event:

. left_click publish ([x_positition, y_position]) The subscribers (observers) subscribe to events: . . Paris_map left_click subscribe (agent find_station) 36 What you can do with an agent a Call the associated routine through the feature whose argument is a single tuple: call , A manifest tuple

. a call ( [horizontal_position, vertical_position] ) . If a is associated with a function, a item ([ ..., ...]) gives the result of applying the function. 37 Keeping arguments open An agent can have both closed and open arguments Closed arguments set at time of agent definition; open arguments set at time of each call. To keep an argument open, just replace it by a question mark: u := agent a0.f (a1, a2, a3) -- All closed (as before) w := agent a0.f (a1, a2, ? )

x := agent a0.f (a1, ? , a3) y := agent a0.f (a1, ?, ? ) z := agent a0.f (?, ?, ? ) 38 Calling the agent f (x1 : T1 ; x2 : T2 ; x3 : T3) a0 : C ; a1 : T1 ; a2 : T2 ; a3 : T3 u := agent a0.f (a1, a2, a3) u.call ([]) v := agent a0.f (a1, a2, ?) v.call ([a3]) w := agent a0.f (a1, ? , a3)

w.call ([a2]) x := agent a0.f (a1, ?, ?) x.call ([a2, a3]) y := agent a0.f (?, ?, ?) y.call ([a1, a2, a3]) 39 Another example of using agents b my_function (x ) dx a b

your_function (x, u, v ) dx a . my_integrator.integral (agent your_function ( ? , u, v ), a, b) my_integrator integral ( agent my_function , a, b) 40 The integration function integral (ff : FUNCTION [ANY, TUPLE [REAL], REAL]; a, b : REAL): REAL -- Integral of f over interval [a, b] local x: REAL; i: INTEGER do

step from x := a until x > b loop Result := Result +ff item item ([x]) ([x]) i := i + 1 x := a + i step . a b end

end 41 Another application: using an iterator class C feature all_positive, all_married: BOOLEAN is_positive (n : INTEGER) : BOOLEAN -- Is n greater than zero? do Result := (n > 0) end class class EMPLOYEE EMPLOYEE feature feature is_married is_married :: BOOLEAN BOOLEAN intlist : LIST [INTEGER]

emplist : LIST [EMPLOYEE] end end r do . all_positive := intlist for_all (agent is_positive (?) ) all_married is_married ) end end := .

emplist for_all (agent {EMPLOYEE} 42 Reminder: using inline agents intlist.for_all (agent (x : INTEGER): BOOLEAN do Result := (x > 0) end) 43 Iterators

In class LINEAR [G ], ancestor to all classes for lists, sequences etc., you will find: for_all there_exists do_all do_if do_while do_until 44 Applications of agents Patterns: Observer, Visitor, Undo-redo (command) Iteration High-level contracts Numerical programming Introspection (finding out properties of the program itself)

45 Kernel library classes representing agents call + PROCEDURE * ROUTINE + FUNCTION last_result item + PREDICATE

46 Declaring an agent p: PROCEDURE [ANY, TUPLE] -- Agent representing a procedure, -- no open arguments q: PROCEDURE [ANY, TUPLE [X, Y, Z]] -- Agent representing a procedure, -- 3 open arguments f: FUNCTION [ANY, TUPLE [X, Y, Z], RES ] -- Agent representing a procedure, -- 3 open arguments, result of type RES 47 Calling an agent f (x1 : T1 ; x2 : T2 ; x3 : T3) a0 : C ; a1 : T1 ; a2 : T2 ; a3 : T3

u := agent a0.f (a1, a2, a3) u.call ([]) v := agent a0.f (a1, a2, ?) v.call ([a3]) w := agent a0.f (a1, ? , a3) w.call ([a2]) x := agent a0.f (a1, ?, ?) x.call ([a2, a3]) y := agent a0.f (?, ?, ?) y.call ([a1, a2, a3])

48 Agents: summary and conclusion Treat routines (computation) as objects An indispensable complement to basic O-O mechanisms 49

Recently Viewed Presentations

  • Personal Property Basics - IN.gov

    Personal Property Basics - IN.gov

    (5) mobile homes that do not qualify as real property and are not described as "all other tangible property (other than real property)" above [addition in bold effective January 1, 2009 by HEA 1125, Section 2].
  • Database Principles - University of Kentucky

    Database Principles - University of Kentucky

    The simplest unit in a database is a field. It is the smallest meaningful unit. It can be any size from 1 character to hundreds of characters. It has a name, like "First Name" or "State" It has a type,...
  • How to Get Started with the paper Tucker

    How to Get Started with the paper Tucker

    Quote. Albert Einstein once said, "To raise new questions, new possibilities, to regard old problems from a new angle, requires creative imagination and marks real advance in science." ... "Twelfth Night is the most nearly perfect festive comedy that Shakespeare...
  • Congress of Student Organizations (CSO) - NDSU

    Congress of Student Organizations (CSO) - NDSU

    Tier 2 Organizations with a CSO status 3 and up are able to get budgets. ... You will then receive a reply with a link that you need to click on and schedule yourself for a time to meet with...
  • INTRODUCTION TO INVESTING - Mrs. Besthoff

    INTRODUCTION TO INVESTING - Mrs. Besthoff

    INTRODUCTION TO INVESTING ... Savings tools are on the first level of the financial risk pyramid, because they are free of the risk of losing the amount of principal invested. However, the trade‐off is receiving lower return on the money...
  • Course Introduction - California State University, Los Angeles

    Course Introduction - California State University, Los Angeles

    Course Introduction Chart A Use when individuals cannot be claimed as dependents on another taxpayer's return Chart B For children and other dependents Chart C Other situations for filing Gross Income Is all the income the taxpayer received during the...
  • Economics and Law - University of Cambridge

    Economics and Law - University of Cambridge

    Economics and Law CST part 1b Ross Anderson, Richard Clayton Philosophies of ethics Authority theories mostly derive from religion. But God usually talks via scriptures or a priesthood; so how do you resolve disputes?
  • Parent & Athlete Meeting

    Parent & Athlete Meeting

    The Spartans have a highly successful booster organization which promote school spirit and pride. The PTSO can help raise money to support transportation costs, replace or upgrade equipment, provide awards/recognition, provide desserts for banquet and other needs that may arise...