What is a good practice to access class attributes in class methods?

11,069

Solution 1

That entirely depends on what the getters and setters are doing. If they do more than just getting and setting the value (which should be explicitly documented in the method's Javadoc), then it would really make difference what way you'd choose from inside the class. But if they are pure Javabean like getters/setters, then I'd rather access the variable directly by either a or this.a depending on whether there's a local variable in the scope with exactly that name.

Personally I would just keep the getters and setters "pure" according the Javabean spec and add another getter or setter with a self-explaining method name whenever I'd like to do something more than just getting/setting the value. E.g. getAndIncrement(), getAsString(), setAsInt(String), etc.

Matter of taste. It won't really harm as long as you're consistent with it throughout your coding.

Solution 2

If you need to create any validation in the future you'll want a setter/getter . When you make a variable visible you brake the class encapsulation. In theory it means that your code is not so Object Oriented :P , but in practice you lose the ability to do a lot of code refactorings. For example, extracting a interface. And for the this call, I think its redundant, but that's just me :)

Share:
11,069
Clem
Author by

Clem

Updated on June 04, 2022

Comments

  • Clem
    Clem about 2 years

    I always wonder about the best way to access a class attribute from a class method in Java.

    Could you quickly convince me about which one of the 3 solutions below (or a totally different one :P) is a good practice?

    public class Test {
    
        String a;
    
    
        public String getA(){
            return this.a;
        }
    
        public setA(String a){
            this.a = a;
        }
    
        // Using Getter
        public void display(){
    
            // Solution 1
            System.out.println(this.a);
    
            // Solution 2
            System.out.println(getA());
    
            // Solution 3
            System.out.println(this.getA());
        }
    
    
        // Using Setter
        public void myMethod(String b, String c){
    
            // Solution 1
            this.a = b + c;
    
            // Solution 2
            setA(b + c);
    
            // Solution 3
            this.setA(b + c);
        }
    }