Object Oriented Programming - Avoid Switching / Case and if / else (JAVA)

I had a problem when I am not allowed to use switch / case or if / else requests.

I have a configuration file that I read and this:

650;0;1.5;month
614;0;2.88;year
466;0;2.48;week
716;0;4.6;half-year
718;0;2.6;quarter

I split these lines into ";" so it is stored in an array. The problem that I have is that I need to do other things in the code for each time specified in this ar [3] array, so if it is a month, I need other calculations when it is a full year.

But I am not allowed to do this with Switch / case or If / Else, now I'm confused.

If (ar[3] = month){
do this;
else if (ar[3] = year) {
do this; 
}

How do I do this object oriented? Thanks for any help :)

+4
source share
5 answers

Inherited Polymorphism - Your Friend

, - , ar [3]. do this . , - . . , .

?:.

, :

MyClass x = ar[3].equals("month") ? new MyClassMonth() :
            (ar[3].equals("year") ? new MyClassYear() :
            (ar[3].equals("week") ? new MyClassWeek() :
            (ar[3].equals("half-year") ? new MyClassHalfyear() :
                                        new MyClassQuarter())));
x.doSomething();

, .

, ?:. ?

, MyClassMonth , , doSomething() . Map<String, MyClass> , , .

​​ :

final Map<String, MyClass> themap = new HashMap<>();
{
  themap.add("month", new MyClassMonth());
  themap.add("year", new MyClassYear());
  themap.add("week", new MyClassWeek());
  themap.add("half-year", new MyClassHalfyear());
  themap.add("quarter", new MyClassQuarter());
}

doSomething() ar :

MyClass x = themap.get(ar[3]);
if (x != null)
  x.doSomething(ar);

. Map, Map , . Map .

@OldCurmudgeon . Map , . , . .

+1

enum factory Map.

// Lookups for teh period.
static final Map<String, Period> lookup = new HashMap<>();

enum Period {

    Month("month") {

                @Override
                void process(int x, int y, double v) {
                    // Processing for "month" records here.
                    System.out.println(this + "-process(" + x + "," + y + "," + v + ")");
                }
            },
    Year("year") {
                @Override
                void process(int x, int y, double v) {
                    // Processing for "year" records here.
                    System.out.println(this + "-process(" + x + "," + y + "," + v + ")");
                }
            },
    Quarter("quarter") {
                @Override
                void process(int x, int y, double v) {
                    // Processing for "quarter" records here.
                    System.out.println(this + "-process(" + x + "," + y + "," + v + ")");
                }
            },
    HalfYear("half-year") {
                @Override
                void process(int x, int y, double v) {
                    // Processing for "half-year" records here.
                    System.out.println(this + "-process(" + x + "," + y + "," + v + ")");
                }
            };

    Period(String inData) {
        // Record me in the map.
        lookup.put(inData, this);
    }

    abstract void process(int x, int y, double v);

    static void process(String data) {
        String[] parts = data.split(";");
        Period p = lookup.get(parts[3]);
        if (p != null) {
            p.process(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Double.parseDouble(parts[2]));
        }
    }
}

public void test() {
    String[] test = {"650;0;1.5;month",
        "614;0;2.88;year",
        "466;0;2.48;week",
        "716;0;4.6;half-year",
        "718;0;2.6;quarter",};
    for (String s : test) {
        Period.process(s);
    }
}

:

Month-process(650,0,1.5)
Year-process(614,0,2.88)
HalfYear-process(716,0,4.6)
Quarter-process(718,0,2.6)

, if, , - .

+2

- :

public interface Calculator {
    double calculate(int p1, int p2, double p3);
}

public class YearCalculator implements Calculator {
    public double calculate(int p1, int p2, double p3) {
        double value = 0.0;
        // do year calculations
        return value;
    }
}

public class CalculatorFactory {
    public Calculator getInstance(String type) {
       Calculator calculator = null;
       if (type != null) {
       } else {
           throw new IllegalArgumentException("calculator type cannot be null");
           if ("year".equalsIgnoreCase(type)) {
           } else {
               System.out.println(String.format("No such type: %s", type));
           }
       }
       return calculator;
    }
}

if/else factory, .

:

CalculatorFactory factory = new CalculatorFactory();
// contents is a List of Strings from your input file.
for (String line : contents) {
    String [] tokens = line.split(";");
    Calculator calculator = factory.getInstance(tokens[3]);
    double value = calculator.calculate(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Double.parseDouble(tokens[2]));
}
+1

Codebender :

5 , , , .

:

public interface MyCalculator {

    public double calculate(double a, double b, double c);

}

5 , . calculate month, year, week, half-year quarter:

public class MyMonthCalculator implements MyCalculator {

    @Override
    public double calculate(double a, double b, double c) {
        // Do your calculations here then return
    }

}

Map.

map.put("month", new MyMonthCalculator());
// Repeat for year, week, half-year and quarter

:

double result = map.get(ar[3]).calculate(Double.parseDouble(ar[0]), Double.parseDouble(ar[1]), Double.parseDouble(ar[2]));
0

if case . . if case, , while .

So your code might look something like:

String[] options = { "foo", "bar", "baz" };
Runnable[] action = { new Runnable() {
    @Override
    public void run() {
        System.out.println("handling foo");
    }
}, new Runnable() {
    @Override
    public void run() {
        System.out.println("handling bar");
    }
}, new Runnable() {
    @Override
    public void run() {
        System.out.println("handling baz");
    }
} };
String choice = "bar";
int matched = 0;
int i = -1;
while (matched != 1) {
    i++;
    matched = boolToInt(options[i].equals(choice));
}
action[i].run();

I used a method like this to convert booleanto integer, where1=true, 0=false

public static int boolToInt(Boolean b) {
    return 5 - b.toString().length();
}

Instead of Runnable, you can provide your own interface.

0
source

Source: https://habr.com/ru/post/1598699/


All Articles