This discussion is archived
5 Replies Latest reply: May 21, 2013 7:37 AM by La VloZ RSS

Direct access or access via accesor

La VloZ Newbie
Currently Being Moderated
Hiii all :)
How are u?? :)

a question to experts :
I wanna know wich is the best way to access a variables within a class :)
Using direct access or using the variable accessor :)

Exemples : (Experts doesn't need that exemple, but maybe a newbie like me :) will read this topic) :)
public class Numbers{
        private int n1;
        private int n2;
     
public void setN1(int n){
     n1 = n;
}
     
public void setN2(int n){
     n2 = n;
}

public int getN1(){
     return n1;
}
     
public int getN2(){
     return n2;
}
wich is the best way??, this :
public int sum(){
     return n1 + n2;
}
or this :
     
public int sum(){
     return getN1() + getN2;
}
     
Thank you all :)

Edited by: La VloZ on 20 mai 2013 00:29
  • 1. Re: Direct access or access via accesor
    EJP Guru
    Currently Being Moderated
    Inside the class I always use the variable, not the accessor, unless the accessor has extra magical properties. After all that's the purpose of classes, to deal with their own members. I don't see much point in using the accessor within the class otherwise, but a lot of people do it, and a lot of IDEs can generate code that way if you prefer.
  • 2. Re: Direct access or access via accesor
    La VloZ Newbie
    Currently Being Moderated
    Thank yoy EJP :)
    And if i want access a vairiable in a superclass, wich is the best way :
    using accessor or declare the variable as protected ?? :), sure we suppose that the accessor doesn't have extra magical properties ;)
  • 3. Re: Direct access or access via accesor
    EJP Guru
    Currently Being Moderated
    I hardly ever use non-private member variables in base classes so I would normally be writing accessors.
  • 4. Re: Direct access or access via accesor
    rp0428 Guru
    Currently Being Moderated
    >
    And if i want access a vairiable in a superclass, wich is the best way :
    using accessor or declare the variable as protected ?? , sure we suppose that the accessor doesn't have extra magical properties
    >
    You should not be 'supposing'.

    Follow the principles of encapsulation as EJP has already suggested.

    Users of your class should NOT be 'supposing' whether your classes accessor do or do not have 'extra magical properties'. They should not be accessing your class variables directly.

    That applies to your class when it needs the superclass data. You should use the accessors. Which means classes that extend your class should use your class accessors.

    If you just make your class variables 'private' it should all take care of itself.
  • 5. Re: Direct access or access via accesor
    La VloZ Newbie
    Currently Being Moderated
    Thank u EJP and rp0428 :)
    I got the answer :)

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points