How to use repeated methods?

Asked

Viewed 180 times

4

I have some methods that I use in various points of the applications and I end up having to copy in each class.

For example:

String getStringOrEmpty(EditText editText) {
    String mString = editText.getText().toString();
    mString = (mString.isEmpty() ? "" : mString);
    return mString;
}

Just to inform: this method returns a String with the text that Edittext, if any, or an empty String.

I didn’t want to have to keep copying it in every class that will use it, but I would like to access this and other methods throughout the project.

This would be similar to a function library in other languages. For example, in php, I would make a file with a list of functions and use a include command to import the list to the page.

How to do this in Java (with emphasis on Android)?

  • If you need to use in several classes, of the two one, either it does not belong to these classes but to another that has a specific responsibility, or it belongs to a mother class that will be used to derive for the daughters that need it and but it seems to be more this last case, but I can’t say with just what was put in the question.

  • Actually, three times one: ... or you put him in a Mixin class, and use multiple inheritance. The problem is that the language in question does not support multiple inheritance - so you have to force the business to be arranged differently - possibly with an artificial base class - anyway, the question is very pertinent.

  • E.. in fact, in addition to multiple inheritances, something else that would do well would be able to have functions - without relying on an artificial "static class". I hope that all the karma of the people who chose to use Java for Android will bring some benefit to their souls in the future.

  • I understood the comments, but the solution has to be within the limits of the language. The solution of a class utils with static methods seems to me the most suitable for the desired purpose. Both for ease and resource saving, since the methods are instantiated only once.

3 answers

2

I believe that the best way to do this is to create a utility package. Within the package you create a class that can be imported whenever you need and use this method. In the case of this method that is presented, it could be static, in this way it would not be necessary to instantiate the object of the class. It would be something like:

Creates a useful name package. Ex: br.com.seuprojeto.util

Then create the utility class. Call as you see fit. Here I call Stringutil

//imports aqui
public class StringUtil {

    public static String getStringOrEmpty(EditText editText) {
        String mString = editText.getText().toString();
        mString = (mString.isEmpty() ? "" : mString);
        return mString; 
    }

}

To use it in your project just call:

//código da classe
String mNome = StringUtil.getStringOrEmpty(mEditText);

2

Another option, besides those already cited/answered, is to use a practice called custom view.

Basically, you create a class that inherits from the type of View that you want to modify and make your own implementations.

In your case, it would look like this:

public class CustomEditText extends EditText {

    public CustomEditText(Context context) {
        this(context, null, 0);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public String getStringOrEmpty() {
        String mString = getText().toString();
        mString = (mString.isEmpty() ? "" : mString);
        return mString;
    }
}

To use this yours custom view, you need to change in your xml (layout):

Before:

<EditText
    android:id="@+id/seu_id"
    style="@style/AlgumStyle" />

Afterward:

<br.com.seupacote.view.CustomEditText
    android:id="@+id/seu_id"
    style="@style/AlgumStyle" />

Now to access the method getStringOrEmpty() it’s pretty easy:

public class AlgumaActivity extends Activity {

    private CustomEditText customEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customEditText = (customEditText) findViewById(R.id.seu_id);
        String algumTexto = customEditText.getStringOrEmpty();
    }

}

This practice is interesting because you avoid creating static methods and classes needlessly.

  • 1

    This technique is interesting, no doubt. But if two different views (editText and Textview, for example), need the same method, you would have to copy in the two custom classes, correct? If it is, I fall back into the problem that motivated the question.

1


You can create a class with static methods. Just by name, you can already suspect that it is something related to constant, something 'stopped' (static).

When we define a class and create several objects of it, we already know that each object will be a faithful copy of the class, but with its own variables and methods in different places of memory. That is, the object 'fusca' has its own variables, different from the object 'Ferrari', although both have the same 'model', which is the class 'Car''.

When defining variables with the word Static in a class it will have a special behavior: it will be the same for all objects in that class. That is, there will not be a type of it in each object. All objects, when accessing and modifying this variable, will access the same variable, the same memory space, and the change can be seen in all objects.

You can create a class called Utils containing all the methods I wanted to use in several classes. See:

public classe Utils{

   public Utils(){
   }

    public static String returnDate(){
        // Aqui o código para retornar data atual
        return date;
    }

    public void String returnHour(){
        // Aqui o código para retornar a hora atual
        return hour;
    }

    public static String getStringOrEmpty1(EditText editText){ 
        String mString = editText.getText().toString();
        mString = (mString.isEmpty() ? "" : mString); 
        return mString; 
    }

    public String getStringOrEmpty2(EditText editText){ 
        String mString = editText.getText().toString();
        mString = (mString.isEmpty() ? "" : mString); 
        return mString; 
    }
}

Access to these methods is done in this way:

Static

String date = Utils.returnDate();
String value = Utils.getStringOrEmpty1(editText);

Non-static

String hour = new Utils().returnDate();
String value = new Utils().getStringOrEmpty2(editText);

When to use Static variables?

Especially when you want to have a control over the objects or when all objects must share information (avoid having to do Composition or call methods from other objects).

Browser other questions tagged

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