SlideShare una empresa de Scribd logo
1 de 73
Descargar para leer sin conexión
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

Más contenido relacionado

Similar a 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 WebJeff Carouth
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-phpJuan Maiz
 
JS-Everywhere - LocalStorage Hands-on
JS-Everywhere - LocalStorage Hands-onJS-Everywhere - LocalStorage Hands-on
JS-Everywhere - LocalStorage Hands-onBrice 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 proceduresNorman 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 partsMikko 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 Appsweissazool
 
Scrum und Craftsmanship
Scrum und CraftsmanshipScrum und Craftsmanship
Scrum und CraftsmanshipStefan ROOCK
 
Apache Hadoop Talk at QCon
Apache Hadoop Talk at QConApache Hadoop Talk at QCon
Apache Hadoop Talk at QConCloudera, Inc.
 
Deconstructing Functional Programming
Deconstructing Functional ProgrammingDeconstructing Functional Programming
Deconstructing Functional ProgrammingC4Media
 

Similar a 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
 

Más de 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
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About MorphismsUberto Barbini
 
The Role of Testing in DevOps
The Role of Testing in DevOpsThe Role of Testing in DevOps
The Role of Testing in DevOpsUberto 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
 
Develop Gwt application in TDD
Develop Gwt application in TDDDevelop Gwt application in TDD
Develop Gwt application in TDDUberto Barbini
 

Más de 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
 

Último

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Último (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

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