• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Boost your-oop-with-fp
 

Boost your-oop-with-fp

on

  • 2,974 views

 

Statistics

Views

Total Views
2,974
Views on SlideShare
2,885
Embed Views
89

Actions

Likes
10
Downloads
35
Comments
3

8 Embeds 89

http://local.host 37
http://presentz.org 35
http://a0.twimg.com 8
https://www.linkedin.com 3
http://localhost 2
http://dev.presentz.org 2
http://iad11.presentz.org 1
http://www.linkedin.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

13 of 3 previous next Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Boost your-oop-with-fp Boost your-oop-with-fp Presentation Transcript

    • How to boost your OOP with FP Uberto Barbini @ramtopSaturday, November 19, 11
    • About me Uberto Barbini Software artisan Agile enthusiast. Hobby: photography and the game of Go. http://www.flickr.com/photos/uberto Team leader and Architect for Vodafone editorial and backend products.Saturday, November 19, 11
    • What if OOP was wrong? http://www.flickr.com/photos/mbshaneSaturday, November 19, 11
    • What if OOP was wrong? OOP is only a tool, we need to keep it sharp we need to learn other tools http://www.flickr.com/photos/mbshaneSaturday, November 19, 11
    • What if OOP was wrong? OOP is only a tool, we need to keep it sharp we need to learn other tools Caution, this presentation can http://www.flickr.com/photos/mbshane contain trace of PhilosophySaturday, November 19, 11
    • I would like to pay my tribute to for their contribution to Software Engineering growing-object-oriented-software@googlegroups.comSaturday, November 19, 11
    • Bugs http://www.flickr.com/photos/staflo/Saturday, November 19, 11
    • Bugs • cause of delays and frustration • many are easy to fix • some cause big problems • the worst ones are caused by... http://www.flickr.com/photos/staflo/Saturday, November 19, 11
    • State • Foundation of behavior • Hidden from outside • Should be defended like a castleSaturday, November 19, 11
    • Where is the state? Easy to understand what it does. Hard to understand why it does it. http://fractalforge.cvs.sourceforge.net/viewvc/fractalforge/fractalforge/Mandelbrot.pas?view=markupSaturday, November 19, 11
    • The new procedural public class NameAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String target = new String("success"); if (form != null) { // Use the NameForm to get the request parameters NameForm nameForm = (NameForm) form; String name = nameForm.getName(); } // if no mane supplied Set the target to failure if (name == null) { target = new String("failure"); } else { request.setAttribute("NAME", name); } return (mapping.findForward(target)); } }Saturday, November 19, 11
    • The new procedural public class NameAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String target = new String("success"); if (form != null) { // Use the NameForm to get the request parameters NameForm nameForm = (NameForm) form; String name = nameForm.getName(); } // if no mane supplied Set the target to failure if (name == null) { target = new String("failure"); } else { request.setAttribute("NAME", name); } return (mapping.findForward(target)); } } Frameworks make easy to keep writing procedural code in OO fashionSaturday, November 19, 11
    • Procedural paradigmSaturday, November 19, 11
    • Procedural paradigmSaturday, November 19, 11
    • Procedural paradigm • Easy to write • Hard to understand • Global stateSaturday, November 19, 11
    • http://www.flickr.com/photos/hatmSaturday, November 19, 11
    • Recipe: “We are pragmatic about code quality” http://www.flickr.com/photos/hatmSaturday, November 19, 11
    • Saturday, November 19, 11
    • John McCarthySaturday, November 19, 11
    • John McCarthy • LISt Processing aka Lots of Irritating Superfluous Parenthesis • S-Expressions func(x,y) => (func, x, y) • Homoiconic (metaprogramming++) • Laziness parameter evaluationSaturday, November 19, 11
    • Homoiconic John “Clojure macro example: AND” (defmacro and ([] true) McCarthy ([x] x) ([x & rest] • LISt Processing `(let [and# ~x] aka Lots of Irritating Superfluous Parenthesis (if and# (and ~@rest) and#)))) • S-Expressions func(x,y) => (func, x, y) • Homoiconic (metaprogramming++) • Laziness parameter evaluationSaturday, November 19, 11
    • Clojure the modern Lisp (ns bowling-game (:use clojure.contrib.seq-utils)) (defn strike? [rolls] (= 10 (first rolls))) (defn spare? [rolls] (= 10 (apply + (take 2 rolls)))) (defn balls-to-score "How many balls contribute to this frames score?" [rolls] (cond (strike? rolls) 3 (spare? rolls) 3 :else 2)) (defn frame-advance "How many rolls should be consumed to advance to the next frame?" [rolls] (if (strike? rolls) 1 2)) (defn frames "Converts a sequence of rolls to a sequence of frames" [rolls] (when-let [rolls (seq rolls)] (lazy-seq (cons (take (balls-to-score rolls) rolls) (frames (drop (frame-advance rolls) rolls)))))) (defn score-frame [frame] (reduce + frame)) (defn score-game "Score a bowling game, passed as a sequence of rolls." [rolls] (reduce + (map score-frame (take 10 (frames rolls)))))Saturday, November 19, 11
    • Saturday, November 19, 11
    • Alan KaySaturday, November 19, 11
    • Alan Kay • The best way to predict the future is to invent it. • Possibly the only real object-oriented system in working order. (About Internet) • The greatest single programming language ever designed. (About Lisp programming language)Saturday, November 19, 11
    • bonusFrame ^self spare or: [self strike] Smalltalkstrike ^self roll1 = 10 an elegantspare ^self roll1 < 10 and: [ self roll1 + self roll2 = 10]. weaponroll1 ^rolls at: frameStart for a moreroll2 ^rolls at: frameStart + 1 civilizedroll3 ^rolls at: frameStart + 2 ageframeScore | frameScore | frameScore := self roll1 + self roll2. self bonusFrame ifTrue: [ frameScore := frameScore + self roll3 ]. ^frameScoreupdateFrameStart self strike ifTrue: [ frameStart := frameStart + 1] ifFalse: [ frameStart := frameStart + 2]score 10 timesRepeat: [score := score + self frameScore. self updateFrameStart]. ^scoreinitialize rolls := OrderedCollection new. score := 0. frameStart := 1. ^selfSaturday, November 19, 11
    • bonusFrame ^self spare or: [self strike] Smalltalkstrike ^self roll1 = 10 an elegantspare ^self roll1 < 10 and: [ self roll1 + self roll2 = 10]. weaponroll1 ^rolls at: frameStart for a moreroll2 ^rolls at: frameStart + 1 civilizedroll3 ^rolls at: frameStart + 2 ageframeScore | frameScore | frameScore := self roll1 + self roll2. self bonusFrame ifTrue: [ frameScore := frameScore + self roll3 ]. ^frameScoreupdateFrameStart self strike ifTrue: [ frameStart := frameStart + 1] ifFalse: [ frameStart := frameStart + 2]score 10 timesRepeat: [score := score + self frameScore. self updateFrameStart]. ^scoreinitialize rolls := OrderedCollection new. score := 0. frameStart := 1. ^selfSaturday, November 19, 11
    • What is OOP? Basically, an object type looks like a record type with additional fields including procedure fields and also optional keywords which indicate the scope of the fields.Saturday, November 19, 11
    • What is OOP? Basically, an object type looks like a record type with additional fields including procedure fields and also optional keywords which indicate the scope of the fields. Lazarus (Object Pascal) wikiSaturday, November 19, 11
    • What is OOP? Object-oriented programming (OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance.Saturday, November 19, 11
    • Edsger W. DijkstraSaturday, November 19, 11
    • Edsger W. Dijkstra It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration. - 1975Saturday, November 19, 11
    • Edsger W. DijkstraSaturday, November 19, 11
    • Edsger W. Dijkstra Object-oriented programming is an exceptionally bad idea which could only have originated in California.Saturday, November 19, 11
    • Edsger W. Dijkstra Object-oriented programming is an exceptionally bad idea which could only have originated in California. I dont know how many of you have ever met Dijkstra, but you probably know that arrogance in computer science is measured in nano-Dijkstras. Alan Kay.Saturday, November 19, 11
    • Alan Kay OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late- binding of all things. It can be done in Smalltalk and in LISP. There are possibly other systems in which this is possible, but Im not aware of them. (email 23/07/2003) http://www.flickr.com/photos/marcospillerSaturday, November 19, 11
    • Alan Kay OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late- binding of all things. It can be done in Smalltalk and in LISP. There are possibly other systems in which this is possible, but Im not aware of them. (email 23/07/2003) I thought of objects being like biological cells and/or individual computers on a network, only able to communicate with messages (so messaging came at the very beginning -- it took a while to see how to do messaging in a programming language efficiently enough to be useful). http://www.flickr.com/photos/marcospillerSaturday, November 19, 11
    •   The venerable master Qc Na was walking with his student, Anton.  Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?"  Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor mans closures."   Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures.  He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system.  He learned much, and looked forward to informing his master of his progress.   On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor mans closures."  Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor mans  object."  At that moment, Anton became enlightened.Saturday, November 19, 11
    •   The venerable master Qc Na was walking with his student, Anton.  Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?"  Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor mans closures."   Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures.  He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system.  He learned much, and looked forward to informing his master of his progress.   On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor mans closures."  Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor mans  object."  At that moment, Anton became enlightened. Anton van Straaten 4 June 2003Saturday, November 19, 11
    • Saturday, November 19, 11
    • Yun Tung Lao - The Art of Objects - Addison WesleySaturday, November 19, 11
    • Bruce Eckel - Thinking in Java The object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space. This representation is general enough that the programmer is not constrained to any particular type of problem. We refer to the elements in the problem space and their representations in the solution space as “objects.” (You will also need other objects that don’t have problem-space analogs.) The idea is that the program is allowed to adapt itself to the lingo of the problem by adding new types of objects, so when you read the code describing the solution, you’re reading words that also express the problem. This is a more flexible and powerful language abstraction than what we’ve had before. Thus, OOP allows you to describe the problem in terms of the problem, rather than in terms of the computer where the solution will run.Saturday, November 19, 11
    • An object has state, behavior, and identity - Grady BoochSaturday, November 19, 11
    • An object has state, behavior, and identity - Grady Booch OOP fundamentals: Ignorance Apathy Selfishness Kevlin Henney (Will The Real Oop Please Stand Up)Saturday, November 19, 11
    • Half presentation check Summary so far: 1. The worst bugs are related to state 2. Procedural paradigm doesn’t care much 3. Functional paradigm expel state from functions 4. OOP (the real one) encapsule state in ObjectsSaturday, November 19, 11
    • Do I smell spaghetti?Saturday, November 19, 11
    • Saturday, November 19, 11
    • Why singleton?Saturday, November 19, 11
    • Why singleton? Strategy without DI is pointlessSaturday, November 19, 11
    • Why singleton? Strategy without DI is pointless This is worse than procedural!Saturday, November 19, 11
    • the real problem is that many Why singleton? people believe this is Strategy without DIOOP good is pointless because there are many objects, interfaces, patterns. This is worse than procedural!Saturday, November 19, 11
    • DDD Eric Evans • Many objects are not fundamentally defined by their attributes but rather by a thread of continuity and identity An object defined primarily by its identity is called an ENTITY. p.91 • When you care only about the attributes of an element of the model, classify it as a value object. Threat the VALUE OBJECT as immutable. Don’t give it any identity and avoid the design complexities necessary to maintain ENTITIES. p.97 • Place as much of the logic of the program as possible in functions, operation that returns results with no observable side effects. p. 251Saturday, November 19, 11
    • The most significant part of the full citation is as follows: computational linguistics. Fortran remains one of the most . . . Backus headed a small IBM group in New York City widely used programming languages in the world. Almost all during the early 1950s. The earliest product of this groups programming languages are now described with some type of efforts was a high-level language for scientific and technical corn- formal syntactic definition. " Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs John Backus IBM Research Laboratory, San Jose Conventional programming languages are growing ever more enormous, but not stronger. Inherent defects at the most basic level cause them to be both fat and weak: their primitive word-at-a-time style of program- ming inherited from their common ancestor--the von Neumann computer, their close coupling of semantics to state transitions, their division of programming into a world of expressions and a world of statements, their inability to effectively use powerful combining forms for building new programs from existing ones, and their lack of useful mathematical properties for reasoning about programs. An alternative functional style of programming is General permission to make fair use in teaching or research of all founded on the use of combining forms for creating or part of this material is granted to individual readers and to nonprofit libraries acting for them provided that ACMs copyright notice is given programs. Functional programs deal with structured and that reference is made to the publication, to its date of issue, and data, are often nonrepetitive and nonrecursive, are hier- to the fact that reprinting privileges were granted by permission of the archically constructed, do not name their arguments, and Association for Computing Machinery. To otherwise reprint a figure, table, other substantial excerpt, or the entire work requires specific do not require the complex machinery of procedure permission as does republication, or systematic or multiple reproduc- declarations to become generally applicable. Combining tion. forms can use high level programs to build still higher Authors address: 91 Saint Germain Ave., San Francisco, CA 94114. level ones in a style not possible in conventional lan- © 1978 ACM 0001-0782/78/0800-0613 $00.75 guages. 613 Communications August 1978 of Volume 2 i the ACM Number 8Saturday, November 19, 11
    • Mark Needham I’m beginning to think that the combination of functional and object oriented programming actually results in code which I think is more expressive and easy to work with than code written only with an object oriented approach in mind. The functional mindset seems to be more about considering the problem as a whole and then working out how we can simplify that problem from the outside in which is a bit of a paradigm shift. I don’t think I’ve completely made but it can certainly lead to solutions which are much easier to understand. - blog April 2009Saturday, November 19, 11
    • http://www.flickr.com/photos/dirtyfSaturday, November 19, 11
    • The Functional eye http://www.flickr.com/photos/dirtyfSaturday, November 19, 11
    • The Functional eye • Immutable structured values (messages) • Never unready or null objects (a keyword) • Use of pure functions (no side effect) • Closures to decouple (or inner classes) http://www.flickr.com/photos/dirtyfSaturday, November 19, 11
    • Saturday, November 19, 11
    • The ObjectOriented eyeSaturday, November 19, 11
    • The ObjectOriented eye • Dependency Injection • No getters for mutable state • Interfaces for collaborators (Liskov) • Simpler aggregates (Demeter) • Meaningful name conventionSaturday, November 19, 11
    • Just an example: protected void processRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { log.info("Processing request " + httpServletRequest.getRequestURI()); HttpCallClock clock = new HttpCallClock(); MyRequest request = createRequest(httpServletRequest); MyResponse response = prepareResponse(getContentService(), request); translateResponse(response, httpServletResponse); long elapsed = clock.getElapsedTime(); log.info("Processed in " + elapsed + " ms. " + httpServletRequest.getRequestURI()); accessLog.info(AccessLog.getRequestLog(httpServletRequest, elapsed, response.getStatus(), response.getResponseContentLength())); }Saturday, November 19, 11
    • Another example: protected MyResponse prepareResponse(MyRequestConfiguration myConfiguration) { String opco = myConfiguration.getOpco(); Device device = VIRTUAL_DEVICE; if (myConfiguration.isTacPresent()) { DeviceResponse devicesResponse = getDeviceResponse(opco, myConfiguration.getPublishType()); if (devicesResponse.isErrorResponse()) { return new ResponseWithError(devicesResponse.getHttpStatusCode(), devicesResponse.getMessage()); } if (!devicesResponse.isDevicePresentByTac(myConfiguration.getTac())) { return new ResponseWithError(SC_NOT_FOUND, "device with tac code: " + myConfiguration.getTac() + " not found"); } device = devicesResponse.getDeviceByTac(); } DatastoreResponse responseFromDatastore = getDashboards(device, myConfiguration.getPublishType(), opco); if (responseFromDatastore.isErrorResponse()) { return new ResponseWithError(responseFromDatastore.getHttpStatusCode(), responseFromDatastore.getMessage()); } return retrieveResponseAccordingUrl(myConfiguration, responseFromDatastore.getDashboards()); }Saturday, November 19, 11
    • Object Design Rebecca Wirfs-Brock Control • Centralized • Dispersed • DelegatedSaturday, November 19, 11
    • Centralized Invoice Customer Invoice Printer ManagerSaturday, November 19, 11
    • Centralized Invoice Customer Invoice Martin Fowler: (http://martinfowler.com/bliki/ AnemicDomainModel.html) The basic symptom of an Anemic Domain Model is that Printer at first blush it looks like the real thing. [...] The catch Manager comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters.  [...] The key point here is that the Service Layer is thin - all the key logic lies in the domain layer.Saturday, November 19, 11
    • Dispersed Customer Items Invoice Printer Popular with Zombie objects (aka Hibernated beans)Saturday, November 19, 11
    • Logic Delegated Entity Identity CustomerFetcher Value InvoiceFetcher Immutable Customer No Id Invoice Printer InvoicePrinterSaturday, November 19, 11
    • The valley of comfort http://www.flickr.com/photos/lviggianoSaturday, November 19, 11
    • The valley Elegance and familiarity are orthogonal of comfort Rich Hickey on #Clojure http://www.flickr.com/photos/lviggianoSaturday, November 19, 11
    • The valley Elegance and familiarity are orthogonal of comfort Rich Hickey on #Clojure A Conversation with Ward Cunningham, Part III (5 January 2004) The Accidental Architecture I like the notion of working the program, like an artist works a lump of clay. An artist wants to make a sculpture, but before she makes the sculpture, she just massages the clay. [...] In a sense we get the architecture without really trying. All the decisions in the context of the other decisions simply gel into an architecture. http://www.flickr.com/photos/lviggianoSaturday, November 19, 11
    • The valley Elegance and familiarity are orthogonal of comfort Rich Hickey on #Clojure There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so A Conversation with Ward Cunningham, Part III (5 January 2004) complicated that there are no obvious deficiencies. The Accidental Architecture [C.A.R. Hoare] I like the notion of working the program, like an artist works a lump of clay. An artist wants to make a sculpture, but before she makes the sculpture, she just massages the clay. [...] In a sense we get the architecture without really trying. All the decisions in the context of the other decisions simply gel into an architecture. http://www.flickr.com/photos/lviggianoSaturday, November 19, 11
    • The journey to the valley • What about domain • What about tests • What about mocks • What about refactoring http://www.flickr.com/photos/bobcatnorthSaturday, November 19, 11
    • Open questions • Do we need a yet another new language? • Can we have Architects? • How to teach design?Saturday, November 19, 11