mardi 13 février 2018

Why put multiple interfaces in a single Java file for an Android app?

I've been working on an Android app for a couple of months. In many of the more sophisticated open source programs I have read through, I keep coming across multiple interfaces or a class with an embedded interface in a single file. Even Android Studio generates fragments this way.

Now, I'm an old coot. I've been programming in Java since version 1.1. I have always been taught to put classes, interfaces, and enumerators in separate files. Related items go in the same package.

Is there a reason to stuff related interfaces into a single file instead of following this best-practice?

Example given:

public class BlankFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public BlankFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment BlankFragment.
 */
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
    BlankFragment fragment = new BlankFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}
... more code ...
/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

Aucun commentaire:

Enregistrer un commentaire