Search code examples
javaandroidandroid-intentsettergetter

In Java/Android, do I pass values through Intent or by using getters/setters?


I read that getter and setters are not good for Android programming when using the method in the same class it was created.

But would there be any negative effects if using it in another class?

I was told not to use many static variables so I'm looking for an alternative and it seems less confusing to use getters/setters than passing values through Intent.

So is it good coding to do this?


Solution

  • Just to get the most important part out of the way: You should NEVER use static variables in Android unless you know exactly what you are doing. Otherwise you are going to create memory leaks and a whole other slew of problems.

    If you want to pass data to another Activity you should use Intents.


    Method calls always have additional overhead. Accessing a field directly will always be faster. But this does not mean that you should abandon getters and setters all together.

    For example look at this class Example:

    public class Example {
    
        private String text;
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
        public void doSomething() {
            ...
        }
    }
    

    Inside doSomething() you should work with the field directly. Calling the getters and setters in there would not be the way to go since that would require additional overhead each time you call one.

    If you are using the Example class inside another class like below you should use the getter and setter methods:

    Example instance = new Example();
    instance.setText("some text");
    ...
    String text = instance.getText();
    

    Making the field public and accessing it directly like instance.text would be bad.


    BUT any modern device has so much computing power that the overhead generated by a method call is completely negligible. The docs do state that you should avoid using getters and setters in performance critical places, but that rule is from a time when most Android phones had 128 MB RAM. The main reason you should adhere to the rules I explained above is just one thing: coding style.

    Your first concern should always be to write clean, readable and maintainable code.