vendredi 17 juin 2016

How to avoid code duplication in List methods in Java?

The following method reads a file and returns a certain List type.

List<X> readFile(String file) {
    List<X> x = new ArrayList<X>();

    File f = new File(file);

    List<String> lines = null;
    try {
        lines = Files.readLines(f, Charsets.UTF_8);
    } catch (IOException e) {
    }

    return x
}

Now a different list is required. The method has been copied and the following returns a different List type.

List<Y> readFile(String file) {
    List<Y> y = new ArrayList<Y>();

    List<String> lines = null;
    try {
        lines = Files.readLines(f, Charsets.UTF_8);
    } catch (IOException e) {
    }

    return y
}

The problem is that the class has been duplicated. How to avoid code duplication in such cases?

Attempt

avoidDuplicatedCode(){
    List<Y> y = new ArrayList<Y>();

    List<String> lines = null;
    try {
        lines = Files.readLines(f, Charsets.UTF_8);
    } catch (IOException e) {
    }

    return y
}

results in:

  • set method return type to 'List'

when changed a lot of other issues occurs

Aucun commentaire:

Enregistrer un commentaire