Calling method inside a getter

Asked

Viewed 85 times

0

It is good practice to call any method within 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 using.. But I still prefer:

lista = ScannerDeHtm.getListaJogos();

to

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

So what do you think?

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

  • I think totally worth what Voce did in the way getListaJogos() So if you want to return something different based on the list of games, maybe a filter, or something like that, you don’t need to rewrite the HTML scan. Not to mention that I find more organized each method doing a little bit of the process.

1 answer

2


Methods get has a single purpose: to return values. They cannot be responsible for any more complex processing than just returning a value. Like the scanHtmFile is a method that initializes an attribute of the class, the ideal would be to put it in the constructor that has this role of initializer of the attributes. Thus, 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 attribute listaJogos be static or not you need to answer the following question: Does the attribute belong to the class or the object? If its value is equal to the class, it must be static, otherwise it cannot be static because its state will vary between created objects of this class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.