Holy boop: goto for Java

  • Follow


Just looking for an extended answer to an earlier question (strings in a 
case-switch statement), I found this on Joe Darcy's blog:

"Summary

"Provide the benefits of the time-testing goto control structure to Java 
programs. The Java language has a history of adding new control 
structures over time, the assert statement in 1.4, the enhanced for-loop 
in 1.5,and try-with-resources in 7. Having support for goto is 
long-overdue and simple to implement since the JVM already has goto 
instructions."

<https://blogs.oracle.com/darcy/entry/upcoming_jep>

Holy booping bat boop Batman!

0
Reply markspace 6/4/2012 2:36:53 AM

On 6/3/12 7:36 PM, markspace wrote:
> Just looking for an extended answer to an earlier question (strings in a
> case-switch statement), I found this on Joe Darcy's blog:
>
> "Summary
>
> "Provide the benefits of the time-testing goto control structure to Java
> programs. The Java language has a history of adding new control
> structures over time, the assert statement in 1.4, the enhanced for-loop
> in 1.5,and try-with-resources in 7. Having support for goto is
> long-overdue and simple to implement since the JVM already has goto
> instructions."
>
> <https://blogs.oracle.com/darcy/entry/upcoming_jep>
>
> Holy booping bat boop Batman!
>
Check the date of that article before getting to excited/disappointed ;-)
0
Reply newsgroup.nospam (530) 6/4/2012 3:03:30 AM


On 6/3/2012 8:03 PM, Daniel Pitts wrote:
> Check the date of that article before getting to excited/disappointed ;-)


Ah.  Somebody got me good, I think.

0
Reply markspace 6/4/2012 3:30:02 AM

markspace wrote:
> Daniel Pitts wrote:
>> Check the date of that article before getting to excited/disappointed ;-)
>
> Ah. Somebody got me good, I think.

In a highly limited, controlled and presumably blessed-for-object-oriented 
way, Java does have a version of "goto", in its 'break' and 'continue' 
statements. You can't just jump anywhere, but you can jump to labels, with 
restrictions.

I have never seen a use of Java's labeled 'break' or 'continue' outside of 
tutorials and examples, though.

The full, unbridled "goto" doesn't exist in Java except for the keyword 
'goto', whose head is mounted on a pike at the language's gates as a warning.

-- 
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg
0
Reply noone7 (3512) 6/4/2012 4:17:56 AM

On Sun, 03 Jun 2012 19:36:53 -0700, markspace <-@.> wrote, quoted or
indirectly quoted someone who said :

>"Provide the benefits of the time-testing goto control structure to Java 
>programs. 

People take a rule of thumb and turn it into a commandment from a
vicious god.

I remember back in the early 90s  in C  demonstrating how a common
pattern could be implemented with a goto. The boss insisted on a
goto-less implementation that was many times more verbose.  NORMALLY
GoTos make for more tangled code. This time it did not.

Parser generators are simpler if they can generate gotos. Nobody is
supposed to even look at the code.

As a general rule, you don't want them. A team leader would want
members to get permission to use one.
-- 
Roedy Green Canadian Mind Products
http://mindprod.com
Controlling complexity is the essence of computer programming.
~ Brian W. Kernighan 1942-01-01
..
0
Reply see_website (4858) 6/4/2012 5:10:19 AM

On 04.06.2012 06:17, Lew wrote:
> The full, unbridled "goto" doesn't exist in Java except for the keyword
> 'goto', whose head is mounted on a pike at the language's gates as a
> warning.

I'll print that and put it on our office door.  Thanks for that, Lew!

Chuckle...

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
0
Reply shortcutter (5766) 6/4/2012 5:56:17 AM

On 12-06-04 01:17 AM, Lew wrote:
> markspace wrote:
>> Daniel Pitts wrote:
>>> Check the date of that article before getting to excited/disappointed
>>> ;-)
>>
>> Ah. Somebody got me good, I think.
>
> In a highly limited, controlled and presumably
> blessed-for-object-oriented way, Java does have a version of "goto", in
> its 'break' and 'continue' statements. You can't just jump anywhere, but
> you can jump to labels, with restrictions.
>
> I have never seen a use of Java's labeled 'break' or 'continue' outside
> of tutorials and examples, though.
>
> The full, unbridled "goto" doesn't exist in Java except for the keyword
> 'goto', whose head is mounted on a pike at the language's gates as a
> warning.
>
I use labeled break/continue occasionally. I see a lot of advice on 
programming forums like StackOverflow that says never use them. Typical 
dogmatic advice is that you should extract inner-loop code into methods 
and use boolean return codes to make a top-level break/continue decision.

What amazes me is that these individuals support this religious stance 
by arguing that it improves readability, when producing little auxiliary 
methods usually does anything but.

The combination of conditions that would indicate a labeled 
break/continue is clear:

1. A loop;
2. A condition in that loop that could lead to a break or continue for it;
3. That condition is itself a loop. Furthermore, the logic in the loop 
is probably coupled to the logic in the rest of the main loop.

To the degree that the logic in that inner loop makes (no) sense as a 
standalone method - size, understandability on its own etc - is the 
decision process I follow as to whether a labeled break/continue is 
advisable.

In any case, Lew, I don't see that this has much to do with "blessed for 
OO". We're talking imperative coding here, which is what Java 
programmers spend the majority of their time doing.

AHS
-- 
Never interrupt your enemy when he is making a mistake.
--Napoleon
0
Reply asandstrom3minus1 (421) 6/4/2012 7:28:13 AM

On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
> What amazes me is that these individuals support this religious stance=20
> by arguing that it improves readability, when producing little auxiliary=
=20
> methods usually does anything but.

I am not religious about break / continue (although I use it extremely seld=
om, I am more likely to use "return" inside a loop).  But I disagree about =
your general statement about little auxiliary methods usually not improving=
 readability.  It all depends on the specific case, of course, but giving a=
 short part of an algorithm a name (with the option to have a place to put =
JavaDoc) often helps readability in my experience.

Kind regards

robert
0
Reply shortcutter (5766) 6/4/2012 7:37:20 AM

On 6/4/2012 12:17 AM, Lew wrote:
> I have never seen a use of Java's labeled 'break' or 'continue' outside
> of tutorials and examples, though.

If you translate some of the examples in Knuth's retort "The use of GOTO 
in structured programming" to Java, you'd find yourself using labeled 
break/continue. I've used it a fair amount in nested loops.

-- 
Beware of bugs in the above code; I have only proved it correct, not 
tried it. -- Donald E. Knuth
0
Reply Pidgeot18 (1393) 6/4/2012 11:26:23 AM

On 6/3/2012 11:03 PM, Daniel Pitts wrote:
> On 6/3/12 7:36 PM, markspace wrote:
>> Just looking for an extended answer to an earlier question (strings in a
>> case-switch statement), I found this on Joe Darcy's blog:
>>
>> "Summary
>>
>> "Provide the benefits of the time-testing goto control structure to Java
>> programs. The Java language has a history of adding new control
>> structures over time, the assert statement in 1.4, the enhanced for-loop
>> in 1.5,and try-with-resources in 7. Having support for goto is
>> long-overdue and simple to implement since the JVM already has goto
>> instructions."
>>
>> <https://blogs.oracle.com/darcy/entry/upcoming_jep>
>>
>> Holy booping bat boop Batman!
>>
> Check the date of that article before getting to excited/disappointed ;-)

When I first saw that article, I got as far as posting it in an IRC 
channel [without context] before I realized it was an joke. Fortunately, 
I realized the joke before any discussion started up around it :-P .

-- 
Beware of bugs in the above code; I have only proved it correct, not 
tried it. -- Donald E. Knuth
0
Reply Pidgeot18 (1393) 6/4/2012 11:28:08 AM

On 6/4/12 12:37 AM, Robert Klemme wrote:
> On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
>> What amazes me is that these individuals support this religious stance
>> by arguing that it improves readability, when producing little auxiliary
>> methods usually does anything but.
>
> I am not religious about break / continue (although I use it extremely seldom, I am more likely to use "return" inside a loop).  But I disagree about your general statement about little auxiliary methods usually not improving readability.  It all depends on the specific case, of course, but giving a short part of an algorithm a name (with the option to have a place to put JavaDoc) often helps readability in my experience.
+1

I rarely have methods that are more than 10 lines long anymore, thanks 
to "Extract Method" and other refactorings. This sort of goes along with 
"self-documenting" code.  Now granted, someone could start naming these 
auxiliary methods in such a way to be contrary to the goal of 
readability, but that's just bad programming.  I find a well named 
method often removes a hastily written comment. For example:

---
while (isYSquibled()) {...}
---

versus

---
//Loop while x squibles y.
while (x == null || y.canBeSquibledBy(x)) {...}
---

Another thing I've noticed is that programmers are less likely to change 
the method to do something-else without renaming the method, but are 
more likely to forget or ignore comments explaining what a single line 
does.
0
Reply newsgroup.nospam (530) 6/4/2012 2:43:22 PM

Lew wrote:
> I have never seen a use of Java's labeled 'break' or 'continue'
> outside of tutorials and examples, though.
>
I've very occasionally found them useful, but they are on the list of things 
I wouldn't miss if they were gone.  Others:

* Do-while.  It seems almost never to be what's needed.  Though I do quite 
often need

  while(true)
  {
   stuff
    if (condition)
    {
      break;
    }
    more stuff
  }

* Local classes (i.e. named classes defined inside a method)
* The non-short-circuit logical operators & and | 


0
Reply mscottschilling (1976) 6/4/2012 2:44:36 PM

Daniel Pitts wrote:
>
> Another thing I've noticed is that programmers are less likely to
> change the method to do something-else without renaming the method,
> but are more likely to forget or ignore comments explaining what a
> single line does.

y = 12; // set Y to 10 


0
Reply mscottschilling (1976) 6/4/2012 2:47:16 PM

"Mike Schilling" <mscottschilling@hotmail.com> writes:
>y = 12; // set Y to 10 

  y = 012; // set y to 10

0
Reply ram (2827) 6/4/2012 3:03:54 PM

"Stefan Ram" <ram@zedat.fu-berlin.de> wrote in message 
news:012-20120604170339@ram.dialup.fu-berlin.de...
> "Mike Schilling" <mscottschilling@hotmail.com> writes:
>>y = 12; // set Y to 10
>
>  y = 012; // set y to 10
>

Nice.  It's like the proof that Halloween equals Christmas

    Dec 25 == Oct 31 


0
Reply mscottschilling (1976) 6/4/2012 3:17:46 PM

On 04.06.2012 16:44, Mike Schilling wrote:
> Lew wrote:
>> I have never seen a use of Java's labeled 'break' or 'continue'
>> outside of tutorials and examples, though.
>>
> I've very occasionally found them useful, but they are on the list of things
> I wouldn't miss if they were gone.  Others:
>
> * Do-while.  It seems almost never to be what's needed.  Though I do quite
> often need
>
>    while(true)
>    {
>     stuff
>      if (condition)
>      {
>        break;
>      }
>      more stuff
>    }

Interesting: I cannot remember having needed this.  While I do remember 
using do {} while.  What use cases do you have for the construct above?

> * Local classes (i.e. named classes defined inside a method)

+1

> * The non-short-circuit logical operators&  and |

+1

Kind regards

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
0
Reply shortcutter (5766) 6/4/2012 4:13:00 PM

Arved Sandstrom wrote:
> In any case, Lew, I don't see that this has much to do with "blessed for=
=20
> OO". We're talking imperative coding here, which is what Java=20
> programmers spend the majority of their time doing.

That was rather my point. I should have remembered to include a smiley with=
 that comment.

Java culture rests on the axiom that Java is an object-oriented language.  =
So if something is built into the language, a circular (and therefore obvio=
usly flawed) argument would encourage the sort of foolish remark I made. Ex=
amining the foolishness leads to exactly what you said.

So, belatedly, :-)

--=20
Lew
0
Reply lewbloch (1312) 6/4/2012 4:33:10 PM

On Mon, 04 Jun 2012 18:13:00 +0200, Robert Klemme
<shortcutter@googlemail.com> wrote:

>On 04.06.2012 16:44, Mike Schilling wrote:
>> Lew wrote:
>>> I have never seen a use of Java's labeled 'break' or 'continue'
>>> outside of tutorials and examples, though.
>>>
>> I've very occasionally found them useful, but they are on the list of things
>> I wouldn't miss if they were gone.  Others:
>>
>> * Do-while.  It seems almost never to be what's needed.  Though I do quite
>> often need
>>
>>    while(true)
>>    {
>>     stuff
>>      if (condition)
>>      {
>>        break;
>>      }
>>      more stuff
>>    }
>
>Interesting: I cannot remember having needed this.  While I do remember 
>using do {} while.  What use cases do you have for the construct above?

     In the sense that there are other ways one can do this, no, you
do not need this.  It can be useful if you have multiple tests in that
loop, especially multiple tests that cannot be combined.  An example
of this would be a body of:
          process first piece
          if error
             break or continue as needed
          process middle piece
          if error
             break or continue as needed
          process last piece

[snip]

Sincerely,

Gene Wirchenko
0
Reply genew (1191) 6/4/2012 5:23:35 PM

Gene Wirchenko wrote:
> Robert Klemme wrote:
>> Mike Schilling wrote:
>>> * Do-while.  It seems almost never to be what's needed.  Though I do quite
>>> often need
>>>
>>>    while(true)
>>>    {
>>>     stuff
>>>      if (condition)
>>>      {
>>>        break;
>>>      }
>>>      more stuff
>>>    }
>>
>> Interesting: I cannot remember having needed this.  While I do remember 
>> using do {} while.  What use cases do you have for the construct above?
> 
>      In the sense that there are other ways one can do this, no, you
> do not need this.  It can be useful if you have multiple tests in that
> loop, especially multiple tests that cannot be combined.  An example
> of this would be a body of:
>           process first piece
>           if error
>              break or continue as needed
>           process middle piece
>           if error
>              break or continue as needed
>           process last piece
> 
> [snip]

public void processResources(String ... resourceNames)
{
  for (String name : resourceNames)
  {
    BufferedReader br;
    try 
    {
      br = new BufferedReader(new FileReader(name));
    }
    catch(FileNotFoundException exc)
    {
      logger.error("Cannot find "+ name, exc);
      continue;
    }
    assert br != null; // and is valid
    try
    {
      doSomething(br);
    }
    finally
    {
      try
      {
        br.close();
      }
      catch(IOException exc)
      {
        logger.error("Cannot close "+ name, exc);
        continue;
      }
    }
    reportComplete(name);
  }
}

(Not using try-with-resources here, in order to illustrate the idiom.)

-- 
Lew
0
Reply lewbloch (1312) 6/4/2012 5:45:58 PM

On 6/4/12 7:44 AM, Mike Schilling wrote:
> Lew wrote:
>> I have never seen a use of Java's labeled 'break' or 'continue'
>> outside of tutorials and examples, though.
>>
> I've very occasionally found them useful, but they are on the list of things
> I wouldn't miss if they were gone.  Others:
>
> * Do-while.  It seems almost never to be what's needed.  Though I do quite
> often need
>
>    while(true)
>    {
>     stuff
>      if (condition)
>      {
>        break;
>      }
>      more stuff
>    }
>
> * Local classes (i.e. named classes defined inside a method)
> * The non-short-circuit logical operators&  and |
>
>

I've seen that loop refactored to:

stuff();
while (!condition) {
   moreStuff();
   stuff();
}


Or:

for (stuff(); !condition; stuff() {
   moreStuff();
}


Not saying that is better, just saying I've seen it.
0
Reply newsgroup.nospam (530) 6/4/2012 5:50:19 PM

On 6/4/12 7:44 AM, Mike Schilling wrote:
> Lew wrote:
>> I have never seen a use of Java's labeled 'break' or 'continue'
>> outside of tutorials and examples, though.
>>
> I've very occasionally found them useful, but they are on the list of things
> I wouldn't miss if they were gone.  Others:
[snip]
> * Local classes (i.e. named classes defined inside a method)
Holy unknown construct Batman!  I had no idea this was possible, and I 
definitely would have used in in certain places!

Specifically, for callbacks where I need to set values to be retrieved 
after the call.


void doSomething(SomethingSomething something) {
   class MyCallback implements SomeCallbackInterface {
     int calls;
     boolean error;


     public void somethingCalled() { ++calls; }
     public void somethingErrored() { error = true; }
   }

    MyCallback cb = new MyCallback();

    something.doSomethingwith(cb);
    if (error) {
       handleError();
    }
    if (cb.calls < 100) { smallBatch(); } else { largeBatch(); }
}


For example.

I have often instead created private static inner classes for this 
purpose, but that pollutes the class IMO.

0
Reply newsgroup.nospam (530) 6/4/2012 5:56:53 PM

Mike Schilling <mscottschilling@hotmail.com> wrote:
>
> * The non-short-circuit logical operators & and | 

There's an argument that we should prefer the 
non-short-circuit versions (of course, only where
performance or program logic doesn't dictate the 
short-circuit operators) as this reduces the number
of paths in the code and makes the program behaviour
more consistent (particularly in time) which helps 
with debugging.

Of course, for Java I think that ship has sailed. The use
of the non-short-circuit operators is so rare that to use
them is to ask for your code to be misinterpreted by 
others.

-- 
Leif Roar Moldskred

0
Reply leifm1143 (162) 6/4/2012 6:05:15 PM

On 04.06.2012 19:45, Lew wrote:
> public void processResources(String ... resourceNames)
> {
....

I'd rather

public void processResources(String ... resourceNames)
{
   for (String name : resourceNames)
   {
     try
     {
       final BufferedReader br =
         new BufferedReader(new FileReader(name));
       try
       {
         doSomething(br);
         reportComplete(name);
       }
       catch(IOException exc)
       {
         logger.error("Issue while processing "+ name, exc);
       }
       finally
       {
         close(br);
       }
     }
     catch(FileNotFoundException exc)
     {
       logger.error("Cannot find "+ name, exc);
     }
   }
}

close() is a static helper method which catches IOException and reports it.

In other words, I try to place the catch block at the end of a logical 
section and use try catch to only execute some commands in absence of 
error.  The exception will make the continue superfluous.  The advantage 
in my eyes is that you can easily follow the regular flow and have error 
handling concentrated in one place.  I sometimes even refactor out 
methods so I can have this catch at the end idiom.

In a more realistic example I'd probably extract parts of this into a 
method (likely the inner try catch finally).

Kind regards

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
0
Reply shortcutter (5766) 6/4/2012 6:31:30 PM

On 6/4/12 10:45 AM, Lew wrote:
> Gene Wirchenko wrote:
>> Robert Klemme wrote:
>>> Mike Schilling wrote:
>>>> * Do-while.  It seems almost never to be what's needed.  Though I do quite
>>>> often need
>>>>
>>>>     while(true)
>>>>     {
>>>>      stuff
>>>>       if (condition)
>>>>       {
>>>>         break;
>>>>       }
>>>>       more stuff
>>>>     }
>>>
>>> Interesting: I cannot remember having needed this.  While I do remember
>>> using do {} while.  What use cases do you have for the construct above?
>>
>>       In the sense that there are other ways one can do this, no, you
>> do not need this.  It can be useful if you have multiple tests in that
>> loop, especially multiple tests that cannot be combined.  An example
>> of this would be a body of:
>>            process first piece
>>            if error
>>               break or continue as needed
>>            process middle piece
>>            if error
>>               break or continue as needed
>>            process last piece
>>
>> [snip]
>
> public void processResources(String ... resourceNames)
> {
>    for (String name : resourceNames)
>    {
>      BufferedReader br;
>      try
>      {
>        br = new BufferedReader(new FileReader(name));
FWIW, this is a potential resource leak (think OOM on the "new 
BufferedReader")
>      }
>      catch(FileNotFoundException exc)
>      {
>        logger.error("Cannot find "+ name, exc);
>        continue;
>      }
>      assert br != null; // and is valid
br is never assigned null, you could make br final.  I think it *should* 
be final.

>      try
>      {
>        doSomething(br);
>      }
>      finally
>      {
>        try
>        {
>          br.close();
>        }
>        catch(IOException exc)
>        {
>          logger.error("Cannot close "+ name, exc);
>          continue;
>        }
>      }
>      reportComplete(name);
>    }
> }
>
> (Not using try-with-resources here, in order to illustrate the idiom.)
>

Hmm, a failure to close causes a resource processing not to be complete?
0
Reply newsgroup.nospam (530) 6/4/2012 6:52:52 PM

Daniel Pitts <newsgroup.nospam@virtualinfinity.net> wrote:

> FWIW, this is a potential resource leak (think OOM on the "new 
> BufferedReader")

In the same sense that the loud BANG from a handgrenade is a 
health-and-safety hazard: if one goes off next to your ear you 
might go deaf.

If you get an OutOfMemory exception on the "new BufferedReader"
bit, you're already fubar and a dangling file-handle more or 
less isn't going to affect the situation any.

-- 
Leif Roar Moldskred
0
Reply leifm1143 (162) 6/4/2012 7:15:32 PM

On 12-06-04 04:37 AM, Robert Klemme wrote:
> On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
>> What amazes me is that these individuals support this religious stance
>> by arguing that it improves readability, when producing little auxiliary
>> methods usually does anything but.
>
> I am not religious about break / continue (although I use it extremely seldom, I am more likely to use "return" inside a loop).  But I disagree about your general statement about little auxiliary methods usually not improving readability.  It all depends on the specific case, of course, but giving a short part of an algorithm a name (with the option to have a place to put JavaDoc) often helps readability in my experience.
>
> Kind regards
>
> robert

When I mean "little", I mean little - like 2 or 3 lines little. Based on 
the "no exceptions NEVER use labeled break/continue" language that I've 
seen in threads on this subject, and the invariable suggestion of using 
extracted helper methods instead, this *inevitably* means that many of 
these helper methods will be that small. After all, the body of such a 
method would be whatever the body of the inner loop is, and in my 
experience that's often small.

I am not super-dogmatic about many things, but one thing I will not 
yield ground on is the readability hit of little (1-3 lines of Java) 
methods. *Sometimes*, with a well-chosen name, and general 
applicability, these are perfectly OK. But these idiots in these threads 
I allude to are talking about extracting all code in an inner loop, if 
it would require a conditional break or continue, robotically making a 
method out of it - even if that outer loop is the only caller - without 
any intelligent thought whatsoever.

Can you imagine what kind of names such methods might have? How about 
"innerLoopStuff()"?

AHS

-- 
Never interrupt your enemy when he is making a mistake.
--Napoleon
0
Reply asandstrom3minus1 (421) 6/4/2012 8:07:12 PM

On 6/4/12 1:07 PM, Arved Sandstrom wrote:
> On 12-06-04 04:37 AM, Robert Klemme wrote:
>> On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
>>> What amazes me is that these individuals support this religious stance
>>> by arguing that it improves readability, when producing little auxiliary
>>> methods usually does anything but.
>>
>> I am not religious about break / continue (although I use it extremely
>> seldom, I am more likely to use "return" inside a loop). But I
>> disagree about your general statement about little auxiliary methods
>> usually not improving readability. It all depends on the specific
>> case, of course, but giving a short part of an algorithm a name (with
>> the option to have a place to put JavaDoc) often helps readability in
>> my experience.
>>
>> Kind regards
>>
>> robert
>
> When I mean "little", I mean little - like 2 or 3 lines little. Based on
> the "no exceptions NEVER use labeled break/continue" language that I've
> seen in threads on this subject, and the invariable suggestion of using
> extracted helper methods instead, this *inevitably* means that many of
> these helper methods will be that small. After all, the body of such a
> method would be whatever the body of the inner loop is, and in my
> experience that's often small.
>
> I am not super-dogmatic about many things, but one thing I will not
> yield ground on is the readability hit of little (1-3 lines of Java)
> methods. *Sometimes*, with a well-chosen name, and general
> applicability, these are perfectly OK. But these idiots in these threads
> I allude to are talking about extracting all code in an inner loop, if
> it would require a conditional break or continue, robotically making a
> method out of it

No need to call me an idiot. Actually, I don't advocate "extracting all 
code in an inner loop, if it would require a conditional break or 
continue".  I advocate distinct intuitive steps into simple methods, 
always, unless you have a specific reason not to.  A good reason, not 
just any reason.

Many experts in the field of software design agree. I learned this 
practice directly from Martin Fowler as a matter of fact, in a training 
session he did on TDD at my company.

> - even if that outer loop is the only caller -
Who calls a method is irrelevant to only value of such a method, unless 
the number of callers is zero of course.
> without any intelligent thought whatsoever.
Intelligent thought is always required, for all software design. The 
problem is when people do things by guessing.
>
> Can you imagine what kind of names such methods might have? How about
> "innerLoopStuff()"?
It depends on the loop. How about instead "processNextStuff()" (where 
stuff is replaced with a meaningful name).

I'm not going to say "It must always be done!" but I will say that when 
done *right*, it will improve the maintainability of the code base 
significantly.

Thanks,
Daniel
Yet Another Idiot Apparently.
0
Reply newsgroup.nospam (530) 6/4/2012 8:17:21 PM

On Mon, 04 Jun 2012 13:17:21 -0700, Daniel Pitts
<newsgroup.nospam@virtualinfinity.net> wrote:

>On 6/4/12 1:07 PM, Arved Sandstrom wrote:
>> On 12-06-04 04:37 AM, Robert Klemme wrote:
>>> On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
>>>> What amazes me is that these individuals support this religious stance
>>>> by arguing that it improves readability, when producing little auxiliary
>>>> methods usually does anything but.

     Personally, I find this sort of stuff to be very unreadable.  If
it is used multiple times, it is not quite so bad.  If it is used but
once, it is a disruption to following the caller.

>>> I am not religious about break / continue (although I use it extremely
>>> seldom, I am more likely to use "return" inside a loop). But I
>>> disagree about your general statement about little auxiliary methods
>>> usually not improving readability. It all depends on the specific
>>> case, of course, but giving a short part of an algorithm a name (with
>>> the option to have a place to put JavaDoc) often helps readability in
>>> my experience.

>> When I mean "little", I mean little - like 2 or 3 lines little. Based on
>> the "no exceptions NEVER use labeled break/continue" language that I've
>> seen in threads on this subject, and the invariable suggestion of using
>> extracted helper methods instead, this *inevitably* means that many of
>> these helper methods will be that small. After all, the body of such a
>> method would be whatever the body of the inner loop is, and in my
>> experience that's often small.

     There is also context to consider.  I have sometimes considered
moving some short, common code to subroutines to find that by the time
I re-established the context in the subroutine, the subroutine's code
would be longer than having the code in the caller.

>> I am not super-dogmatic about many things, but one thing I will not
>> yield ground on is the readability hit of little (1-3 lines of Java)
>> methods. *Sometimes*, with a well-chosen name, and general
>> applicability, these are perfectly OK. But these idiots in these threads
>> I allude to are talking about extracting all code in an inner loop, if
>> it would require a conditional break or continue, robotically making a
>> method out of it

     That is extreme.

>No need to call me an idiot. Actually, I don't advocate "extracting all 
>code in an inner loop, if it would require a conditional break or 
>continue".  I advocate distinct intuitive steps into simple methods, 
>always, unless you have a specific reason not to.  A good reason, not 
>just any reason.

     You are talking past each other.  He is not talking about
intuitive steps, but just automatic "methodising" of code.

>Many experts in the field of software design agree. I learned this 
>practice directly from Martin Fowler as a matter of fact, in a training 
>session he did on TDD at my company.
>
>> - even if that outer loop is the only caller -
>Who calls a method is irrelevant to only value of such a method, unless 
>the number of callers is zero of course.

     If it is only one, in-line might be better.

>> without any intelligent thought whatsoever.
>Intelligent thought is always required, for all software design. The 
>problem is when people do things by guessing.

     Or by manifesto which is much the same.

>> Can you imagine what kind of names such methods might have? How about
>> "innerLoopStuff()"?
>It depends on the loop. How about instead "processNextStuff()" (where 
>stuff is replaced with a meaningful name).

     innerLoopStuff2(), innerLoopStuff3(), ... ?

>I'm not going to say "It must always be done!" but I will say that when 
>done *right*, it will improve the maintainability of the code base 
>significantly.

     But then it probably would be done as the code is written,
because it is a sensible -- what you called "intuitive" above --
design.

     I like my code to tell a story at one level of abstraction.  It
makes it easier to follow the logic.  The high-level code is all in
one sequence.  With this, I can skip the lower-level logic most of the
time.  If I need to adjust the higher-level logic, it is a good sign
when I do not have to concern myself much with the lower-level logic
(because what I came up with for it is still what is needed).

>Thanks,
>Daniel
>Yet Another Idiot Apparently.

     Nope.  You are too thoughtful for that.

Sincerely,

Gene Wirchenko
0
Reply genew (1191) 6/4/2012 9:46:03 PM

Daniel Pitts wrote:
> Lew wrote:
>> public void processResources(String ... resourceNames)
>> {
>>    for (String name : resourceNames)
>>    {
>>      BufferedReader br;
>>      try
>>      {
>>        br = new BufferedReader(new FileReader(name));

> FWIW, this is a potential resource leak (think OOM on the "new 
> BufferedReader")

OOM is not a resource leak, it's a program crash.

I generally don't handle 'Error's. (Except when I do.) 
If the OOM happens here as you suggest, well, what Leif said.

> >      }
> >      catch(FileNotFoundException exc)
> >      {
> >        logger.error("Cannot find "+ name, exc);
> >        continue;
> >      }
> >      assert br != null; // and is valid

> br is never assigned null, you could make br final.  I think it *should* 
> be final.

Yes. Actually, in real code with this idiom I do make it final. Good catch.

> >      try
> >      {
> >        doSomething(br);
> >      }
> >      finally
> >      {
> >        try
> >        {
> >          br.close();
> >        }
> >        catch(IOException exc)
> >        {
> >          logger.error("Cannot close "+ name, exc);
> >          continue;
> >        }
> >      }
> >      reportComplete(name);
> >    }
> > }
> >
> > (Not using try-with-resources here, in order to illustrate the idiom.)
> >
> 
> Hmm, a failure to close causes a resource processing not to be complete?

You read too much into the method names.

It's a pattern. I do not claim the names and all are useful in real life, only for pedagogy.

Use better names if these make you twitch.

-- 
Lew
0
Reply lewbloch (1312) 6/4/2012 9:52:00 PM

On 04.06.2012 23:46, Gene Wirchenko wrote:
> On Mon, 04 Jun 2012 13:17:21 -0700, Daniel Pitts
> <newsgroup.nospam@virtualinfinity.net>  wrote:
>
>> On 6/4/12 1:07 PM, Arved Sandstrom wrote:
>>> On 12-06-04 04:37 AM, Robert Klemme wrote:
>>>> On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
>>>>> What amazes me is that these individuals support this religious stance
>>>>> by arguing that it improves readability, when producing little auxiliary
>>>>> methods usually does anything but.
>
>       Personally, I find this sort of stuff to be very unreadable.  If
> it is used multiple times, it is not quite so bad.  If it is used but
> once, it is a disruption to following the caller.

Hmm, but with that argument you must put everything in one method - what 
you clearly do not do as your later comments show. :-)

>       There is also context to consider.  I have sometimes considered
> moving some short, common code to subroutines to find that by the time
> I re-established the context in the subroutine, the subroutine's code
> would be longer than having the code in the caller.

Right.  Or if argument lists get too long that is also a good sign that 
something is wrong.

>       I like my code to tell a story at one level of abstraction.

That's an interesting way to put it.  And it hits the nail on the head.

> It makes it easier to follow the logic.  The high-level code is all in
> one sequence.  With this, I can skip the lower-level logic most of the
> time.  If I need to adjust the higher-level logic, it is a good sign
> when I do not have to concern myself much with the lower-level logic
> (because what I came up with for it is still what is needed).

Right!  That discussion nicely shows why it still needs humans to write 
software: the process of cutting algorithms in parts cannot be easily 
automated.  One reason for that is that we do not write for machines 
(which easily cope with the most contrived code as long as it compiles) 
but rather for humans - namely the one who comes after us and has to fix 
a bug or add a feature.

Kind regard

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
0
Reply shortcutter (5766) 6/5/2012 5:31:44 AM

On Tue, 05 Jun 2012 07:31:44 +0200, Robert Klemme
<shortcutter@googlemail.com> wrote:

>On 04.06.2012 23:46, Gene Wirchenko wrote:
>> On Mon, 04 Jun 2012 13:17:21 -0700, Daniel Pitts
>> <newsgroup.nospam@virtualinfinity.net>  wrote:
>>
>>> On 6/4/12 1:07 PM, Arved Sandstrom wrote:
>>>> On 12-06-04 04:37 AM, Robert Klemme wrote:
>>>>> On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
>>>>>> What amazes me is that these individuals support this religious stance
>>>>>> by arguing that it improves readability, when producing little auxiliary
>>>>>> methods usually does anything but.
>>
>>       Personally, I find this sort of stuff to be very unreadable.  If
>> it is used multiple times, it is not quite so bad.  If it is used but
>> once, it is a disruption to following the caller.
>
>Hmm, but with that argument you must put everything in one method - what 
>you clearly do not do as your later comments show. :-)

     NO!  Pulling some code out to make it a method that is called
ONLY ONCE is what I object to.  (I might do it if there is
clearly-delineated functionality that could be useful again (but just
happens to be needed but once when it written)).  I will not do it for
some manifesto.

>>       There is also context to consider.  I have sometimes considered
>> moving some short, common code to subroutines to find that by the time
>> I re-established the context in the subroutine, the subroutine's code
>> would be longer than having the code in the caller.
>
>Right.  Or if argument lists get too long that is also a good sign that 
>something is wrong.

     Yes.  I should have included length of calling sequence.

>>       I like my code to tell a story at one level of abstraction.
>
>That's an interesting way to put it.  And it hits the nail on the head.

     I hit on it several years ago.  Many of my programs or large
segments have one story with the rest of the methods/subroutines
supporting it.  A consequence of this is that some of my methods can
get rather long (ones that tell a story).

>> It makes it easier to follow the logic.  The high-level code is all in
>> one sequence.  With this, I can skip the lower-level logic most of the
>> time.  If I need to adjust the higher-level logic, it is a good sign
>> when I do not have to concern myself much with the lower-level logic
>> (because what I came up with for it is still what is needed).
>
>Right!  That discussion nicely shows why it still needs humans to write 
>software: the process of cutting algorithms in parts cannot be easily 
>automated.  One reason for that is that we do not write for machines 
>(which easily cope with the most contrived code as long as it compiles) 
>but rather for humans - namely the one who comes after us and has to fix 
>a bug or add a feature.

     Which is often us so being nice to the maintenance programmer is
being nice to oneself.

     Besides the story paradigm, I also think in terms of program
usefulness.  If a program is not very useful, one can write it pretty
much any way one wants as the program is going to get tossed anyway.
If it is useful, then it is going to stick around, and requirements
have a way of changing so the program had better be maintainable.  It
can also be difficult to tell whether a program will be useful so why
not just write them all clearly?

Sincerely,

Gene Wirchenko
0
Reply genew (1191) 6/5/2012 4:15:02 PM

On 6/5/12 9:15 AM, Gene Wirchenko wrote:
>       NO!  Pulling some code out to make it a method that is called
> ONLY ONCE is what I object to.  (I might do it if there is
> clearly-delineated functionality that could be useful again (but just
> happens to be needed but once when it written)).  I will not do it for
> some manifesto.

Code re-usability is the great lie that has become the manifesto, not 
pulling out a once-used method.

You don't create a method, or a class, or any other abstraction just so 
that it is reusable. You create abstractions so that it is easier to 
manipulate the software without breaking it.  Yes, if you have the same 
code in 3 places, pulling it into a method creates "reuse", but the 
reason you reuse the code is so that changes to it appear *everywhere* 
they should.  Otherwise copy and paste would be an acceptable method of 
code reuse. And its not.

My philosophy on designing software is make it correct, make it simple, 
make it pretty, make it fast.  Usually (but granted not always) if you 
start from the left, you'll end up at the right much easier than 
starting at the right and going left.

If making it simple or pretty involves pulling out a simple one-line 
method that isn't used but once, then so be it.  If pulling that method 
out makes it uglier, then I don't do it.
0
Reply newsgroup.nospam (530) 6/5/2012 5:51:13 PM

On Tue, 05 Jun 2012 10:51:13 -0700, Daniel Pitts
<newsgroup.nospam@virtualinfinity.net> wrote:

>On 6/5/12 9:15 AM, Gene Wirchenko wrote:
>>       NO!  Pulling some code out to make it a method that is called
>> ONLY ONCE is what I object to.  (I might do it if there is
>> clearly-delineated functionality that could be useful again (but just
>> happens to be needed but once when it written)).  I will not do it for
>> some manifesto.
>
>Code re-usability is the great lie that has become the manifesto, not 
>pulling out a once-used method.
>
>You don't create a method, or a class, or any other abstraction just so 
>that it is reusable. You create abstractions so that it is easier to 
>manipulate the software without breaking it.  Yes, if you have the same 
>code in 3 places, pulling it into a method creates "reuse", but the 
>reason you reuse the code is so that changes to it appear *everywhere* 
>they should.  Otherwise copy and paste would be an acceptable method of 
>code reuse. And its not.
>
>My philosophy on designing software is make it correct, make it simple, 
>make it pretty, make it fast.  Usually (but granted not always) if you 
>start from the left, you'll end up at the right much easier than 
>starting at the right and going left.
>
>If making it simple or pretty involves pulling out a simple one-line 
>method that isn't used but once, then so be it.  If pulling that method 
>out makes it uglier, then I don't do it.

     We are in violent agreement.

Sincerely,

Gene Wirchenko
0
Reply genew (1191) 6/5/2012 5:54:35 PM

On 05.06.2012 18:15, Gene Wirchenko wrote:
> On Tue, 05 Jun 2012 07:31:44 +0200, Robert Klemme
> <shortcutter@googlemail.com>  wrote:

>       Which is often us so being nice to the maintenance programmer is
> being nice to oneself.

That's a nice side effect - and a motivating argument which helps the 
selfish. :-)

>       Besides the story paradigm, I also think in terms of program
> usefulness.  If a program is not very useful, one can write it pretty
> much any way one wants as the program is going to get tossed anyway.
> If it is useful, then it is going to stick around, and requirements
> have a way of changing so the program had better be maintainable.  It
> can also be difficult to tell whether a program will be useful so why
> not just write them all clearly?

I suspect often the answer to that question is: because the author did 
not understand the problem or the program or programming itself clearly. 
  The other big reason is carelessness, often increased by tight 
schedules.  Deadlines seem to make people nervous and trying to take 
short circuits.  But it will cost - sooner or later.

Kind regards

	robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
0
Reply shortcutter (5766) 6/5/2012 9:24:19 PM

On 6/5/2012 5:24 PM, Robert Klemme wrote:
> On 05.06.2012 18:15, Gene Wirchenko wrote:
>> On Tue, 05 Jun 2012 07:31:44 +0200, Robert Klemme
>> <shortcutter@googlemail.com> wrote:
>
>> Which is often us so being nice to the maintenance programmer is
>> being nice to oneself.
>
> That's a nice side effect - and a motivating argument which helps the
> selfish. :-)
>
>> Besides the story paradigm, I also think in terms of program
>> usefulness. If a program is not very useful, one can write it pretty
>> much any way one wants as the program is going to get tossed anyway.
>> If it is useful, then it is going to stick around, and requirements
>> have a way of changing so the program had better be maintainable. It
>> can also be difficult to tell whether a program will be useful so why
>> not just write them all clearly?
>
> I suspect often the answer to that question is: because the author did
> not understand the problem or the program or programming itself clearly.
> The other big reason is carelessness, often increased by tight
> schedules. Deadlines seem to make people nervous and trying to take
> short circuits. But it will cost - sooner or later.

     In my experience, it is often the case that shortcuts extract
their price sooner rather than later, in the form of more testing
and debugging time (and if you don't pay that price, you pay the
still higher price of more and nastier bugs, more support headaches,
and more patch releases).

     Not always, mind, but often.

-- 
Eric Sosman
esosman@ieee-dot-org.invalid
0
Reply esosman2 (2945) 6/5/2012 9:30:57 PM

On Tue, 05 Jun 2012 17:30:57 -0400, Eric Sosman
<esosman@ieee-dot-org.invalid> wrote:

>On 6/5/2012 5:24 PM, Robert Klemme wrote:
>> On 05.06.2012 18:15, Gene Wirchenko wrote:
>>> On Tue, 05 Jun 2012 07:31:44 +0200, Robert Klemme
>>> <shortcutter@googlemail.com> wrote:
>>
>>> Which is often us so being nice to the maintenance programmer is
>>> being nice to oneself.
>>
>> That's a nice side effect - and a motivating argument which helps the
>> selfish. :-)

     Enlightened selfishness.

>>> Besides the story paradigm, I also think in terms of program
>>> usefulness. If a program is not very useful, one can write it pretty
>>> much any way one wants as the program is going to get tossed anyway.
>>> If it is useful, then it is going to stick around, and requirements
>>> have a way of changing so the program had better be maintainable. It
>>> can also be difficult to tell whether a program will be useful so why
>>> not just write them all clearly?
>>
>> I suspect often the answer to that question is: because the author did
>> not understand the problem or the program or programming itself clearly.

     I would go with the latter but not the former.  One can still
program clearly even if one is unsure of exactly what to do, but those
who can not program are very good at messing up.

>> The other big reason is carelessness, often increased by tight
>> schedules. Deadlines seem to make people nervous and trying to take
>> short circuits. But it will cost - sooner or later.

     Yup.

>     In my experience, it is often the case that shortcuts extract
>their price sooner rather than later, in the form of more testing
>and debugging time (and if you don't pay that price, you pay the
>still higher price of more and nastier bugs, more support headaches,
>and more patch releases).
>
>     Not always, mind, but often.

     Not always, so those who want to justify shortcuts can do so. Try
pointing out that the same arguments apply to playing Russian
roulette, and invite them to play.

Sincerely,

Gene Wirchenko
0
Reply genew (1191) 6/6/2012 3:06:02 AM

On 12-06-05 02:51 PM, Daniel Pitts wrote:
> On 6/5/12 9:15 AM, Gene Wirchenko wrote:
>> NO! Pulling some code out to make it a method that is called
>> ONLY ONCE is what I object to. (I might do it if there is
>> clearly-delineated functionality that could be useful again (but just
>> happens to be needed but once when it written)). I will not do it for
>> some manifesto.
>
> Code re-usability is the great lie that has become the manifesto, not
> pulling out a once-used method.
>
> You don't create a method, or a class, or any other abstraction just so
> that it is reusable. You create abstractions so that it is easier to
> manipulate the software without breaking it. Yes, if you have the same
> code in 3 places, pulling it into a method creates "reuse", but the
> reason you reuse the code is so that changes to it appear *everywhere*
> they should. Otherwise copy and paste would be an acceptable method of
> code reuse. And its not.
>
> My philosophy on designing software is make it correct, make it simple,
> make it pretty, make it fast. Usually (but granted not always) if you
> start from the left, you'll end up at the right much easier than
> starting at the right and going left.
>
> If making it simple or pretty involves pulling out a simple one-line
> method that isn't used but once, then so be it. If pulling that method
> out makes it uglier, then I don't do it.

We're pretty much in agreement. I don't think my reply to an earlier 
post of yours, sardonically characterizing yourself as an idiot, made it 
to this NG: in that reply I indicated that Gene actually captured my 
thinking well, and that you and I were discussing at cross-purposes.

My main objection to kneejerk "Extract As Method", to avoid things like 
loop labels (but really kneejerk for any reason), is maintenance - by me 
later, or by other people. I also agree that re-use isn't usually a 
major factor. For me it's maintenance, IOW readability. If I have to 
keep jumping, even with the aid of an IDE, from one spot to another to 
track down code chunks, it degrades my capability to put code in 
perspective, and it wastes my time.

On another note, copy and paste can be perfectly OK. It's not OK if you 
now have to maintain business rules or constants or suchlike in several 
spots, or if it's an intricate algorithm, but otherwise it can 
frequently be the right thing to do, again informed by maintenance 
considerations. Copy 'n' paste is wrong mainly when the people doing it 
don't understand what, and why, they are doing it.

AHS
-- 
Never interrupt your enemy when he is making a mistake.
--Napoleon
0
Reply asandstrom3minus1 (421) 6/6/2012 8:58:50 AM

Arved Sandstrom wrote:
[snip]
> My main objection to kneejerk "Extract As Method", to avoid things like 
> loop labels (but really kneejerk for any reason), is maintenance - by me 
> later, or by other people. I also agree that re-use isn't usually a 
> major factor. For me it's maintenance, IOW readability. If I have to 
> keep jumping, even with the aid of an IDE, from one spot to another to 
> track down code chunks, it degrades my capability to put code in 
> perspective, and it wastes my time.
> 
> On another note, copy and paste can be perfectly OK. It's not OK if you 
> now have to maintain business rules or constants or suchlike in several 
> spots, or if it's an intricate algorithm, but otherwise it can 
> frequently be the right thing to do, again informed by maintenance 
> considerations. Copy 'n' paste is wrong mainly when the people doing it 
> don't understand what, and why, they are doing it.

+1
0
Reply lewbloch (1312) 6/6/2012 7:11:44 PM

On 6/4/2012 12:37 AM, Robert Klemme wrote:
> On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
>> What amazes me is that these individuals support this religious
>> stance by arguing that it improves readability, when producing
>> little auxiliary methods usually does anything but.
>
> I am not religious about break / continue (although I use it
> extremely seldom, I am more likely to use "return" inside a loop).
> But I disagree about your general statement about little auxiliary
> methods usually not improving readability.  It all depends on the
> specific case, of course, but giving a short part of an algorithm a
> name (with the option to have a place to put JavaDoc) often helps
> readability in my experience.


One test that I use in this sort of situation is to try to think of a
name for the potential extracted method. If there is a good, clear,
simple name, I make a method. If not, I'm more likely to leave it in place.

Patricia
0
Reply pats (3215) 7/22/2012 1:37:18 PM

On 7/22/2012 8:37 AM, Patricia Shanahan wrote:
> On 6/4/2012 12:37 AM, Robert Klemme wrote:
>> On Monday, June 4, 2012 9:28:13 AM UTC+2, Arved Sandstrom wrote:
>>> What amazes me is that these individuals support this religious
>>> stance by arguing that it improves readability, when producing
>>> little auxiliary methods usually does anything but.
>>
>> I am not religious about break / continue (although I use it
>> extremely seldom, I am more likely to use "return" inside a loop).
>> But I disagree about your general statement about little auxiliary
>> methods usually not improving readability.  It all depends on the
>> specific case, of course, but giving a short part of an algorithm a
>> name (with the option to have a place to put JavaDoc) often helps
>> readability in my experience.
>
>
> One test that I use in this sort of situation is to try to think of a
> name for the potential extracted method. If there is a good, clear,
> simple name, I make a method. If not, I'm more likely to leave it in place.
>
> Patricia

I've always liked the way someone long ago put it on this group or maybe 
comp.lang.lisp: "You should define a function if the call to it is 
clearer than the code it replaces."
0
Reply Chris.Riesbeck (104) 7/23/2012 6:27:27 PM

On Mon, 23 Jul 2012 13:27:27 -0500, Chris Riesbeck
<Chris.Riesbeck@gmail.com> wrote:

>On 7/22/2012 8:37 AM, Patricia Shanahan wrote:

[snip]

>> One test that I use in this sort of situation is to try to think of a
>> name for the potential extracted method. If there is a good, clear,
>> simple name, I make a method. If not, I'm more likely to leave it in place.

     That is the first test.  If there is no GCS name, either it does
not need extracting or you have a bad design that should be addressed.

>I've always liked the way someone long ago put it on this group or maybe 
>comp.lang.lisp: "You should define a function if the call to it is 
>clearer than the code it replaces."

     I would add that if the code is repeated, then break it out even
if it is a bit more complicated.  (I do not like cut-and-paste
programming.)

Sincerely,

Gene Wirchenko

0
Reply genew (1191) 7/23/2012 8:23:24 PM

40 Replies
44 Views

(page loaded in 0.489 seconds)


Reply: