I
I
insomnia772016-04-25 21:59:48
Java
insomnia77, 2016-04-25 21:59:48

What is the best way to format java code?

There is a code that parses an excel file and if the phrase begins with a specific action, then a unique action is performed.
Now the code is formatted like this:

if (elemTitle.startsWith("Выбор"))
                    try {
                        //выбирает(elemTitle, elemVal);
                        делает_выбор(elemTitle, elemVal);
                    } catch (AutotestError e) {
                        logger.error("Set field " + elemTitle + " error", e);
                    }
 else if (elemTitle.startsWith("МультиВыбор")) {
                    сбросить_мультиселект(elemTitle);
                    выбрать_мультиселект(elemTitle, elemVal);
}

.....
Should it be remade into something like this or will it only reduce readability?
String[] cases = {"Выбор", "МультиВыбор", "yetanotherSubString"};

int i;
for(i = 0; i < cases.length; i++)
    if(SomeString.contains(cases[i])) break;

switch(i) {
    case 0: //someSubString
        System.out.println("do something");
    break;
    case 1: //anotherSubString
        System.out.println("do something else");
    break;
    case 2: //yetanotherSubString
        System.out.println("do something even more different");
    break;
    default:
        System.out.println("do nothing");
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Cheremisin, 2016-04-26
@insomnia77

We create case-classes: we put them in a HashMap and ... Voila! No ifs! It is easy to expand - by adding a new class and initializing the map.
Context we use for storage in transfer of any hogwash.

package my.com;

import java.util.HashMap;
import java.util.Map;

public class MyJob {
  class Context {
    private String astring;

    public Context(String string){
      this.setAstring(string);
      // set properties
    }

    public String getAstring() {
      return astring;
    }

    public void setAstring(String astring) {
      this.astring = astring;
    }
  }
  
  interface Worker {
    public int doWork(Context c);
  }

  class MultiChoose implements Worker {

    @Override
    public int doWork(Context c) {
      c.getAstring();
      System.out.println(c.getAstring() +" MultiChoose");
      c.setAstring("Новая фигня");
      return 0;
    }
    
  }

  class Choose implements Worker {

    @Override
    public int doWork(Context c) {
      System.out.println(c.getAstring() +" Choose");
      return 0;
    }
    
  }
  class AnotherString implements Worker {

    @Override
    public int doWork(Context c) {
      System.out.println(c.getAstring() + " AnotherString");
      return 0;
    }
    
  }

  class Nothing implements Worker {

    @Override
    public int doWork(Context c) {
      System.out.println("Nothing");
      return 1;
    }
    
  }
  public static void main(String[] args) {
    MyJob job = new MyJob();
    Map<String, Worker> cases = new HashMap<String, Worker>();
    cases.put("Выбор", job.new Choose());
    cases.put("МультиВыбор", job.new MultiChoose());
    cases.put("yetanotherSubString", job.new AnotherString());
    
    
    String[] keys_for_test = {"Выбор","МультиВыбор","yetanotherSubString","WrongKey"};
    Context content = job.new Context("Всякая фигня");

    for (String key:keys_for_test) {
      Worker worker = cases.getOrDefault(key, job.new Nothing());
      worker.doWork(content);
    }

  }

}

Result
Всякая фигня Choose
Всякая фигня MultiChoose
Новая фигня AnotherString
Nothing

G
guras256, 2016-04-28
@guras256

The version of the previous speaker, pumped by the eighth Java =)
Well, of course, you can put any lamb and handle situations as you like, and divide the methods into classes, here is the simplest example.
Well, it’s better not to get too carried away with the eighth java, even this example shows through the strimosis of the brain and generates a bunch of extra objects =)

public class App {

    private static Map<String, Runnable> actionMap = new HashMap<>();
    private static Runnable defaultAction = App::defaultActionMethod;
    static {
        actionMap.put("Выбор", App::choice);
        actionMap.put("МультиВыбор", App::multipleChoice);
        actionMap.put("yetanotherSubString", App::yetAnotherSubString);
    }

    private static void choice() {
        System.out.println("doSomething");
    }

    private static void multipleChoice() {
        System.out.println("doThisOrThat");
    }

    private static void yetAnotherSubString() {
        System.out.println("doYetAnotherSomething");
    }

    private static void defaultActionMethod() {
        System.out.println("Action not found.");
    }

    public static void main(String[] args) {
        String[] cases = {"Выбор", "МультиВыбор", "yetanotherSubString", "йуцйцуйцу"};
        Stream.of(cases)
                .map(actionMap::get)
                .map(Optional::ofNullable)
                .forEach(runnable -> runnable.orElse(defaultAction).run());
    }
}

doSomething
doThisOrThat
doYetAnotherSomething
Action not found.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question