Article Discussion
How Scala Changed My Programming Style
Summary: Learning a new programming language sometimes influences how you code in other languages, too. In this essay, Bill Venners shares how learning Scala influenced his programming style.
52 posts.
The ability to add new comments in this discussion is temporarily disabled.
Most recent reply: November 29, 2018 2:45 AM by Jason
    Bill
     
    Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
    How Scala Changed My Programming Style
    April 28, 2009 9:00 PM      
    In this short article, first published in December 2009 in the Parleys Magazine at the Devoxx conference in Antwerp, Belgium, Bill Venners describes how learning Scala has changed his programming style:

    http://www.artima.com/scalazine/articles/programming_style.html

    If you've programmed in Scala, how has it influenced your programming style? If you haven't yet tried Scala, what is your opinion of all this functional stuff?
    • Mark
       
      Posts: 48 / Nickname: mthornton / Registered: October 16, 2005 11:22 PM
      Re: How Scala Changed My Programming Style
      April 28, 2009 11:46 PM      
      boolean nameHasUpperCase = !name.toLowerCase().equals(name);
      


      I suspect there are some strings (and Locale's) for which that expression will give the wrong answer.
    • Daniel
       
      Posts: 11 / Nickname: djimenez / Registered: December 22, 2004 0:48 AM
      Re: How Scala Changed My Programming Style
      April 29, 2009 6:53 AM      
      Imperative code seems to me to be a jumble of three parts: control structures, the data model, and calculation. (By control structures, I mean going through the data model to get to the pieces that are to be calculated upon; think finding a particular vertex in a graph to operate on, or getting the flozzle from the whosit contained by the thingamajig stored in the shigbaz.) But it wasn't until I started reading about, and attempting, functional programming techniques that I recognized this.

      Your article provides an excellent example of these three parts: the for loop is the control structure, the data model is the string, and the calculation is "are any letters upper case?"

      I'm thinking, following Fred Brooks, that the calculation part is the essential complexity, with the control structures and data model somewhat "accidental." I find imperative code to be a mix of the three, and therefore quite difficult to maintain. But, as your functional rewrite shows, when the control structures and data model are pushed into the background, the calculation is easier to see, thus easier to maintain / extend.

      Of course, legacy code (in the Michael Feathers sense: huge and without tests) has methods tens-to-hundreds of lines long intermixing those three parts. In your experience, to what scale does functional rewriting work? Trivial examples, obviously; ten-line methods with one calculation embedded? Hundred-line methods with 2-5? Thousand line methods with 10-30? (None of us write those monstrosities, but the unfortunate amongst us have had to maintain them.) What are your logistics for refactoring from imperative to functional style?
    • Rupert
       
      Posts: 3 / Nickname: rkit / Registered: December 9, 2005 7:32 AM
      Re: How Scala Changed My Programming Style
      April 29, 2009 10:09 AM      
      in C++, you can do it like this:


      template <typename ITER>
      bool has_upper(ITER begin, ITER end) {
      return end != std::find_if(begin, end, std::isupper);
      }
    • amin
       
      Posts: 1 / Nickname: aahmad / Registered: February 28, 2007 0:26 AM
      Re: How Scala Changed My Programming Style
      April 29, 2009 9:24 PM      
      Personally, traits are another feature of Scala that I really miss in Java.

      And, as you alluded, functions-as-objects is a huge benefit to re-usability. In Java, you would need to define an interface to do the same thing, but the problem is that 3rd party code won't know about your interface, so you end up having to write little wrapper classes all over the place.
    • Tom
       
      Posts: 2 / Nickname: boardtc / Registered: September 9, 2003 11:43 AM
      Re: How Scala Changed My Programming Style
      April 30, 2009 1:57 AM      
      Thanks for the article. That's a great angle to think about the languages we have used.

      val nameHasUpperCase = name.exists(_.isUpperCase)

      Scala's exists reminds me of Groovy's each..essentially if I am following it _.isUpperCase is the closure.
      • Bill
         
        Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
        Re: How Scala Changed My Programming Style
        April 30, 2009 9:03 AM      
        > Thanks for the article. That's a great angle to think
        > about the languages we have used.
        >
        > val nameHasUpperCase = name.exists(_.isUpperCase)
        >

        > Scala's exists reminds me of Groovy's each..essentially if
        > I am following it _.isUpperCase is the closure.
        >
        You're right that Groovy's each is similar to Scala's exists in that both take a function as a parameter, but the Scala method that exactly corresponds to Groovy's each is called foreach. This will print each character of name on a separate line:


        name.foreach(println)
        • Tom
           
          Posts: 2 / Nickname: boardtc / Registered: September 9, 2003 11:43 AM
          Re: How Scala Changed My Programming Style
          April 30, 2009 9:59 AM      
          > >
          > > val nameHasUpperCase = name.exists(_.isUpperCase)
          > >

          > > Scala's exists reminds me of Groovy's each..essentially
          > > if I am following it _.isUpperCase is the
          > > closure.
          > You're right that Groovy's each is similar to Scala's
          > exists in that both take a function as a parameter

          Ok, that was my point really that the exists took a closure. Does the fact that you did not use this terminology suggest it is not used in Scala because of the more functional slant? It's all; semantics anyway!
    • Dave
       
      Posts: 2 / Nickname: 64382 / Registered: December 29, 2008 5:19 PM
      Re: How Scala Changed My Programming Style
      April 29, 2009 9:21 AM      
      Hi Bill. I love reading your clear articles (and the book you co-authored) about Scala. From you I try to learn how to better explain Scala to people myself.

      Sometimes when people compare Java to other languages, they unfairly use the old-style “for” statement, when really a modern programmer would use for-each. You did that here. In this case:

      for (char c : name.toCharArray())

      would have been more fair.

      Dave
      • Bill
         
        Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
        Re: How Scala Changed My Programming Style
        April 29, 2009 11:14 AM      
        > Hi Bill. I love reading your clear articles (and the book
        > you co-authored) about Scala. From you I try to learn how
        > to better explain Scala to people myself.
        >
        > Sometimes when people compare Java to other languages,
        > they unfairly use the old-style “for” statement, when
        > really a modern programmer would use for-each. You did
        > that here. In this case:
        >
        > for (char c : name.toCharArray())
        >
        > would have been more fair.
        >
        Ah! That's a great approach, and one that had never occurred to me. I actually picked iterating through the characters of a string as an example because java.lang.String can't be treated as a sequential collection in Java. For most other collections in Java you could use the foreach syntax, and I wanted to show the most imperative style first (i.e., I wanted to show a realistic example that forces you to iterate with an index). The foreach syntax moves closer to the functional style, in that it doesn't require you to specify an end index, so it eliminates the potential for an off-by-one error.

        I was trying to be fair to Java, though, by showing the Java one liner. I wanted to show you can do it in a more concise way in Java, and in general can program in a functional style in Java to some extent.

        Another thing that's a bit interesting to me is that what you did explicitly by converting the String to a Char[] is also the approach Scala has to take, but it does so with an implicit conversion to RichString. RichString mixes in the Seq trait, so you get higher-order methods such as exists, which I used in the example, but also map, flatMap, etc., that make it possible to use strings as sequences of characters in for expressions in Scala.
        • Dave
           
          Posts: 2 / Nickname: 64382 / Registered: December 29, 2008 5:19 PM
          Re: How Scala Changed My Programming Style
          April 30, 2009 9:56 AM      
          I suppose you could continue to use looping over a java.lang.String with old-style for in this example if you said that the String could be very long and memory and time tight, precluding copying it to a char[]. Just so it’s a realistic need to use old-style for.

          Thanks for bringing Scala to so many new people, Bill.
      • James
         
        Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
        Re: How Scala Changed My Programming Style
        April 29, 2009 9:27 AM      
        > Hi Bill. I love reading your clear articles (and the book
        > you co-authored) about Scala. From you I try to learn how
        > to better explain Scala to people myself.
        >
        > Sometimes when people compare Java to other languages,
        > they unfairly use the old-style “for” statement, when
        > really a modern programmer would use for-each. You did
        > that here. In this case:
        >
        > for (char c : name.toCharArray())
        >
        > would have been more fair.

        Now that you mention is, the use of a boolean variable is also terrible style. I would do this:
        boolean containsUpperCase(String s)
        {
            for (char c : s.toCharArray()) {
               if (Character.isUpperCase(c)) return true;
            }
         
            return false;
        }
        
        • Bill
           
          Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
          Re: How Scala Changed My Programming Style
          April 29, 2009 11:25 AM      
          > > Hi Bill. I love reading your clear articles (and the
          > book
          > > you co-authored) about Scala. From you I try to learn
          > how
          > > to better explain Scala to people myself.
          > >
          > > Sometimes when people compare Java to other languages,
          > > they unfairly use the old-style “for” statement, when
          > > really a modern programmer would use for-each. You did
          > > that here. In this case:
          > >
          > > for (char c : name.toCharArray())
          > >
          > > would have been more fair.
          >
          > Now that you mention is, the use of a boolean variable is
          > also terrible style. I would do this:
          >
          > boolean containsUpperCase(String s)
          > {
          >     for (char c : s.toCharArray()) {
          >        if (Character.isUpperCase(c)) return true;
          >     }
          > 
          >     return false;
          > }
          > 
          

          >
          Since when has the approach of setting a boolean variable inside a loop been considered terrible style? I'd just call it an imperative style. That's how I was taught to program in C, and how I continued to program in C++, and how I programmed in Java. I did this for years and years. When looking for something in a collection I'd initialize a boolean variable named found to false, then set it to true inside the loop. I wasn't clued into making little functions so I could avoid mutable variables like you've shown in your example until I was faced with val versus var in Scala. Trying to figure out how to get rid of vars, and puzzling over why I would care to to do that, is where I got the insight into how the functional style could make my code better.

          Do many people already try and avoid mutable variables like this in Java?
          • James
             
            Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
            Re: How Scala Changed My Programming Style
            April 29, 2009 1:28 PM      
            > Since when has the approach of setting a boolean variable
            > inside a loop been considered terrible style? I'd just
            > call it an imperative style. That's how I was taught to
            > program in C, and how I continued to program in C++, and
            > how I programmed in Java. I did this for years and years.
            > When looking for something in a collection I'd initialize
            > a boolean variable named found to false, then set it to
            > true inside the loop. I wasn't clued into making little
            > functions so I could avoid mutable variables like you've
            > shown in your example until I was faced with val versus
            > var in Scala. Trying to figure out how to get rid of vars,
            > and puzzling over why I would care to to do that, is where
            > I got the insight into how the functional style could make
            > my code better.
            >
            > Do many people already try and avoid mutable variables
            > like this in Java?

            OK you've got me. I'm really only speaking for myself here. There's no consensus (that I see) that this is bad style. But I have specific reasons for why I believe it to be so and the reasons I've often heard for contrary usually amounts to what you provide: "That's how I was taught to program in <language X>"

            What you did here is not the worst case of this but it's a general problem I see in Java: extraneous variables, usually boolean flags. It actually makes sense in a some languages specifically those that do not guarantee all branches of a method return a value or that variables are assigned before they are used.

            Generally I see things like this:
            int getFoo(int in)
            {
               int out = 0;
             
               switch (in) {
                 case 1:
                   out = 10;
                   break;
                 case 2:
                   out = 200;
                   break;
                 case 3:
                   out = 15;
                   break;
               }
             
               return out;
            }
            


            This is then declared to be "good practice" because you know what getFoo returns: the value of 'out'. This to me is a 'turtles all the way down' kind of argument. Knowing the name of the variable that is returned at the end of the method is not important.

            Consider the alternative style:
            int getFoo(int in)
            {
               switch (in) {
                 case 1:
                   return 10;
                 case 2:
                   return 200;
                 case 3:
                   return 15;
               }
            }
            


            Much simpler and if I ask you what it returns it returns 10 if in is 1, 200 if in is 2 and 15 if in is 3 and... Did you catch it? This doesn't return anything if something other than 1, 2 or 3 is provided. What's really cool about this in Java is that you don't have to catch that mistake. It won't compile. So if I'm coding on the tail end of a bender, I just saved myself some frustration. It might also make me realize that I don't want to return 0 for all other cases. I might want to do something else if a negative number was passed in.

            In fact, I actually sometimes write code like you have done here, although it's usually out of laziness and flags are sometimes the right choice. The point I'm trying to make is that by switching to an unfamiliar paradigm you are able to lose a lot of baggage that you've accumulated that may not have anything to do with Java at all.

            I actually completely agree with your overall premise here but it might seem like you set up a straw-man a bit (which I don't think was your intention.)
            • Bill
               
              Posts: 28 / Nickname: billpyne / Registered: January 29, 2007 4:12 AM
              Re: How Scala Changed My Programming Style
              April 29, 2009 6:01 PM      
              "What's really cool about this in Java is that you don't have to catch that mistake. It won't compile."

              Oddly, I was just bitten today by a language that doesn't catch it at compile time. I added a few functions to my PL/SQL package on Tuesday 5 minutes before leaving. I forgot to put in the return statement to the functions - stupid mistake caused by rushing. It compiled fine but today I had a heck of a time debugging odd run-time behavior. I would have thought that checks for a return would be compile time given PL/SQL's ancestry being Ada and Ada's safety record.

              Anyway, it makes me appreciate languages like Java that do perform the check a compile time.
            • Bill
               
              Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
              Re: How Scala Changed My Programming Style
              April 29, 2009 2:30 PM      
              > > Since when has the approach of setting a boolean
              > variable
              > > inside a loop been considered terrible style? I'd just
              > > call it an imperative style. That's how I was taught to
              > > program in C, and how I continued to program in C++,
              > and
              > > how I programmed in Java. I did this for years and
              > years.
              > > When looking for something in a collection I'd
              > initialize
              > > a boolean variable named found to false, then set it to
              > > true inside the loop. I wasn't clued into making little
              > > functions so I could avoid mutable variables like
              > you've
              > > shown in your example until I was faced with val versus
              > > var in Scala. Trying to figure out how to get rid of
              > vars,
              > > and puzzling over why I would care to to do that, is
              > where
              > > I got the insight into how the functional style could
              > make
              > > my code better.
              > >
              > > Do many people already try and avoid mutable variables
              > > like this in Java?
              >
              > OK you've got me. I'm really only speaking for myself
              > here. There's no consensus (that I see) that this is bad
              > style. But I have specific reasons for why I believe it
              > to be so and the reasons I've often heard for contrary
              > usually amounts to what you provide: "That's how I was
              > taught to program in <language X>"
              >
              > What you did here is not the worst case of this but it's a
              > general problem I see in Java: extraneous variables,
              > usually boolean flags. It actually makes sense in a some
              > languages specifically those that do not guarantee all
              > branches of a method return a value or that variables are
              > assigned before they are used.
              >
              > Generally I see things like this:
              >
              > int getFoo(int in)
              > {
              >    int out = 0;
              > 
              >    switch (in) {
              >      case 1:
              >        out = 10;
              >        break;
              >      case 2:
              >        out = 200;
              >        break;
              >      case 3:
              >        out = 15;
              >        break;
              >    }
              > 
              >    return out;
              > }
              

              >
              > This is then declared to be "good practice" because you
              > know what getFoo returns: the value of 'out'. This to me
              > is a 'turtles all the way down' kind of argument. Knowing
              > the name of the variable that is returned at the end of
              > the method is not important.
              >
              > Consider the alternative style:
              >
              > int getFoo(int in)
              > {
              >    switch (in) {
              >      case 1:
              >        return 10;
              >      case 2:
              >        return 200;
              >      case 3:
              >        return 15;
              >    }
              > }
              

              >
              > Much simpler and if I ask you what it returns it returns
              > 10 if in is 1, 200 if in is 2 and 15 if in is 3 and... Did
              > you catch it? This doesn't return anything if something
              > other than 1, 2 or 3 is provided. What's really cool
              > about this in Java is that you don't have to catch that
              > mistake. It won't compile. So if I'm coding on the tail
              > end of a bender, I just saved myself some frustration. It
              > might also make me realize that I don't want to return 0
              > for all other cases. I might want to do something else if
              > a negative number was passed in.
              >
              > In fact, I actually sometimes write code like you have
              > done here, although it's usually out of laziness and flags
              > are sometimes the right choice. The point I'm trying to
              > make is that by switching to an unfamiliar paradigm you
              > are able to lose a lot of baggage that you've accumulated
              > that may not have anything to do with Java at all.
              >
              > I actually completely agree with your overall premise here
              > but it might seem like you set up a straw-man a bit (which
              > I don't think was your intention.)
              >
              Sorry if I unintentionally strawed you. I just was curious if I had missed the Java community talking about this kind of thing. I need to look at the latest Effective Java again for this, because that's pretty influential on how people code, I'd expect.

              It looks to me like you have subconscious functional urges trying to manifest themselves in your Java style. Bill Pyne made a good point about using the variables to look at intermediate values in debuggers. I also like to put intermediate values in variables in complex expressions just to give them a name to kind of explain what I'm calculating, just for code readability. But it also can help when debugging I think.

              I also was told by someone at some point, maybe back in my C days, that it is better to just have one return statement in a function or method. But I was also told by others that they liked multiple returns to keep the method less nested. I think I usually leaned towards trying to just have one exit point, but I remember not being sure it was the best way.

              Anyway, Java's switch statement is an example of how Java kind of pushes its users towards the imperative style. It is an imperative control construct because it doesn't result in a value. Java's equivalent construct, match, can do the same kind of thing. For example, I could say in Scala:


              def getFoo(in: Int): Int = {
              in match {
              case 1 =>
              return 10;
              case 2 =>
              return 200;
              case 3 =>
              return 15;
              }
              }


              But match is a functional control construct because it results in a value. The value it results in in the previous example is called "Unit", which is a bit like void. But I could simply make it result in an Int like this:


              def getFoo(in: Int) =
              in match {
              case 1 => 10
              case 2 => 200
              case 3 => 15
              case _ => -1
              }


              The case _ at the end is a default case, like default in Java switch statements. Scala's match doesn't fall through, either, so you don't need break, and in fact Scala doesn't even have break. The result of this match expression will either be 10, 200, 15, or -1, and because it is the last expression of the method, that value will be returned. No explicit return is needed. When I look at your examples, I get the feeling you're wanting to do this kind of thing in Java, but that Java doesn't make it as easy as Scala. The other thing you did in your previous post was make a little function, which is something I do a lot more in Scala than I did in Java, because Scala encourages that style with its concise syntax for functions and support for local functions (which are functions declared inside other functions, and only available in that scope).
              • James
                 
                Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
                Re: How Scala Changed My Programming Style
                April 29, 2009 6:24 PM      
                > Sorry if I unintentionally strawed you. I just was curious
                > if I had missed the Java community talking about this kind
                > of thing. I need to look at the latest Effective Java
                > again for this, because that's pretty influential on how
                > people code, I'd expect.

                Seriously, don't take it to heart. There was a the post above mentioning the foreach sugar in Java and I got on my soapbox trying to push my multiple return agenda. It wasn't really on-topic. Sorry.

                > It looks to me like you have subconscious functional urges
                > trying to manifest themselves in your Java style.

                Absolutely. My experience with Scala and Python has definitely shown me that functional approaches can add a lot to OO. Bill and I were actually working together on a functional style library for Java (with an eye on Scala) until I got busy with other things and left him hanging.

                I like a lot of things about Scala but I think it's a bit too arcane for the average IT shop to seriously consider. I want to get your book though and give it another chance.

                > Bill Pyne made a good point about using the variables to
                > look at intermediate values in debuggers. I also like to
                > put intermediate values in variables in complex
                > expressions just to give them a name to kind of explain
                > what I'm calculating, just for code readability. But it
                > also can help when debugging I think.

                I don't use debuggers so that may be part of why I don't do that. In my experience, code that uses these intermediate variables is harder to follow and tends to have more bugs. If you keep your methods small and to the point, there's rarely a need for them. I write lots of short private methods that are only called from one place just to help organize and document code. When I do use intermediate variables, I don't initialize them to a default value unless that's the clearest and most correct logic or can't be avoided.
          • Bill
             
            Posts: 28 / Nickname: billpyne / Registered: January 29, 2007 4:12 AM
            Re: How Scala Changed My Programming Style
            April 29, 2009 0:32 PM      
            > Since when has the approach of setting a boolean variable
            > inside a loop been considered terrible style? I'd just
            > call it an imperative style. That's how I was taught to
            > program in C, and how I continued to program in C++, and
            > how I programmed in Java.

            I'm with you on this Bill. I was taught to set the variable so you could see the return variable's value in dbx before the return.

            (Also, I was taught multiple calls to "return" in the same function were no-no's but I break that rule in some instances.)
            • Mark
               
              Posts: 48 / Nickname: mthornton / Registered: October 16, 2005 11:22 PM
              Re: How Scala Changed My Programming Style
              May 1, 2009 1:32 AM      
              >
              > I'm with you on this Bill. I was taught to set the
              > variable so you could see the return variable's value in
              > dbx before the return.
              >

              We could do with debuggers that show a functions return value without needing artificial variables.
              • John
                 
                Posts: 7 / Nickname: garibaldi / Registered: March 3, 2008 1:14 AM
                Re: How Scala Changed My Programming Style
                May 1, 2009 2:56 AM      
                > We could do with debuggers that show a functions return
                > value without needing artificial variables.

                Works just nicely for C++ with Visual Studio 2008 :-)
            • Vincent
               
              Posts: 40 / Nickname: vincent / Registered: November 13, 2002 7:25 AM
              Re: How Scala Changed My Programming Style
              May 1, 2009 1:25 AM      
              > I'm with you on this Bill. I was taught to set the
              > variable so you could see the return variable's value in
              > dbx before the return.

              I think that's the point. The variable only exists for the potential benefit of using a debugger if you have to step through the code. Apart from that, it's existence adds nothing to the method and it could be replaced by a return statement because the return value has been calculated, so there is no longer any reason to remain in the method.

              (Overall though, it's just a minor distraction since the point of the article was to demonstrate Scala capabilities not Java coding style artifacts.)
              • James
                 
                Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
                Re: How Scala Changed My Programming Style
                May 1, 2009 5:13 AM      
                > (Overall though, it's just a minor distraction since the
                > point of the article was to demonstrate Scala capabilities
                > not Java coding style artifacts.)

                You're right. Sorry about that.
    • Harrison
       
      Posts: 7 / Nickname: hxa7241 / Registered: April 10, 2005 7:41 AM
      Re: How Scala Changed My Programming Style
      April 30, 2009 9:25 AM      
      Having a single return point is structured -- which gives a simple, uniformity of shape (check: ‘Notes On Structured Programming’/ewd249; Dijkstra; 1970). It should be the default, unless the code can be made even simpler otherwise.

      I rate Scala even more compact than Ruby and Python: 86% of the size to be exact! (45% of C++) -- see: http://www.hxa.name/minilight/#comparison and http://www.hxa.name/minilight/minilight-scala-code.html for full code.

      Scala struck just right balance with its type inference, that is: types stated explicitly at function parameters, but not needed elsewhere. OCaml doesn't require them at function parameters, but it is sometimes hard to make it compile -- each time you try to fix it, the error messages change because it infers from a different point.

      OCaml changed me a bit earlier, but that prepared me for immediately liking Scala.
      • James
         
        Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
        Re: How Scala Changed My Programming Style
        April 30, 2009 11:30 AM      
        > Having a single return point is structured -- which gives
        > a simple, uniformity of shape (check: ‘Notes On Structured
        > Programming’/ewd249; Dijkstra; 1970).

        Structured programming and this rule specifically is baked into Java. This isn't surprising given that Java was created 20 years later. It's implicit. Doing it explicitly is redundant and has provides no benefit.

        Like I said before, the reasoning that people give for doing this is based on older languages that allow for things that Java does not.

        > It should be the
        > default, unless the code can be made even simpler
        > otherwise.

        It's almost always simpler otherwise. Tree shaped methods are easier to follow than onion shaped methods which is why the compiler can verify tree shaped methods and not onion shaped methods.

        I've worked with reams of code written in single return style. It's much buggier and harder to understand than multiple return style code. You are just substituting an assignment to variable (a vague operation) for the return keyword (a clear operation.) The variable is completely extraneous.

        Yes, you know there is one return at the end. Why is that important? It tells you nothing about what is returned. You still have to do the look through the code to figure out what value the variable will be i.e. what will be returned. And often this is more difficult than it is to determine than in the equivalent multi return code for multiple reasons. For example consider the following snippets:

        boolean isFoo()
        {
           for (item : things) {
              if (item.hasBar()) return true;
           }
         
           // more code ...
        }
        


        boolean isFoo()
        {
           boolean returnValue = false;
         
           for (item : things) {
              if (item.hasBar()) returnValue = true;
           }
         
           // more code ...
         
           return returnValue;
        }
        


        In the first example, I can see immediately that if one of the items has bar, the method returns true. If that's all the information I need, I'm done. In the second, all I know is that returnValue is set to true at that point in the method. I might think that probably means the method returns true in that case but I can't be sure. I must look through the rest of the code or risk error. Most of the time it will be but I've seen cases where it would set later. I often found this kind of logic while hunting down bugs because the later assignment to the return variable was in error.

        And, on a side note, any decent IDE is going to allow the return keyword to be syntax highlighted. The simple assignment won't be. I seriously don't understand why people continue to insist that this unequivocally bad practice is good.


        Consider this:
        boolean isFoo()
        {
           for (item : things) {
              if (item.hasBar()) return true;
           }
         
           if (useDefaultFoo) {
              if (LOGGER.isTraceEnabled()) {
                 LOGGER.trace("using default foo: " + defaultFoo);
                 return defaultFoo;  // real error I've seen
              }
           } else {
              return false;
           }
        }
        


        boolean isFoo()
        {
           boolean returnValue = false;
         
           for (item : things) {
              if (item.hasBar()) returnValue = true;
           }
         
           if (useDefaultFoo) {
              if (LOGGER.isTraceEnabled()) {
                 LOGGER.trace("using default foo: " + defaultFoo);
                 returnValue = defaultFoo;  // real error I've seen
              }
           }
         
           return returnValue;
        }
        


        Both are wrong. The first doesn't compile, the second does. By using return variables, you are impeding the compiler's ability to catch mistakes. I can't count the number of times using multiple returns has saved me from errors.
        • Mark
           
          Posts: 48 / Nickname: mthornton / Registered: October 16, 2005 11:22 PM
          Re: How Scala Changed My Programming Style
          April 30, 2009 0:50 PM      
          I see nothing wrong with multiple returns in pure functions, however they may sometimes be more dangerous in methods with side effects.
          • James
             
            Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
            Re: How Scala Changed My Programming Style
            April 30, 2009 0:59 PM      
            > I see nothing wrong with multiple returns in pure
            > functions, however they may sometimes be more dangerous in
            > methods with side effects.

            Can you elaborate?
            • Mark
               
              Posts: 48 / Nickname: mthornton / Registered: October 16, 2005 11:22 PM
              Re: How Scala Changed My Programming Style
              April 30, 2009 1:14 PM      
              In a pure function you need only verify that the valuye returned by each return is sensible. With a method evaluated for its side effects you have also to verify that all the required side effects have been produced in preceding code. You might modify such a method and fail to notice that an earlier return takes place without causing your modifed side effect to take place.
              • Mark
                 
                Posts: 48 / Nickname: mthornton / Registered: October 16, 2005 11:22 PM
                Re: How Scala Changed My Programming Style
                April 30, 2009 1:21 PM      
                Incidentally, Scala reminds of a feature which I would like to use but which Java doesn't support efficiently and where Scala's support is limited: tail recursion.
                A JVM could do a much better job of this than Scala's compiler can do.
              • James
                 
                Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
                Re: How Scala Changed My Programming Style
                April 30, 2009 1:44 PM      
                > In a pure function you need only verify that the valuye
                > returned by each return is sensible. With a method
                > evaluated for its side effects you have also to verify
                > that all the required side effects have been produced in
                > preceding code. You might modify such a method and fail to
                > notice that an earlier return takes place without causing
                > your modifed side effect to take place.

                Generally, I would deal with this either by structuring the code such that logic and side effects are not executed in the same method. I'll create another class (usually inner or nested) if there's a lot of state that's shared between logic and persistence. If necessary, I'll use a finally block.

                If you can "miss" an early return, the method is probably too long. I seen many many bugs where not returning immediately was the root cause and I have never seen one caused by the situation you describe that I can recall. My insistence on this matter is derived from the number of times I've had to fix such bugs. Overall, though, keeping the methods short is the most important thing.
              • Morgan
                 
                Posts: 37 / Nickname: miata71 / Registered: March 29, 2006 6:09 AM
                This is why Scala Syntax annoys me
                April 30, 2009 1:20 PM      
                From Bill's article:

                "The exists method iterates through a collection of objects and passes each element in turn to the passed function object"

                Why the heck is this call "exists"???

                Actually, I think the name is o.k., it's Bill's description that is wrong - the "exists" matches that reverse E (or is it forward???) thing from math, right?

                But it's still a fairly technical term - how about "eachOr" or "checkEach" whatever???
                • Bill
                   
                  Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
                  Re: This is why Scala Syntax annoys me
                  May 1, 2009 7:31 AM      
                  Hi Morgan,

                  > From Bill's article:
                  >
                  > "The exists method iterates through a collection of
                  > objects and passes each element in turn to the passed
                  > function object"
                  >
                  > Why the heck is this call "exists"???
                  >
                  > Actually, I think the name is o.k., it's Bill's
                  > description that is wrong - the "exists" matches that
                  > reverse E (or is it forward???) thing from math, right?
                  >
                  > But it's still a fairly technical term - how about
                  > "eachOr" or "checkEach" whatever???
                  >
                  The way I'd say it in English is that the method answers the question, "Does a n element exist in this collection for which this Boolean "predicate" function is true?" That whole thing got shorted to simply, exists.
                  • James
                     
                    Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
                    Re: This is why Scala Syntax annoys me
                    May 1, 2009 8:26 AM      
                    > > But it's still a fairly technical term - how about
                    > > "eachOr" or "checkEach" whatever???
                    > >
                    > The way I'd say it in English is that the method answers
                    > the question, "Does a n element exist in this collection
                    > for which this Boolean "predicate" function is true?" That
                    > whole thing got shorted to simply, exists.

                    I think Morgan's right that this is a very mathematical name for this. The statement would be:

                    "at least one element exists such that [predicate] is true for that element."

                    A more intuitive name might be: atLeastOne(). This is an example (not the best) of what I think will hold Scala back. It designed with a very academic mindset. I know that the intention was to cater to business with Scala but I don't consider it successful in that aspect. There are a lot of really smart developers out there who have never taken a class in discrete mathematics or studied set theory. If I were going to champion Scala where I work, I would be required to explain a lot of these terms. And this is one of the simpler concepts in Scala. A lot of really educated developers don't know what a fold is. I'd never encountered the term before I started learning Scala. It might be hugely useful but how will people know without an explanation in plan terms?
                    • Bill
                       
                      Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
                      Re: This is why Scala Syntax annoys me
                      May 1, 2009 11:51 AM      
                      Hi James,

                      > A more intuitive name might be: atLeastOne(). This is an
                      > example (not the best) of what I think will hold Scala
                      > back. It designed with a very academic mindset.
                      >
                      One more thing on Scala's academic-ness. I saw James Gosling give his "Feel of Java Revisited" talk last year, and one of the things he reemphasized was that his goal was to almost "trick" mainstream C programmers into using things that had been proven in academia, but hadn't been accepted by the mainstream commercial software world. Things like garbage collection and exceptions. These were "academic" features of "academic" languages back then, not mainstream languages. Gosling actually used the word "fraud" in his talk, saying that Java was a well orchestrated fraud, it looked like C on the outside, but on the inside, it was moving the art forward by getting things out from academia into the real world.

                      So folds in Scala I think have the same problem. They are seen as academic, because they haven't been used by the mainstream, and they in fact are academic in that sense. But that doesn't mean they aren't darned useful, and so the question is really to what extent will Scala help popularize the concept of folds, as well as other things from the functional world. I think Scala does indeed look a lot less like Java than Java looked like C, so there's a chance it is too great a leap for some folks. It remains to be seen how people react, but so far the reactions seem pretty positive. It may be a self selecting group, though. In other words, the people that would even bother to look at Scala this early might be the kind of people who are open to leaping a bit and learning some new ways of doing things.
                    • Bill
                       
                      Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
                      Re: This is why Scala Syntax annoys me
                      May 1, 2009 11:35 AM      
                      > > > But it's still a fairly technical term - how about
                      > > > "eachOr" or "checkEach" whatever???
                      > > >
                      > > The way I'd say it in English is that the method
                      > answers
                      > > the question, "Does a n element exist in this
                      > collection
                      > > for which this Boolean "predicate" function is true?"
                      > That
                      > > whole thing got shorted to simply, exists.
                      >
                      > I think Morgan's right that this is a very mathematical
                      > name for this. The statement would be:
                      >
                      > "at least one element exists such that [predicate] is true
                      > for that element."
                      >
                      > A more intuitive name might be: atLeastOne(). This is an
                      > example (not the best) of what I think will hold Scala
                      > back. It designed with a very academic mindset. I know
                      > that the intention was to cater to business with Scala but
                      > I don't consider it successful in that aspect. There are
                      > a lot of really smart developers out there who have never
                      > taken a class in discrete mathematics or studied set
                      > theory. If I were going to champion Scala where I work, I
                      > would be required to explain a lot of these terms. And
                      > this is one of the simpler concepts in Scala. A lot of
                      > really educated developers don't know what a fold is. I'd
                      > never encountered the term before I started learning
                      > Scala. It might be hugely useful but how will people know
                      > without an explanation in plan terms?
                      >
                      Scala was designed in academia, but by a guy who has a very practical outlook and was aiming to solve real world problems. I don't agree with all his naming choices either. For example, I think it would be better to have called "foreach" simply "each", like in Ruby. Because foreach seems to violate the camel case convention, and is longer. But exists honestly I never thought of as mathematical until the "backwards E" was brought in this forum discussion. I just figured he grabbed one English word from the English sentence you'd use to describe what the method call does.

                      I also didn't know what a fold was before I encountered Scala, but that surely doesn't mean it should be left out. It just needs to be explained, taught, learned. And you don't need to use it until you learn it, but of course if someone else uses it and you're reading their code, you'll have to learn it at that point. But fold is very fundamental and useful and should be learned by all Scala programmers eventually.

                      By the way, on fold, once in Junior high school I remember in some choir we prepared a round to sing at a conference, and I had to sing something that included "fold in eggs." It was a song about making a cake or something. I had never heard of "folding in eggs," and asked about it. I was told it is a baking term in which you mix the egg in one stroke at a time until it is mixed, and when I found out what folds mean in Scala, it reminded me of what it means in baking. You start with a start value (the egg), and then one element at a time, fold it into the collection. At the end, you have a different batter/collection that you can do something else with.
                      • James
                         
                        Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
                        Re: This is why Scala Syntax annoys me
                        May 1, 2009 0:55 PM      
                        > Scala was designed in academia, but by a guy who has a
                        > very practical outlook and was aiming to solve real world
                        > problems.

                        I said as much in my post that you are responding to. I did not say no attempt was made. I said the attempt was not successful in my opinion.

                        I don't want to be rude but when I look at Scala I have to wonder if the creators had any "real world" experience to pull from when attempting to solve "real world" problems. If not, I then have to question why they believed they knew what the "real world" needs. Even the obviously business targeted XML support was in no way what the "real world" needed.

                        > I also didn't know what a fold was before I encountered
                        > Scala, but that surely doesn't mean it should be left out.
                        > It just needs to be explained, taught, learned. And you
                        > don't need to use it until you learn it, but of course if
                        > someone else uses it and you're reading their code, you'll
                        > have to learn it at that point. But fold is very
                        > fundamental and useful and should be learned by all Scala
                        > programmers eventually.

                        Again this seems to me like you are not understanding me. I never said it should be left out. What I said was that this is unfamiliar to most developers. If Scala is to be an accessible language, I think a little more effort will be needed explain these features to non-academics. Having said that, I haven't read your book yet so maybe this is a bad example.
                        • Bill
                           
                          Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
                          Re: This is why Scala Syntax annoys me
                          May 1, 2009 3:22 PM      
                          > > Scala was designed in academia, but by a guy who has a
                          > > very practical outlook and was aiming to solve real
                          > world
                          > > problems.
                          >
                          > I said as much in my post that you are responding to. I
                          > did not say no attempt was made. I said the attempt was
                          > not successful in my opinion.
                          >
                          Fair enough. I actually thought of a better example for you, which I'll describe at the end.

                          > I don't want to be rude but when I look at Scala I have to
                          > wonder if the creators had any "real world" experience to
                          > pull from when attempting to solve "real world" problems.
                          > If not, I then have to question why they believed they
                          > y knew what the "real world" needs. Even the obviously
                          > business targeted XML support was in no way what the "real
                          > world" needed.
                          >
                          Martin didn't go out and do surveys or any kind of "market research" that I know of, and I think most of his adult career has been in academia. But he had always been somewhat grounded in reality in that he wrote a compiler that was bought by Borland in the early days, his GJ compiler was bought by Sun and used as javac for many years, etc. But mainly, his goal for Scala was not only that it serve as a vehicle for his language research, but also that it actually be adopted widely by real programmers doing real work. That's different than many academic languages, which are intended more a research vehicles only. He does listen and respond to his "customers," the users of Scala, but during the development of most of it he didn't have many customers to listen to. So how he decides what the world needs may be mostly coming from his intuition and experience.

                          > > I also didn't know what a fold was before I encountered
                          > > Scala, but that surely doesn't mean it should be left
                          > out.
                          > > It just needs to be explained, taught, learned. And you
                          > > don't need to use it until you learn it, but of course
                          > if
                          > > someone else uses it and you're reading their code,
                          > you'll
                          > > have to learn it at that point. But fold is very
                          > > fundamental and useful and should be learned by all
                          > Scala
                          > > programmers eventually.
                          >
                          > Again this seems to me like you are not understanding me.
                          > I never said it should be left out. What I said was that
                          > t this is unfamiliar to most developers. If Scala is to
                          > be an accessible language, I think a little more effort
                          > will be needed explain these features to non-academics.
                          > Having said that, I haven't read your book yet so maybe
                          > e this is a bad example.
                          >
                          The concept of folds may or may not be such a good example, but the syntax of folds might. There are two ways to do a fold left on lists in Scala, one is called foldLeft, the other /:. Here's how they look when used:

                          list.foldLeft(z)(op)

                          versus:

                          (z /: list)(op)

                          Even though the latter form has some readability and writability advantages for those familar with Scala and folds, the former one is a lot less scary or wierd looking to someone coming from Java. This fold operator is one of the more common complaints I've heard from Scala newbies, and a lot of people shy away from it. It certainly isn't going to "trick" a Java programmer into thinking this isn't very different from Java.
        • Bill
           
          Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
          Re: How Scala Changed My Programming Style
          May 1, 2009 7:44 AM      
          >
          > boolean isFoo()
          > {
          >    boolean returnValue = false;
          > 
          >    for (item : things) {
          >       if (item.hasBar()) returnValue = true;
          >    }
          > 
          >    // more code ...
          > 
          >    return returnValue;
          > }
          > 
          

          >
          > In the first example, I can see immediately that if one of
          > the items has bar, the method returns true. If that's all
          > the information I need, I'm done. In the second, all I
          > know is that returnValue is set to true at that point in
          > the method. I might think that probably means the method
          > returns true in that case but I can't be sure. I must
          > look through the rest of the code or risk error. Most of
          > the time it will be but I've seen cases where it would set
          > later. I often found this kind of logic while hunting
          > down bugs because the later assignment to the return
          > variable was in error.
          >
          This is exactly the benefit that I've found to prefer vals over vars in Scala. When you assign to a val (like a final variable in Java), you know it isn't going to change, so you don't have to look down through the rest of the method to see if it did. It makes code easier to read simply because of that one difference. In Java I probably used 5% final variables and 95% normal variables, but in Scala it is the other way around. I use probably 95% vals and 5% vars. That's a big way my programming style changed when moving to Scala, and is another example of my style becoming more functional.

          Another thing, which someone else pointed out, is that the problem you have with this kind of single return code would be reduced if the methods were smaller. And you, James, mentioned you like to make little private helper methods yourself. I'm not sure I use helper functions yet as much as I will in the future, but I use them some. David Pollak has lately been saying he tries to make his functions in Scala all one-liners. I wasn't so sure about going that far, but decomposing things into short, clear functions I think can help readability.

          Lastly, the irony I see in the multi-return style you're recommending James is that you're doing it to get benefits you get if the language would let you more easily program in a functional style. Java just makes it hard because so many of its control constructs don't result in a value. When everything results in a value, it is easier to see each function as just one expression, which results in a value. You don't need an explicit return, because that last value is returned implicitly. But that's the same as having "one return" in the method.
          • Morgan
             
            Posts: 37 / Nickname: miata71 / Registered: March 29, 2006 6:09 AM
            Re: How Scala Changed My Programming Style
            May 1, 2009 8:19 AM      
            No strong opinion on multiple returns, cause I use both styles schizophrenically. With the advent of multicore processors, I use many more final vars (and especially fields) in Java. When declaring a new class, the default visibility for fields is final. They change to non-final only if required.

            as to syntax, guess I'll have to invent my own language. :-)

            but, instead of

            name.exists(_.isUpperCase)

            if you are going to use mathematics-like language, why not use mathematics-like language

            thereExists(x elementOf name)suchThat(x.isUpperCase)
            or, a bit shorter
            thereExists(x elementOf name, x.isUpperCase)

            Less OO, which normally I'd complain about, but, IMO way clearer, and I was never that fond of the underline.
            • Bill
               
              Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
              Re: How Scala Changed My Programming Style
              May 1, 2009 11:25 AM      
              > Less OO, which normally I'd complain about, but, IMO way
              > clearer, and I was never that fond of the underline.
              >
              The underscore is an optional placeholder syntax. Other possibilities, in increasing order of verbosity, are:


              name.exists(x => x.isUpperCase)

              name.exists((x) => x.isUpperCase)

              name.exists((x: Char) => x.isUpperCase)


              But if someone else uses an underscore and you're reading your code, you'll have to look at it. It can be a cryptic if not used well, but if used well it reduces a bit of boilerplate.
            • James
               
              Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
              Re: How Scala Changed My Programming Style
              May 1, 2009 8:34 AM      
              > Less OO, which normally I'd complain about, but, IMO way
              > clearer, and I was never that fond of the underline.

              I not big on the underline either. It seems too Perl-esque to me. I mean, why underline, why not implicit variables?

              One the other hand, as long as it's consistent and there aren't too many other 'things to know' to use Scala, I'm OK with it.

              On a side note, the python for comprehension syntax is nice, IMO:

              [x.foo() for x in list]
              • Bill
                 
                Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
                Re: How Scala Changed My Programming Style
                May 1, 2009 11:37 AM      
                > On a side note, the python for comprehension syntax is
                > nice, IMO:
                >
                > [x.foo() for x in list]
                >
                Yes, Python is nice in a lot of ways. The equivalent in Scala is called a "for comprehension" or "for expression," and looks like this:

                for (x <- list) yield x.foo
          • James
             
            Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
            Re: How Scala Changed My Programming Style
            May 1, 2009 8:07 AM      
            > This is exactly the benefit that I've found to prefer vals
            > over vars in Scala. When you assign to a val (like a final
            > variable in Java), you know it isn't going to change, so
            > you don't have to look down through the rest of the method
            > to see if it did. It makes code easier to read simply
            > y because of that one difference. In Java I probably used
            > 5% final variables and 95% normal variables, but in Scala
            > it is the other way around. I use probably 95% vals and 5%
            > vars. That's a big way my programming style changed when
            > moving to Scala, and is another example of my style
            > becoming more functional.

            Agreed. The var vs. val choice is forced up front. My approach would be to mark almost everything as val unless and until I decide I need to make it a var and even then, I would contemplate if that's the right choice.

            > Another thing, which someone else pointed out, is that the
            > problem you have with this kind of single return code
            > would be reduced if the methods were smaller. And you,
            > James, mentioned you like to make little private helper
            > methods yourself. I'm not sure I use helper functions yet
            > as much as I will in the future, but I use them some.
            > David Pollak has lately been saying he tries to make his
            > functions in Scala all one-liners. I wasn't so sure about
            > going that far, but decomposing things into short, clear
            > functions I think can help readability.

            I actually like the way blocks in Scala allow you to do that kind of thing inside a method. I can see how it might get out of control but in a lot of cases, you wouldn't need another method.

            > Lastly, the irony I see in the multi-return style you're
            > recommending James is that you're doing it to get benefits
            > you get if the language would let you more easily program
            > in a functional style. Java just makes it hard because so
            > many of its control constructs don't result in a value.
            > When everything results in a value, it is easier to see
            > each function as just one expression, which results in a
            > value. You don't need an explicit return, because that
            > last value is returned implicitly. But that's the same as
            > having "one return" in the method.

            I think you are misinterpreting my argument. My point was never to demonstrate that Scala isn't an improvement over Java. I think it definitely has a lot to offer and that Java has many flaws. My point was that the comparison you showed was a little unfair, kind of like a car race where one car has bags of concrete in the trunk. Scala still wins IMO and making Java look worse than it really is might make your argument appear weaker.

            Basically, we have these rules that we follow in Java "because they are good" and we complain about the resulting code. Then we take a new language and declare those rules don't apply in it. But really, a lot of those rules never really applied in Java either. Bringing these kinds of things into the comparison is just noise and makes it harder to see the real differences.
            • Bill
               
              Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
              Re: How Scala Changed My Programming Style
              May 1, 2009 11:21 AM      
              > > This is exactly the benefit that I've found to prefer
              > > Lastly, the irony I see in the multi-return style
              > you're
              > > recommending James is that you're doing it to get
              > benefits
              > > you get if the language would let you more easily
              > program
              > > in a functional style. Java just makes it hard because
              > so
              > > many of its control constructs don't result in a value.
              > > When everything results in a value, it is easier to see
              > > each function as just one expression, which results in
              > a
              > > value. You don't need an explicit return, because that
              > > last value is returned implicitly. But that's the same
              > as
              > > having "one return" in the method.
              >
              > I think you are misinterpreting my argument. My point was
              > never to demonstrate that Scala isn't an improvement over
              > Java. I think it definitely has a lot to offer and that
              > Java has many flaws. My point was that the comparison you
              > showed was a little unfair, kind of like a car race where
              > one car has bags of concrete in the trunk. Scala still
              > wins IMO and making Java look worse than it really is
              > might make your argument appear weaker.
              >
              Oh, I was trying to be fair to Java. That's why I showed that Java can actually do it in one line. Had I thought of the foreach approach that Dave B showed, I would have showed that too. I have tried hard not to try and push Scala up by putting other languages, especially Java, down. Instead, I try and show the differences and talk about the plusses and minusses of both.

              I'm not sure why you thought I was suggesting you were trying to say Scala isn't an improvement over Java. I didn't get that impression. The "irony" I saw was that to get at the benefits of the functional style in Java, Java syntax actually pushed you in the other direction.

              As far as using the boolean variable, that's not me being unfair to Java. That's me being true to how I programmed in Java for 10 years, and how I think most people program in Java from the code I've seen over the years. That's the idiom, and returning from inside a for loop, which you showed, would I think be frowned upon by many Java programmers.

              > Basically, we have these rules that we follow in Java
              > "because they are good" and we complain about the
              > resulting code. Then we take a new language and declare
              > those rules don't apply in it. But really, a lot of those
              > rules never really applied in Java either. Bringing these
              > kinds of things into the comparison is just noise and
              > makes it harder to see the real differences.
              >
              Which rules to you mean? Sorry, can you be more explicit? If you mean he rule of having just one return, that doesn't quit add up because in Scala that's also the rule of thumb, except that you see it as one expression that doesn't need an explicit return.
              • James
                 
                Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
                Re: How Scala Changed My Programming Style
                May 1, 2009 0:42 PM      
                > I'm not sure why you thought I was suggesting you were
                > trying to say Scala isn't an improvement over Java. I
                > didn't get that impression. The "irony" I saw was that to
                > get at the benefits of the functional style in Java, Java
                > syntax actually pushed you in the other direction.

                I guess I get that impression because you keep telling about features of Scala when I already know Scala, or at least all the features you are talking about. Since I have tried to make that clear a couple times, it makes me think that you are not understanding me. I'm angry or anything, I'm just want to communicate effectively.

                > As far as using the boolean variable, that's not me being
                > unfair to Java. That's me being true to how I programmed
                > in Java for 10 years, and how I think most people program
                > in Java from the code I've seen over the years. That's the
                > idiom, and returning from inside a for loop, which you
                > showed, would I think be frowned upon by many Java
                > programmers.

                And again, this is exactly my point. It's not a feature of Java. It's something that people do in Java because think Java is like C. Given that Java is not really much like C, I fail to understand why it makes any more sense to use this idiom in Java than it does to use it in Scala.

                Are you saying that we must accept this as part of Java merely because some people say we should? If developers starting using this idiom in Scala does it become part of Scala?

                > Which rules to you mean? Sorry, can you be more explicit?
                > If you mean he rule of having just one return, that
                > doesn't quit add up because in Scala that's also the rule
                > of thumb, except that you see it as one expression that
                > doesn't need an explicit return.

                The source for List.exists() follows:
                  override def exists(p: A => Boolean): Boolean = {
                    var these = this
                    while (!these.isEmpty) {
                      if (p(these.head)) return true
                      these = these.tail
                    }
                    false
                  }
                

                Caveat: it's possible that the author of this method is not familiar with the idioms of Scala or of the single return rule of thumb in general.
                • James
                   
                  Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
                  Re: How Scala Changed My Programming Style
                  May 1, 2009 1:04 PM      
                  > I'm angry or anything,

                  Crud! That's "NOT angry".
                  • johny
                     
                    Posts: 11 / Nickname: johnyboyd / Registered: April 26, 2007 3:17 AM
                    Re: How Scala Changed My Programming Style
                    May 1, 2009 1:53 PM      
                    Jeez man, you sure have lots of free time :) Judging from your 'copious' output in these forums!
                  • Bill
                     
                    Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
                    Re: How Scala Changed My Programming Style
                    May 1, 2009 3:04 PM      
                    > > I'm angry or anything,
                    >
                    > Crud! That's "NOT angry".
                    >
                    I'm not angry either. I think we just misunderstood each other a bit, but when you said "I'm angry" I already knew you meant "I'm not angry". So how's that for communication? I guess that's also irony as well, because the literal meaning was the opposite of the actual meaning.
                • Bill
                   
                  Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
                  Re: How Scala Changed My Programming Style
                  May 1, 2009 2:47 PM      
                  > > I'm not sure why you thought I was suggesting you were
                  > > trying to say Scala isn't an improvement over Java. I
                  > > didn't get that impression. The "irony" I saw was that
                  > to
                  > > get at the benefits of the functional style in Java,
                  > Java
                  > > syntax actually pushed you in the other direction.
                  >
                  > I guess I get that impression because you keep telling
                  > about features of Scala when I already know Scala, or at
                  > least all the features you are talking about. Since I
                  > have tried to make that clear a couple times, it makes me
                  > think that you are not understanding me. I'm angry or
                  > anything, I'm just want to communicate effectively.
                  >
                  Sorry I wasn't sure how much of Scala you've seen, but also I'm telling others who are reading the discussion who aren't familiar with Scala. But mainly my irony comment was more about how I found it interesting that although you seem to have naturally stumbled upon some of the values that I only discovered when I went to Scala (like preferring little helper methods, avoiding vars, etc.), when trying to write that way in Java, it pushed you in a direction of multiple returns, the opposite direction it pushed me in Scala. The difference is in the language influence, I think. Because Java has mostly imperative control structures that don't result in a value, it makes it harder to
                  do the seeing methods as single expressions approach.

                  > > As far as using the boolean variable, that's not me
                  > being
                  > > unfair to Java. That's me being true to how I
                  > programmed
                  > > in Java for 10 years, and how I think most people
                  > program
                  > > in Java from the code I've seen over the years. That's
                  > the
                  > > idiom, and returning from inside a for loop, which you
                  > > showed, would I think be frowned upon by many Java
                  > > programmers.
                  >
                  > And again, this is exactly my point. It's not a feature
                  > of Java. It's something that people do in Java because
                  > think Java is like C. Given that Java is not really much
                  > like C, I fail to understand why it makes any more sense
                  > to use this idiom in Java than it does to use it in
                  > Scala.
                  >
                  Yes, some of it may be tradition, but how can you tell the difference between when people's preference is because they are used to that way, they were taught that way, etc., versus that they *really* feel that way.

                  > Are you saying that we must accept this as part of Java
                  > merely because some people say we should? If developers
                  > starting using this idiom in Scala does it become part of
                  > Scala?
                  >
                  > > Which rules to you mean? Sorry, can you be more
                  > explicit?
                  > > If you mean he rule of having just one return, that
                  > > doesn't quit add up because in Scala that's also the
                  > rule
                  > > of thumb, except that you see it as one expression that
                  > > doesn't need an explicit return.
                  >
                  > The source for List.exists() follows:
                  >
                  >   override def exists(p: A => Boolean): Boolean = {
                  >     var these = this
                  >     while (!these.isEmpty) {
                  >       if (p(these.head)) return true
                  >       these = these.tail
                  >     }
                  >     false
                  >   }
                  > 
                  

                  > Caveat: it's possible that the author of this method is
                  > not familiar with the idioms of Scala or of the single
                  > return rule of thumb in general.
                  >
                  Well, it was probably Martin who wrote that. That's a great example that ties everything together. Pretty impressive. Did you plan that or was it just a coincidence?

                  Anyway, I would say this is idiomatic Scala in the sense that one of the good reasons for using the imperative style is for performance. There are other good reasons. I think "Scala style" is lean towards functional by default, use imperative when you have a good reason and justification.

                  List needs to be fast, though I not sure why the while loop being used would be faster than a tail recursive loop that uses recursion, which would have gotten optimized into a a while loop in the binaries. I'm pretty sure it would be tail recursive. Anyway, once they picked the while approach, they would have returned out of the middle because there is no break in Scala. Either you return out of the middle, or you set the flag and keep looping to the end, or check the flat each time through the while loop. The fastest of these would be the return from the middle.
                  • James
                     
                    Posts: 128 / Nickname: watson / Registered: September 7, 2005 3:37 AM
                    Re: How Scala Changed My Programming Style
                    May 1, 2009 7:45 PM      
                    > Well, it was probably Martin who wrote that. That's a
                    > great example that ties everything together. Pretty
                    > impressive. Did you plan that or was it just a
                    > coincidence?

                    Just a coincidence, if you can believe it. Lucky for me it was the first thing I looked at.

                    Honestly, I feel bad for taking this so off-topic. As someone else pointed out, there are probably better uses of my time.
    • Javier
       
      Posts: 1 / Nickname: javierbds / Registered: September 5, 2005 8:13 PM
      Re: How Scala Changed My Programming Style
      May 8, 2009 9:11 AM      
      Because Java never used multiple returns ...
       
      public boolean equals(Object anObject) {
      if (this == anObject) {
      return true;
      }
      if (anObject instanceof String) {
      String anotherString = (String)anObject;
      int n = count;
      if (n == anotherString.count) {
      char v1[] = value;
      char v2[] = anotherString.value;
      int i = offset;
      int j = anotherString.offset;
      while (n-- != 0) {
      if (v1[i++] != v2[j++])
      return false;
      }
      return true;
      }
      }
      return false;
      }
    • Oliver
       
      Posts: 1 / Nickname: oliplow / Registered: December 6, 2012 8:13 PM
      Re: How Scala Changed My Programming Style
      February 15, 2013 1:25 AM      
      You can do this

      name.exists(_.isUpperCase)

      in every language that supports closures like Ruby, Groovy, Go, JDK8, Kotlin, etc. In Smalltalk this would be something like this:

      name contains: [ :each | each isUpper]

      And I have never heard any Smalltalk developer calling this functional programming style. Calling simple use of closures functional programming only causes confusion.
    • Wiegers
       
      Posts: 1 / Nickname: wiegers325 / Registered: October 15, 2018 1:27 AM
      Re: How Scala Changed My Programming Style
      November 26, 2018 11:47 PM      
      Having a single return point is structured -- which gives a simple, uniformity of shape (check: ‘Notes On Structured Programming’/ewd249; Dijkstra; 1970). It should be the default, unless the code can be made even simpler otherwise.

      I rate Scala even more compact than Ruby and Python: 86% of the size to be exact! (45% of C++) for full code.

      Scala struck just right balance with its type inference, that is: types stated explicitly at function parameters, but not needed elsewhere. OCaml doesn't require them at function parameters, but it is sometimes hard to make it compile -- each time you try to fix it, the error messages change because it infers from a different point.

      OCaml changed me a bit earlier, but that prepared me for immediately liking Scala.
      • Jason
         
        Posts: 1 / Nickname: jason312 / Registered: November 29, 2018 2:44 AM
        Re: How Scala Changed My Programming Style
        November 29, 2018 2:45 AM      
        > Having a single return point is structured -- which gives
        > a simple, uniformity of shape (check: ‘Notes On Structured
        > Programming’/ewd249; Dijkstra; 1970). It should be the
        > default, unless the code can be made even simpler
        > otherwise.
        >
        > I rate Scala even more compact than Ruby and Python: 86%
        > of the size to be exact! (45% of C++) for full code.
        >
        > Scala struck just right balance with its type inference,
        > that is: types stated explicitly at function parameters,
        > but not needed elsewhere. OCaml doesn't require them at
        > function parameters, but it is sometimes hard to make it
        > compile -- each time you try to fix it, the error messages
        > change because it infers from a different point.
        >
        > OCaml changed me a bit earlier, but that prepared me for
        > immediately liking Scala.

        Just a coincidence, if you can believe it. Lucky for me it was the first thing I looked at here.

        Honestly, I feel bad for taking this so off-topic. As someone else pointed out, there are probably better uses of my time.