SlideShare a Scribd company logo
How to boost your
                              OOP with FP
                                 Uberto Barbini
                                   @ramtop




Saturday, 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/mbshane




Saturday, 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/mbshane




Saturday, 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 Philosophy
Saturday, November 19, 11
I would like to
                pay my tribute to




    for their contribution to
     Software Engineering
                            growing-object-oriented-software@googlegroups.com
Saturday, 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 castle



Saturday, 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=markup

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));
        }
 }




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 fashion
Saturday, November 19, 11
Procedural paradigm




Saturday, November 19, 11
Procedural paradigm




Saturday, November 19, 11
Procedural paradigm



                                     • Easy to write
                                     • Hard to understand
                                     • Global state


Saturday, November 19, 11
http://www.flickr.com/photos/hatm



Saturday, November 19, 11
Recipe:
   “We are pragmatic
   about code quality”


       http://www.flickr.com/photos/hatm



Saturday, November 19, 11
Saturday, November 19, 11
John
                            McCarthy




Saturday, 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
                              evaluation
Saturday, 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
                                                          evaluation
Saturday, 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 frame's 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 Kay




Saturday, 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]                                          Smalltalk
strike
  ^self roll1 = 10


                                                                         an elegant
spare
  ^self roll1 < 10          and:   [ self roll1 + self roll2 = 10].



                                                                          weapon
roll1
  ^rolls at: frameStart



                                                                         for a more
roll2
  ^rolls at: frameStart + 1



                                                                          civilized
roll3
  ^rolls at: frameStart + 2



                                                                             age
frameScore
    | frameScore |
    frameScore := self roll1 + self roll2.
    self bonusFrame ifTrue: [ frameScore := frameScore + self roll3 ].
    ^frameScore

updateFrameStart
    self strike
        ifTrue: [ frameStart := frameStart + 1]
        ifFalse: [ frameStart := frameStart + 2]

score
    10 timesRepeat:
        [score := score + self frameScore.
        self updateFrameStart].
    ^score

initialize
    rolls := OrderedCollection new.
    score := 0.
    frameStart := 1.
    ^self

Saturday, November 19, 11
bonusFrame
  ^self spare or: [self strike]                                          Smalltalk
strike
  ^self roll1 = 10


                                                                         an elegant
spare
  ^self roll1 < 10          and:   [ self roll1 + self roll2 = 10].



                                                                          weapon
roll1
  ^rolls at: frameStart



                                                                         for a more
roll2
  ^rolls at: frameStart + 1



                                                                          civilized
roll3
  ^rolls at: frameStart + 2



                                                                             age
frameScore
    | frameScore |
    frameScore := self roll1 + self roll2.
    self bonusFrame ifTrue: [ frameScore := frameScore + self roll3 ].
    ^frameScore

updateFrameStart
    self strike
        ifTrue: [ frameStart := frameStart + 1]
        ifFalse: [ frameStart := frameStart + 2]

score
    10 timesRepeat:
        [score := score + self frameScore.
        self updateFrameStart].
    ^score

initialize
    rolls := OrderedCollection new.
    score := 0.
    frameStart := 1.
    ^self

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.




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) wiki

Saturday, 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.
                             Dijkstra




Saturday, 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. - 1975

Saturday, November 19, 11
Edsger W.
                             Dijkstra




Saturday, 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 don't 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
             I'm not aware of them. (email 23/07/2003)




                                                                    http://www.flickr.com/photos/marcospiller


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
             I'm 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/marcospiller


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 man's
         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 man's closures."  Qc Na responded by hitting
         Anton with his stick, saying "When will you learn? Closures are a poor man's 
         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 man's
         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 man's closures."  Qc Na responded by hitting
         Anton with his stick, saying "When will you learn? Closures are a poor man's 
         object."  At that moment, Anton became enlightened.




                                             Anton van Straaten 4 June 2003


Saturday, November 19, 11
Saturday, November 19, 11
Yun Tung Lao - The Art of Objects - Addison Wesley



Saturday, 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 Booch




Saturday, 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
                               Objects

Saturday, 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 pointless




Saturday, 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. 251

Saturday, 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 group's                  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 ACM's 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
                      Author's 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 8


Saturday, 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 2009


Saturday, November 19, 11
http://www.flickr.com/photos/dirtyf


Saturday, November 19, 11
The Functional eye




      http://www.flickr.com/photos/dirtyf


Saturday, 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/dirtyf


Saturday, November 19, 11
Saturday, November 19, 11
The ObjectOriented eye




Saturday, November 19, 11
The ObjectOriented eye


                    • Dependency Injection
                    • No getters for mutable state
                    • Interfaces for collaborators (Liskov)
                    • Simpler aggregates (Demeter)
                    • Meaningful name convention
Saturday, 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
                            • Delegated

Saturday, November 19, 11
Centralized
                            Invoice
                                       Customer
        Invoice


                                                  Printer
                                  Manager



Saturday, 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
                            InvoicePrinter


Saturday, November 19, 11
The valley
                                             of comfort




     http://www.flickr.com/photos/lviggiano


Saturday, November 19, 11
The valley
                            Elegance and familiarity are orthogonal

                                             of comfort
                            Rich Hickey on #Clojure




     http://www.flickr.com/photos/lviggiano


Saturday, 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/lviggiano


Saturday, 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/lviggiano


Saturday, 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/bobcatnorth


Saturday, 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

More Related Content

Similar to Boost your-oop-with-fp

The Contextual Experience of the Mobile Web
The Contextual Experience of the Mobile WebThe Contextual Experience of the Mobile Web
The Contextual Experience of the Mobile Web
Jeff Carouth
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
Juan Maiz
 
has("builds")
has("builds")has("builds")
has("builds")
Peter Higgins
 
JS-Everywhere - LocalStorage Hands-on
JS-Everywhere - LocalStorage Hands-onJS-Everywhere - LocalStorage Hands-on
JS-Everywhere - LocalStorage Hands-on
Brice Argenson
 
De vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored proceduresDe vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored procedures
Norman Clarke
 
Javascript - How to avoid the bad parts
Javascript - How to avoid the bad partsJavascript - How to avoid the bad parts
Javascript - How to avoid the bad parts
Mikko Ohtamaa
 
Acceptance & Integration Testing With Behat (PHPNw2011)
Acceptance & Integration Testing With Behat (PHPNw2011)Acceptance & Integration Testing With Behat (PHPNw2011)
Acceptance & Integration Testing With Behat (PHPNw2011)
benwaine
 
Localizing iOS Apps
Localizing iOS AppsLocalizing iOS Apps
Localizing iOS Apps
weissazool
 
Scrum und Craftsmanship
Scrum und CraftsmanshipScrum und Craftsmanship
Scrum und Craftsmanship
Stefan ROOCK
 
Apache Hadoop Talk at QCon
Apache Hadoop Talk at QConApache Hadoop Talk at QCon
Apache Hadoop Talk at QCon
Cloudera, Inc.
 
Deconstructing Functional Programming
Deconstructing Functional ProgrammingDeconstructing Functional Programming
Deconstructing Functional Programming
C4Media
 

Similar to Boost your-oop-with-fp (11)

The Contextual Experience of the Mobile Web
The Contextual Experience of the Mobile WebThe Contextual Experience of the Mobile Web
The Contextual Experience of the Mobile Web
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 
has("builds")
has("builds")has("builds")
has("builds")
 
JS-Everywhere - LocalStorage Hands-on
JS-Everywhere - LocalStorage Hands-onJS-Everywhere - LocalStorage Hands-on
JS-Everywhere - LocalStorage Hands-on
 
De vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored proceduresDe vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored procedures
 
Javascript - How to avoid the bad parts
Javascript - How to avoid the bad partsJavascript - How to avoid the bad parts
Javascript - How to avoid the bad parts
 
Acceptance & Integration Testing With Behat (PHPNw2011)
Acceptance & Integration Testing With Behat (PHPNw2011)Acceptance & Integration Testing With Behat (PHPNw2011)
Acceptance & Integration Testing With Behat (PHPNw2011)
 
Localizing iOS Apps
Localizing iOS AppsLocalizing iOS Apps
Localizing iOS Apps
 
Scrum und Craftsmanship
Scrum und CraftsmanshipScrum und Craftsmanship
Scrum und Craftsmanship
 
Apache Hadoop Talk at QCon
Apache Hadoop Talk at QConApache Hadoop Talk at QCon
Apache Hadoop Talk at QCon
 
Deconstructing Functional Programming
Deconstructing Functional ProgrammingDeconstructing Functional Programming
Deconstructing Functional Programming
 

More from Uberto Barbini

CQRS with Event Source in Functional sauce served by Kotlin
CQRS with Event Source in Functional sauce served by Kotlin CQRS with Event Source in Functional sauce served by Kotlin
CQRS with Event Source in Functional sauce served by Kotlin
Uberto Barbini
 
Go kotlin, Go!
Go kotlin, Go!Go kotlin, Go!
Go kotlin, Go!
Uberto Barbini
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About Morphisms
Uberto Barbini
 
Legacy is Good
Legacy is GoodLegacy is Good
Legacy is Good
Uberto Barbini
 
The Role of Testing in DevOps
The Role of Testing in DevOpsThe Role of Testing in DevOps
The Role of Testing in DevOps
Uberto Barbini
 
When Tdd Goes Awry (IAD 2013)
When Tdd Goes Awry (IAD 2013)When Tdd Goes Awry (IAD 2013)
When Tdd Goes Awry (IAD 2013)
Uberto Barbini
 
When Tdd Goes Awry
When Tdd Goes AwryWhen Tdd Goes Awry
When Tdd Goes Awry
Uberto Barbini
 
The Effective Team
The Effective TeamThe Effective Team
The Effective Team
Uberto Barbini
 
Develop Gwt application in TDD
Develop Gwt application in TDDDevelop Gwt application in TDD
Develop Gwt application in TDD
Uberto Barbini
 

More from Uberto Barbini (9)

CQRS with Event Source in Functional sauce served by Kotlin
CQRS with Event Source in Functional sauce served by Kotlin CQRS with Event Source in Functional sauce served by Kotlin
CQRS with Event Source in Functional sauce served by Kotlin
 
Go kotlin, Go!
Go kotlin, Go!Go kotlin, Go!
Go kotlin, Go!
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About Morphisms
 
Legacy is Good
Legacy is GoodLegacy is Good
Legacy is Good
 
The Role of Testing in DevOps
The Role of Testing in DevOpsThe Role of Testing in DevOps
The Role of Testing in DevOps
 
When Tdd Goes Awry (IAD 2013)
When Tdd Goes Awry (IAD 2013)When Tdd Goes Awry (IAD 2013)
When Tdd Goes Awry (IAD 2013)
 
When Tdd Goes Awry
When Tdd Goes AwryWhen Tdd Goes Awry
When Tdd Goes Awry
 
The Effective Team
The Effective TeamThe Effective Team
The Effective Team
 
Develop Gwt application in TDD
Develop Gwt application in TDDDevelop Gwt application in TDD
Develop Gwt application in TDD
 

Recently uploaded

Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
Zilliz
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
Google Developer Group - Harare
 
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
alexjohnson7307
 
The Impact of the Internet of Things (IoT) on Smart Homes and Cities
The Impact of the Internet of Things (IoT) on Smart Homes and CitiesThe Impact of the Internet of Things (IoT) on Smart Homes and Cities
The Impact of the Internet of Things (IoT) on Smart Homes and Cities
Arpan Buwa
 
Zaitechno Handheld Raman Spectrometer.pdf
Zaitechno Handheld Raman Spectrometer.pdfZaitechno Handheld Raman Spectrometer.pdf
Zaitechno Handheld Raman Spectrometer.pdf
AmandaCheung15
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
Ivanti
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
SubhamMandal40
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
The History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal EmbeddingsThe History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal Embeddings
Zilliz
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
SAI KAILASH R
 
It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...
Zilliz
 
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Nicolás Lopéz
 
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Zilliz
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
ankush9927
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3
DianaGray10
 
Redefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI CapabilitiesRedefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI Capabilities
Priyanka Aash
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
FIDO Alliance
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
shanihomely
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 

Recently uploaded (20)

Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
 
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
 
The Impact of the Internet of Things (IoT) on Smart Homes and Cities
The Impact of the Internet of Things (IoT) on Smart Homes and CitiesThe Impact of the Internet of Things (IoT) on Smart Homes and Cities
The Impact of the Internet of Things (IoT) on Smart Homes and Cities
 
Zaitechno Handheld Raman Spectrometer.pdf
Zaitechno Handheld Raman Spectrometer.pdfZaitechno Handheld Raman Spectrometer.pdf
Zaitechno Handheld Raman Spectrometer.pdf
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
The History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal EmbeddingsThe History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal Embeddings
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
 
It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...
 
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024
 
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3
 
Redefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI CapabilitiesRedefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI Capabilities
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 

Boost your-oop-with-fp

  • 1. How to boost your OOP with FP Uberto Barbini @ramtop Saturday, November 19, 11
  • 2. 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
  • 3. What if OOP was wrong? http://www.flickr.com/photos/mbshane Saturday, November 19, 11
  • 4. 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/mbshane Saturday, November 19, 11
  • 5. 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 Philosophy Saturday, November 19, 11
  • 6. I would like to pay my tribute to for their contribution to Software Engineering growing-object-oriented-software@googlegroups.com Saturday, November 19, 11
  • 7. Bugs http://www.flickr.com/photos/staflo/ Saturday, November 19, 11
  • 8. 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
  • 9. State • Foundation of behavior • Hidden from outside • Should be defended like a castle Saturday, November 19, 11
  • 10. 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=markup Saturday, November 19, 11
  • 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
  • 12. 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 fashion Saturday, November 19, 11
  • 15. Procedural paradigm • Easy to write • Hard to understand • Global state Saturday, November 19, 11
  • 17. Recipe: “We are pragmatic about code quality” http://www.flickr.com/photos/hatm Saturday, November 19, 11
  • 19. John McCarthy Saturday, November 19, 11
  • 20. John McCarthy • LISt Processing aka Lots of Irritating Superfluous Parenthesis • S-Expressions func(x,y) => (func, x, y) • Homoiconic (metaprogramming++) • Laziness parameter evaluation Saturday, November 19, 11
  • 21. 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 evaluation Saturday, November 19, 11
  • 22. 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 frame's 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
  • 25. 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
  • 26. bonusFrame ^self spare or: [self strike] Smalltalk strike ^self roll1 = 10 an elegant spare ^self roll1 < 10 and: [ self roll1 + self roll2 = 10]. weapon roll1 ^rolls at: frameStart for a more roll2 ^rolls at: frameStart + 1 civilized roll3 ^rolls at: frameStart + 2 age frameScore | frameScore | frameScore := self roll1 + self roll2. self bonusFrame ifTrue: [ frameScore := frameScore + self roll3 ]. ^frameScore updateFrameStart self strike ifTrue: [ frameStart := frameStart + 1] ifFalse: [ frameStart := frameStart + 2] score 10 timesRepeat: [score := score + self frameScore. self updateFrameStart]. ^score initialize rolls := OrderedCollection new. score := 0. frameStart := 1. ^self Saturday, November 19, 11
  • 27. bonusFrame ^self spare or: [self strike] Smalltalk strike ^self roll1 = 10 an elegant spare ^self roll1 < 10 and: [ self roll1 + self roll2 = 10]. weapon roll1 ^rolls at: frameStart for a more roll2 ^rolls at: frameStart + 1 civilized roll3 ^rolls at: frameStart + 2 age frameScore | frameScore | frameScore := self roll1 + self roll2. self bonusFrame ifTrue: [ frameScore := frameScore + self roll3 ]. ^frameScore updateFrameStart self strike ifTrue: [ frameStart := frameStart + 1] ifFalse: [ frameStart := frameStart + 2] score 10 timesRepeat: [score := score + self frameScore. self updateFrameStart]. ^score initialize rolls := OrderedCollection new. score := 0. frameStart := 1. ^self Saturday, November 19, 11
  • 28. 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
  • 29. 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) wiki Saturday, November 19, 11
  • 30. 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
  • 31. Edsger W. Dijkstra Saturday, November 19, 11
  • 32. 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. - 1975 Saturday, November 19, 11
  • 33. Edsger W. Dijkstra Saturday, November 19, 11
  • 34. Edsger W. Dijkstra Object-oriented programming is an exceptionally bad idea which could only have originated in California. Saturday, November 19, 11
  • 35. Edsger W. Dijkstra Object-oriented programming is an exceptionally bad idea which could only have originated in California. I don't 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
  • 36. 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 I'm not aware of them. (email 23/07/2003) http://www.flickr.com/photos/marcospiller Saturday, November 19, 11
  • 37. 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 I'm 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/marcospiller Saturday, November 19, 11
  • 38.   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 man's 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 man's closures."  Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's  object."  At that moment, Anton became enlightened. Saturday, November 19, 11
  • 39.   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 man's 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 man's closures."  Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's  object."  At that moment, Anton became enlightened. Anton van Straaten 4 June 2003 Saturday, November 19, 11
  • 41. Yun Tung Lao - The Art of Objects - Addison Wesley Saturday, November 19, 11
  • 42. 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
  • 43. An object has state, behavior, and identity - Grady Booch Saturday, November 19, 11
  • 44. 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
  • 45. 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 Objects Saturday, November 19, 11
  • 46. Do I smell spaghetti? Saturday, November 19, 11
  • 49. Why singleton? Strategy without DI is pointless Saturday, November 19, 11
  • 50. Why singleton? Strategy without DI is pointless This is worse than procedural! Saturday, November 19, 11
  • 51. 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
  • 52. 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. 251 Saturday, November 19, 11
  • 53. 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 group's 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 ACM's 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 Author's 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 8 Saturday, November 19, 11
  • 54. 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 2009 Saturday, November 19, 11
  • 56. The Functional eye http://www.flickr.com/photos/dirtyf Saturday, November 19, 11
  • 57. 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/dirtyf Saturday, November 19, 11
  • 60. The ObjectOriented eye • Dependency Injection • No getters for mutable state • Interfaces for collaborators (Liskov) • Simpler aggregates (Demeter) • Meaningful name convention Saturday, November 19, 11
  • 61. 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
  • 62. 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
  • 63. Object Design Rebecca Wirfs-Brock Control • Centralized • Dispersed • Delegated Saturday, November 19, 11
  • 64. Centralized Invoice Customer Invoice Printer Manager Saturday, November 19, 11
  • 65. 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
  • 66. Dispersed Customer Items Invoice Printer Popular with Zombie objects (aka Hibernated beans) Saturday, November 19, 11
  • 67. Logic Delegated Entity Identity CustomerFetcher Value InvoiceFetcher Immutable Customer No Id Invoice Printer InvoicePrinter Saturday, November 19, 11
  • 68. The valley of comfort http://www.flickr.com/photos/lviggiano Saturday, November 19, 11
  • 69. The valley Elegance and familiarity are orthogonal of comfort Rich Hickey on #Clojure http://www.flickr.com/photos/lviggiano Saturday, November 19, 11
  • 70. 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/lviggiano Saturday, November 19, 11
  • 71. 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/lviggiano Saturday, November 19, 11
  • 72. The journey to the valley • What about domain • What about tests • What about mocks • What about refactoring http://www.flickr.com/photos/bobcatnorth Saturday, November 19, 11
  • 73. Open questions • Do we need a yet another new language? • Can we have Architects? • How to teach design? Saturday, November 19, 11