Code before or after super

Asked

Viewed 38 times

2

When screams a method, always comes the super of the parent class, but at the time of coding 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 one:

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

Or whatever?

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

1 answer

4


In your specific case, you should first warn the functionality of the event’s parent class start, and therefore 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 better to put in the end. There are still cases where it can appear in the middle, appear more than once, appear within a if, and other cases. This depends a lot on the functionality offered by the parent class you want to use. One has to consider whether the call to the parent class method has to be within a try-catch and how to deal with exceptions thrown by the parent class method.

Here’s 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, today class inheritance is already considered a bad programming practice, as it promotes a strong class coupling. It is best that 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 has been designed to be used in this way, but excepting these cases, avoid the use of inheritance. Eliminating inheritance also eliminates the question of having to decide where to call the super.

  • 1

    Thank you very much, excellent explanation

Browser other questions tagged

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