Clean code - best way to compact code in Java
Asked Answered
P

2

8

I have code that looks like this:

    for(int i=0; i < a; i++){
        List<Integer> list = elementA.get(i);
        SomeClass rg = new SomeClass(list, a, methodA(i));
        int result = rg.generate();
        var+=methodA2(i, result);
    }
    for(int i=0; i < b; i++){
        List<Integer> list = elementB.get(i);
        SomeClass rg = new SomeClass(list, b, methodB(i));
        int result = rg.generate();
        var+=methodB2(i, result);
    }

How can I avoid this code repetition? I can create function which does that, but what to do with this different methods?

Potter answered 21/4, 2014 at 17:18 Comment(1)
It depends on the declarations of elementA and elementB, of methodA() and methodB(), and of methodA2() and methodB2(). If the get() methods of the classes are defined by a common interface or superclass, that helps. As for the methods, we'd just have to know more about them -- do they correspond to the classes with get() in some fashion?Cornstarch
D
10

With Java < 8 you can create an interface (note that there already is an IntFunction interface in Java 8):

interface IntFunction<A> { A apply (int i); }

m(elementA, a, new IntFunction<A> () { public A apply(int i) { methodA(i); } });

And your method would look like:

private void m(Collection<List<Integer>> element, int a, IntFunction<A> f) {
    for(int i=0; i < a; i++){
        List<Integer> list = element.get(i);
        SomeClass rg = new SomeClass(list, a, f.apply(i));
        int result = rg.generate();
    }
}

(I have omitted the methodA2 for conciseness: you would need a second interface that has an apply(int, int))

That is quite verbose and the benefit is not obvious vs. repetition.


With Java 8 it becomes cleaner:

m(elementA, a, i -> methodA(i));
//or
m(elementA, a, this::methodA);
Dreda answered 21/4, 2014 at 17:23 Comment(4)
@ᴋᴇʏsᴇʀ I have added a more detailed example.Dreda
Might be worth pointing out that the IntFunction interface already exists in Java 8.Stenophagous
@BoristheSpider Yes I did pick the name on purpose!Dreda
I know, I assumed that you did - just might be worth stating it explicitly.Stenophagous
E
1
  • Define a method that receives your List<List<Integer>> as argument that returns the desired data.
  • Define an interface that will hold the generic methods like method, method2 (based from your code).

For example:

public long yourFooMethod(List<List<Integer>> listOfData, int n, SomeInterface foo) {
    int i = 0;
    long var = 0;
    for(List<Integer> list : listOfData) {
        SomeClass rg = new SomeClass(list, n, foo.method(i));
        int result = rg.generate();
        var += foo.method2(i, result);
    }
    return var;
}
Effortful answered 21/4, 2014 at 17:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.