Call method inside a getter

0

Is it good practice to call any method inside a getter?

Example:

public final class ScannerDeHtm {

    private static final String DIR_CEF = DefineDiretorio.getDiretorio() + "CEF";
    private static List<String> listaHtmFile;
    private static List<Jogo> listaJogos;

    private ScannerDeHtm() {}

    private static void scanHtmFile() throws IOException {

        List<String> listaSorteios;

        File arquivoHtm = new File(DIR_CEF + File.separator + "d_megasc.htm");

        try {
            Scanner scanner = new Scanner(arquivoHtm.toPath());

            // ...
        }
    }

    public static List<Jogo> getListaJogos() {

        try {
            scanHtmFile();       // é boa prática?
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (listaJogos != null) {
            return new ArrayList<>(listaJogos);
        }
        return new ArrayList<>();
    }
}

The other way would be to insert the scanHtmFile () method into the constructor of this class, or make it public and call it static when it is to be used. But I still prefer:

lista = ScannerDeHtm.getListaJogos();

a

ScannerDeHtm scan = new ScannerDeHtm(); 
lista = scan.getListaJogos();

So, what do you think?

Edit: It is worth mentioning that this Class in question only exists to return a List with the games and it will be used extensively in this program.

    
asked by anonymous 08.09.2016 / 08:50

1 answer

2

Methods get has a single purpose: return values. They can not be responsible for any more complex processing than just returning a value. Since scanHtmFile is a method that initializes an attribute of the class, it would ideally be placed in the constructor that has this attribute initializing role. So the get would be called only to return the initialized value. It would look like this:

public ScannerDeHtm() {
    try {
        listaJogos = scanHtmFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static List<Jogo> getListaJogos() {
    return listaJogos;
}

Regarding the listaJogos attribute to be static or not you need to answer the following question: Does the attribute belong to the class or to the object? If its value is the same for the class, it should be static, otherwise it can not be static because its state will vary between objects created in that class.

    
09.09.2016 / 02:29