Blup1980
Blup1980

Reputation: 397

What is the advantage of creating an instance of an Interface Class instead of just adding that Interface to the main class for Callbacks?

I am working on an Android app and I came across the following code for a set of Callbacks from C++. I am wondering why, using an instance of the interface class JNIListener instead of implementing the interface and adding the Callbacks directly, makes sense.

public interface JNIListener {
    void onProcessingStarted();
    void onResultAvailable();
} 


public class MainFragment extends Fragment {

......

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        .....  

        mListener = new JNIListener() {
            @Override
            public void onProcessingStarted() {
                NavDirections action = MainFragmentDirections.actionMainFragmentToResultFragment();
                NavHostFragment.findNavController(ThisFragment).navigate(action);
            }

            @Override
            public void onResultAvailable(){
                ....
            }
        }
        subscribeListener(mListener);
    }
}

instead of :

public class MainFragment extends Fragment implements JNIListener{

......

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        .....  

        subscribeListener(this);
    }

    @Override
    public void onProcessingStarted() {
        NavDirections action = MainFragmentDirections.actionMainFragmentToResultFragment();
        NavHostFragment.findNavController(thisFragment).navigate(action);
    }

    @Override
    public void onResultAvailable(){
        ....
    }
}

I don't get the advantages of the first approach. The second makes more sense to me: The callbacks have complete access to the members of the MainFragment.

The first approach should have its pro, otherwise why would someone have done it that way.

The person who wrote that code is for sure more experienced than I am. If I am doing something weird by preferring the second approach, it would be nice to understand why it is weird, learn something and avoid the issue next time.

Upvotes: 1

Views: 45

Answers (1)

Viktor Petrovski
Viktor Petrovski

Reputation: 796

The only advantage for the first approach is If you need two or more interfaces for separate things in your class. In every other case, I would use the second approach since it makes the code looks cleaner.

Upvotes: 2

Related Questions