Results 1 to 12 of 12
Like Tree1Likes
  • 1 Post By jim829

Thread: Should we always use getters/setters or only when they are needed?

  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    7

    Default Should we always use getters/setters or only when they are needed?

    Should we always use getters/setters, e.g. even in something like

    Java Code:
    class Foo {
        private static int foo;
    
        public int getFoo() {
            return foo;
        }
    
        public void setFoo(int fig) {
            foo = fig;
        }
    }
    Or should we use the only when there is a good reason to use them, e.g. validation for a setter or may be computing a value to return from some variables etc. ?

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Should we always use getters/setters or only when they are needed?

    I think you should always use getters and setters. The primary reason being that it hides the implementation details from the users of your class. I also recommend using them within the class as well (it can make refactoring a little easier if you have to change the way the instance fields are stored). And as you mention, enforcing invariants on the setter arguments is another good reason.

    BTW, your example above has a subtle problem (but it will work as written). To access a static variable you are supposed to use the class name, not an instance of the class. But you are using instance methods to return a static value which forces one to use an instance of the class. This gives the user of the class a wrong impression (they might believe each instance has a unique value for foo). Again, IMO, you should be using static methods to return or set static values. And they should be invoked with the class name, not an instance.

    Regards,
    Jim
    Last edited by jim829; 05-31-2015 at 11:11 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Should we always use getters/setters or only when they are needed?

    I have an unorthodox approach to explaining why you should always use getters and setters - based on personal experience of my repeatedly making the same mistake. I have one personal exclusion to that rule that I keep pestering myself with: private inner classes. Whenever I decide I can use one of those I just make the properties public, since I know they will only be handled within the class it is declared so "who cares".

    Java Code:
    public class WorkMachine {
      ...
    
      private class WorkMachinePrivateStorageBean {
        
        public int prop1;
        public String prop2;
    
        public WorkMachinePrivateStorageBean(int prop1, String prop2){ 
           this.prop1 = prop1;
           this.prop2 = prop2;
        }
      }
    }
    Nowadays I can already predict I'm making a huge design flaw - whenever until now I've used a private inner class, inevitably I get to a point where the code grows enough that I start to need to make it public because classes need to share data; either that or the code in the inner class grows enough that I want it in a separate source file anyway for readability. And then I'm left with the task of moving the class to its own source file and fixing all the code which was directly accessing the properties to use getters/setters. IDE's make that task rather easy, but its still an unnecessary distraction.

    -Always- use getters and optionally setters to expose read/write capabilities of an object property, even when they at that moment in time have no added value. You never know what you might desire of your code later on in the development process, so might as well design it as cleanly as possible right from the get-go.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Should we always use getters/setters or only when they are needed?

    Why make anything in the private inner class anything except private?

    That's what I use to make sure, if I move it, that I have to provide setters/getters...or at least rethink how the classes interact.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Should we always use getters/setters or only when they are needed?

    Exactly my point.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Should we always use getters/setters or only when they are needed?

    Quote Originally Posted by gimbal2 View Post
    Exactly my point.
    Was it?

    I need to get my eyes tested....or my brain...or both.
    :)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    7

    Default Re: Should we always use getters/setters or only when they are needed?

    The primary reason being that it hides the implementation details from the users of your class.
    This implies that when we don't use them, we are not hiding the implementation details of the class. But what implementation detail can there be in a simple
    Java Code:
    public int num=35;
    statement which is hidden by doing
    Java Code:
    private int num=35;
    public getNum() {
        return num;
    }
    ? I have read a number of times that hiding implementation details is a basic OOP principle. But I do not understand what difference does it make in the scenerio given above?


    About the problem with my code snippet, I agree. Thank you for pointing it out.
    Last edited by Zarah; 06-04-2015 at 02:59 AM.

  8. #8
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    7

    Default Re: Should we always use getters/setters or only when they are needed?

    I think you should always use getters and setters.
    -Always- use getters and optionally setters to expose read/write capabilities of an object property, even when they at that moment in time have no added value. You never know what you might desire of your code later on in the development process, so might as well design it as cleanly as possible right from the get-go.
    Thank you very much. I am taking this advice, will be using getters and setters in every class I write.

    I have one personal exclusion to that rule that I keep pestering myself with: private inner classes...either that or the code in the inner class grows enough that I want it in a separate source file anyway for readability.
    I have yet not written any big/serious projects where I would use inner classes, and I'll probably witness this when I write one. I am already taking the advice to always use getters and setters (when I want to give write capabilities as well), so thank you for the advice.
    Last edited by Zarah; 06-04-2015 at 03:07 AM.

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Should we always use getters/setters or only when they are needed?

    First, I will assume you meant to include a return type in your method. In your example it may not make a huge difference. But here is a contrived example that illustrates the point.

    Java Code:
    class MyValue {
        public int num;
    }
    Now you can use the num directly as follows:

    Java Code:
    MyValue mv = new MyValue();
    int a = mv.num;
    But say I do it like this:

    Java Code:
    class MyValue {
       private int num;
       public int getVal() {
           return num;
       }
       public void setVal(int num) {
           this.num = num;
       }
    }
    or this

    Java Code:
    class MyValue {
       private String num;
       public int getVal() {
           return Integer.parseInt(num);
       }
       public void setVal(int num) {
           this.num = Integer.toString(num);
       }
    }
    Notice in the last two examples, the user cannot tell how the integer is stored. The internal details are hidden. So it allows the author of the class to change things (hopefully for the better) and yet make the class compatible with the previous versions. If the the internal values are public and the class is published, it cannot be changed because it would affect existing code.

    You find this situation quite often in programming to interfaces. The user interface (all the methods) is consistent across all implementations but the internals may be totally different.

    Regards,
    Jim
    gimbal2 likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    7

    Default Re: Should we always use getters/setters or only when they are needed?

    @Jim829 Thank you very much, I am clear about it now.

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Should we always use getters/setters or only when they are needed?

    Quote Originally Posted by Zarah View Post
    @Jim829 Thank you very much, I am clear about it now.
    Great! And I did leave out one important aspect. Enforcing invariants. If the num must be >= 0 then the setter can enforce that once and take appropriate action. If the user sets the value directly, the number must be checked each time it is referenced. This can lead to inefficient and bloated code.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Should we always use getters/setters or only when they are needed?

    Another reason: debugging. Its way easier to set a breakpoint in a setter method to be able to trace when exactly a particular property is set to a particular value :)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Getters and setters
    By Erre in forum New To Java
    Replies: 10
    Last Post: 10-25-2012, 08:30 PM
  2. Confused about getters and setters
    By jnjh in forum New To Java
    Replies: 8
    Last Post: 05-03-2011, 07:12 AM
  3. Setters and Getters and the counter exercise
    By gnng in forum New To Java
    Replies: 8
    Last Post: 03-27-2011, 08:48 PM
  4. Getters and Setters
    By lheviathan in forum New To Java
    Replies: 4
    Last Post: 11-02-2009, 01:47 AM
  5. Getters and Setters
    By Charliestons in forum New To Java
    Replies: 10
    Last Post: 09-12-2008, 10:57 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •