SpartanRefactoring / Main

Eclipse plugin that performs automatic refactoring of Java source code, making it shorter, more idiomatic and more readable
https://www.spartan.org.il
100 stars 56 forks source link

Inlining into the initliazers of for loop: #292

Open yossigil opened 7 years ago

yossigil commented 7 years ago

Write Preview

Tough inlining problem

  String f() {
    final StringBuffer sb = new StringBuffer();
    String line;
    for (; (line = reader.readLine()) != null; sb.append(line))
      ;
    return sb + "";
  }

Could be inlined as

  String f() {
    final StringBuffer sb = new StringBuffer();
    for (String line;; (line = reader.readLine()) != null; sb.append(line))
      ;
    return sb + "";
  }

and then no further, or we can apply move closer to usage on sb, getting:

  String f() {
    String line;
    final StringBuffer sb = new StringBuffer();
    for (; (line = reader.readLine()) != null; sb.append(line))
      ;
    return sb + "";
  }

See issue #293 for more details on how and when this could be done. Then we get

  String f() {
    String line;
    final StringBuffer sb = new StringBuffer();
    for (; (line = reader.readLine()) != null; sb.append(line))
      ;
    return sb + "";
  }

then, we get stuck, unless a clever tipper or two do the job:

  String f() {
    String line;

    for ( final StringBuffer sb = new StringBuffer(line); (line = reader.readLine()) != null; sb.append(line))
      ;
    return sb + "";
  }

which then changes to

  String f() {
    String line;

    for ( final StringBuffer $ = new StringBuffer(line); (line = reader.readLine()) != null; $.append(line))
      ;
    return $ + "";
  }

which laconically goes to

  String f() {
    String line;
    for ( final StringBuffer $ = new StringBuffer(line); true; $.append(line))
      if ((line = reader.readLine()) == null)
         return $ + "";
  }

and then by

  String f() {
    for ( final StringBuffer $ = new StringBuffer(line); ; $.append(line)) {
     String line;
      if ((line = reader.readLine()) == null)
         return $ + "";
     }
  }

which gets simplified to

  String f() {
    for ( final StringBuffer $ = new StringBuffer(line); ; $.append(line)) {
     String ¢;
      if ((¢ = reader.readLine()) == null)
         return $ + "";
     }
  }

which then someday converts to some kind of an iterator

sakopzon commented 7 years ago

String f() { String line;

for ( final StringBuffer sb = new StringBuffer(line); (line = reader.readLine()) != null; sb.append(line)) ; return sb + ""; }

is compilation error, now ForToForInitializers wouldn't tip this...