Code before or after super

2

When we override a method, it always comes with super of the parent class, but at the time of encoding the right thing to do would be before or after it?

In the example below the right would be this:

@Override
public void onStart() {
    super.onStart();
    Toast.makeText(getActivity(), "Aqui", Toast.LENGTH_SHORT).show();
} 

Or this:

@Override
public void onStart() {
    Toast.makeText(getActivity(), "Aqui", Toast.LENGTH_SHORT).show();
    super.onStart();
}

Or whatever?

What is the best practice? Or it will depend on each case, for example if we need the parent class to do its job first.

    
asked by anonymous 29.08.2018 / 06:24

1 answer

4

In your specific case, you might want to first notify the parent class of the start event, so the super.onStart(); would be at the beginning.

However each case is a case. There are cases where it is best to put in the beginning. In other cases it is best to put in the end. There are still cases where it can appear in the middle, appear more than once, appear inside a if , and other cases. This depends a lot on the functionality offered by the parent class you want to use. It is also necessary to consider whether the call to the method of the parent class has to be within try-catch and how to deal with exceptions thrown by the method of the parent class.

Here is a very simple example, but it shows that this decision can be complex:

public class Pessoa {
    public void pegarObjetoNoQuarto(Objeto a, Quarto b) throws NaoAchouException {
        // ...
    }

    public void acenderLuz(Quarto x) { /* ... */ }

    public void apagarLuz(Quarto x) { /* ... */ }
}
public class PessoaCuidadosa extends Pessoa {
    @Override
    public void pegarObjetoNoQuarto(Objeto a, Quarto b) throws NaoAchouException {
        acenderLuz(b);
        try {
            super.pegarObjetoNoQuarto(a, b);
        } finally {
            apagarLuz(b);
        }
    }
}

However, nowadays class inheritance is already considered a bad programming practice, since it promotes strong coupling between classes. It is best you do not depend on inheritance if possible. It is true that there are cases where you are forced to use inheritance, especially when using some framework or tool that is designed to be used in this way, but with the exception of such cases, avoid using inheritance. Deleting the inheritance also eliminates the question of having to decide where to call super .

    
29.08.2018 / 07:16