Java - Duplicate methods in classes and how to call them from another class

I learn and love Java and Android, but have a long way to go. I think this is a question with best practice. In my work with Android, I have 6 classes. Some of them call methods that I duplicated from another class. It seems redundant to duplicate methods when I can just call them from another class. I also think that it would be easier to support them all in one class. (The main activity, maybe?) My question is: What is the best practice for calling the same method from multiple classes? For example, say my classes are:

Main activity of GameSelector Game1Home Game1

I have several methods that are the same in every class. Lets call them getPrefs () and setPrefs (). I don’t miss anything in or out of them. What class should they enter, and how can I name them from another class?

Edit - thanks to some very useful answers I have a fully functioning class of settings, and my other 6 classes look much cleaner! This will be very easy to maintain, and I learn some great pointers when I do this. I am posting my finished class here if it can help someone else. You can call methods from your other classes as follows:

Configurations.getPrefs(this); 

and refer to the static variables that you defined as global in the configuration file as follows:

 Configurations.buttonClicked.start(); 

Configurations.java:

 public class Configurations extends Activity { static MediaPlayer buttonClicked; static MediaPlayer instructionsAudio; static MediaPlayer messageAudio; static MediaPlayer correctNum_sound; static MediaPlayer incNuma_sound; static MediaPlayer incNumb_sound; static String storeChildsName; static String storeRequestedRange; static String storeVoiceChoice; static Intent i; public static void setupPrefs(final Activity a) { ImageButton settingsClicked = ((ImageButton) a.findViewById(R.id.prefButton)); settingsClicked.setOnClickListener(new OnClickListener() { public void onClick(View v) { ImageView settingsClicked = ((ImageView) a.findViewById(R.id.prefButton)); settingsClicked.setImageResource(R.drawable.settings_button_clicked); buttonClicked = MediaPlayer.create(a, R.raw.click); buttonClicked.start(); Intent settingsActivity = new Intent(a.getBaseContext(), Preferences.class); a.startActivity(settingsActivity); } }); } public static void getPrefs(final Activity a) { // Get the xml/preferences.xml preferences SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(a.getBaseContext()); storeChildsName = prefs.getString("editTextPref", "Friend"); storeRequestedRange = prefs.getString("listPref", "3"); storeVoiceChoice = prefs.getString("voices", "1"); } public static void setupMusicToggle(final Activity a) { i=new Intent(a, MyMusicService.class); final ToggleButton togglebutton =(ToggleButton)a.findViewById(R.id.music_toggle); togglebutton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks if (togglebutton.isChecked()) { Toast.makeText(a, "Music on.", Toast.LENGTH_SHORT).show(); a.startService(i); } else { a.stopService(i); Toast.makeText(a, "Music off.", Toast.LENGTH_SHORT).show(); } }}); } public static void returnHome(View view, Activity a) { ImageView homeClicked = (ImageView) a.findViewById(R.id.home); homeClicked.setImageResource(R.drawable.homebuttonclicked); buttonClicked = MediaPlayer.create(a, R.raw.click); buttonClicked.start(); Intent intent = new Intent(a, GameSelector.class); a.startActivity(intent); } public static void releaseMP(Activity a) { if (buttonClicked != null) { buttonClicked.stop(); buttonClicked.release();} if (instructionsAudio != null) { instructionsAudio.stop(); instructionsAudio.release();} if (messageAudio != null) { messageAudio.stop(); messageAudio.release(); } if (correctNum_sound != null){ correctNum_sound.stop(); correctNum_sound.release(); } if (incNuma_sound != null) { incNumb_sound.stop(); incNuma_sound.release(); } if (incNumb_sound !=null) { incNumb_sound.stop(); incNumb_sound.release(); } } public static boolean isMyServiceRunning(Activity a) { ActivityManager manager = (ActivityManager) a.getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (MyMusicService.class.getName().equals(service.service.getClassName())) { return true; } } return false; } 

}

Hope this helps someone just as it helped me!

PS - If you see any room to improve this code, please share! I have something to learn =)

+4
source share
4 answers

There are several ways to share the code - you can do it with

  • Defining the helper class and adding static methods to it
  • Defining a base class (often an abstract base class) and adding your own methods to it,
  • Defining a non-static class and nesting an instance of this class in each of the classes that need to separate the code; classes can also use a reference to a shared instance.

It is difficult to say which approach is more appropriate, but from the names of the methods it seems that you plan to get and set preferences. In such situations, # 1 or # 3 with a common instance is most often suitable.

+6
source

It depends on what each method does. By name, getPrefs() looks like a preference setting. In this case, I personally create the Configuration class and create a singleton instance that all classes share.

Android is slightly different from regular Java.
In "normal" Java, you create objects, reference them, and then call methods on them.
On Android, most of your methods are defined in Activity , Fragment , DialogFragment , etc., and you do not control their instance. Methods defined by whitin can only be called internally unless static declared.

So, go over your design, see what these methods do, and see if you can make another class out of them :)
Hope this helps.

+1
source

It all depends on the sole purpose of the classes and methods that you define.

If there are too many methods that you need to use in many of your actions, then one of the options:

  • Define a separate helper class and implement these methods. Include them in all necessary classes.
  • Inheritance or interface will be the second option.
+1
source

I create an abstract Activity class that extends the Android Activity API class (or the FragmentActivity support class):

 public abstract class Activity extends android.app.Activity { //or extends FragmentActivity //put your common stuff here } 

Similar recommendations will ask you to name this BaseActivity class, but I like the name Activity better because it synchronizes with the Android system.

All my actions will be extended from this abstract class:

 //GameActivity.java public class GameActivity extends Activity { } //OptionsActivity.java public class OptionsActivity extends Activity { } 

I also save this abstract Activity class (and some other properties) in the library project, so I have one base for all my common things, and all my other projects just include this as a library (Project Properties> Android> Libraries> Add) . But, of course, your development needs may differ from this model.

Additional tips for developing Java:

  • Always start with the strictest access modifier ( private ), switching to a more leniant, since you need more access (by default> protected > public ).
  • If the method does not use anything static, be sure to make it static . Thus, you do not need to instantiate the object just to call the method inside its class.
  • Use getters and setters for member fields if you are not sure that you need direct access and will not introduce any errors.
  • Use wrapper classes such as java.lang.Integer when you need to show the "unknown" or "invalid" status of a primitive type ( int ).
+1
source

Source: https://habr.com/ru/post/1496696/


All Articles