A question about some long java code that has getters/setters

Discussion in 'Java' started by Chad, Jul 23, 2011.

  1. Chad

    Chad Guest

    The following code, which is taken from one of my school books,
    displays 4 different boxes inside a gui



    import java.awt.*;
    import javax.swing.*;

    public class TestMessagePanel extends JFrame {

    public TestMessagePanel() {
    MessagePanel messagePanel1 = new MessagePanel("Top Left");
    MessagePanel messagePanel2 = new MessagePanel("Top Right");
    MessagePanel messagePanel3 = new MessagePanel("Bottom Left");
    MessagePanel messagePanel4 = new MessagePanel("Bottom Right");
    messagePanel1.setBackground(Color.RED);
    messagePanel2.setBackground(Color.CYAN);
    messagePanel3.setBackground(Color.GREEN);
    messagePanel4.setBackground(Color.WHITE);
    messagePanel1.setCentered(true);

    setLayout(new GridLayout(2, 2));
    add(messagePanel1);
    add(messagePanel2);
    add(messagePanel3);
    add(messagePanel4);
    }

    public static void main(String[] args) {
    TestMessagePanel frame = new TestMessagePanel();
    frame.setSize(300, 200);
    frame.setTitle("TestMessagePanel");
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    }//end main()
    }

    class MessagePanel extends JPanel {

    private String message = "Nope";
    private int xCoordinate = 20;
    private int yCoordinate = 20;
    private int interval = 10;
    private boolean centered;

    public MessagePanel() {
    }

    public MessagePanel(String message) {
    this.message = message;
    }

    public String getMessage() {
    return message;
    }

    public void setMessage(String message) {
    this.message = message;
    repaint();
    }

    public int getXCoordinate() {
    return xCoordinate;
    }

    public void setXCoordinate(int x) {
    this.xCoordinate = x;
    repaint();
    }

    public int getYCoordinate() {
    return yCoordinate;
    }

    public void setYCoordinate(int y) {
    this.xCoordinate = y;
    repaint();
    }

    public boolean isCentered() {
    return centered;
    }

    public void setCentered(boolean centered) {
    this.centered = centered;
    repaint();
    }

    public int getInterval() {
    return interval;
    }

    public void setInterval(int interval) {
    this.interval = interval;
    repaint();
    }

    protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (centered) {
    FontMetrics fm = g.getFontMetrics();
    int stringWidth = fm.stringWidth(message);
    int stringAscent = fm.getAscent();
    xCoordinate = getWidth() / 2 - stringWidth / 2;
    yCoordinate = getWidth() / 2 - stringAscent / 2;
    }
    g.drawString(message, xCoordinate, yCoordinate);
    }

    public void MoveLeft() {
    xCoordinate -= interval;
    repaint();
    }

    public void MoveRight() {
    xCoordinate += interval;
    repaint();
    }

    public void moveUp() {
    yCoordinate -= interval;
    repaint();
    }

    public void moveDown() {
    yCoordinate += interval;
    repaint();
    }

    public Dimension getPreferredSize() {
    return new Dimension(200, 30);
    }
    }


    What I don't get is why the book defines stuff like getXCoordinate(),
    getYCoordinate(), and getInterval() when it doesn't even use them in
    this very long code example. I tried reading over the section in the
    book, but the author gives no explanation on why he included a bunch
    of unused getters/setters. On top of that, the code seems to work fine
    when I comment out these methods.

    Ideas?

    Chad
    Chad, Jul 23, 2011
    #1
    1. Advertising

  2. Chad

    Arne Vajhøj Guest

    On 7/22/2011 7:12 PM, Chad wrote:
    > The following code, which is taken from one of my school books,
    > displays 4 different boxes inside a gui
    >
    >
    >
    > import java.awt.*;
    > import javax.swing.*;
    >
    > public class TestMessagePanel extends JFrame {
    >
    > public TestMessagePanel() {
    > MessagePanel messagePanel1 = new MessagePanel("Top Left");
    > MessagePanel messagePanel2 = new MessagePanel("Top Right");
    > MessagePanel messagePanel3 = new MessagePanel("Bottom Left");
    > MessagePanel messagePanel4 = new MessagePanel("Bottom Right");
    > messagePanel1.setBackground(Color.RED);
    > messagePanel2.setBackground(Color.CYAN);
    > messagePanel3.setBackground(Color.GREEN);
    > messagePanel4.setBackground(Color.WHITE);
    > messagePanel1.setCentered(true);
    >
    > setLayout(new GridLayout(2, 2));
    > add(messagePanel1);
    > add(messagePanel2);
    > add(messagePanel3);
    > add(messagePanel4);
    > }
    >
    > public static void main(String[] args) {
    > TestMessagePanel frame = new TestMessagePanel();
    > frame.setSize(300, 200);
    > frame.setTitle("TestMessagePanel");
    > frame.setLocationRelativeTo(null);
    > frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    > frame.setVisible(true);
    >
    > }//end main()
    > }
    >
    > class MessagePanel extends JPanel {
    >
    > private String message = "Nope";
    > private int xCoordinate = 20;
    > private int yCoordinate = 20;
    > private int interval = 10;
    > private boolean centered;
    >
    > public MessagePanel() {
    > }
    >
    > public MessagePanel(String message) {
    > this.message = message;
    > }
    >
    > public String getMessage() {
    > return message;
    > }
    >
    > public void setMessage(String message) {
    > this.message = message;
    > repaint();
    > }
    >
    > public int getXCoordinate() {
    > return xCoordinate;
    > }
    >
    > public void setXCoordinate(int x) {
    > this.xCoordinate = x;
    > repaint();
    > }
    >
    > public int getYCoordinate() {
    > return yCoordinate;
    > }
    >
    > public void setYCoordinate(int y) {
    > this.xCoordinate = y;
    > repaint();
    > }
    >
    > public boolean isCentered() {
    > return centered;
    > }
    >
    > public void setCentered(boolean centered) {
    > this.centered = centered;
    > repaint();
    > }
    >
    > public int getInterval() {
    > return interval;
    > }
    >
    > public void setInterval(int interval) {
    > this.interval = interval;
    > repaint();
    > }
    >
    > protected void paintComponent(Graphics g) {
    > super.paintComponent(g);
    >
    > if (centered) {
    > FontMetrics fm = g.getFontMetrics();
    > int stringWidth = fm.stringWidth(message);
    > int stringAscent = fm.getAscent();
    > xCoordinate = getWidth() / 2 - stringWidth / 2;
    > yCoordinate = getWidth() / 2 - stringAscent / 2;
    > }
    > g.drawString(message, xCoordinate, yCoordinate);
    > }
    >
    > public void MoveLeft() {
    > xCoordinate -= interval;
    > repaint();
    > }
    >
    > public void MoveRight() {
    > xCoordinate += interval;
    > repaint();
    > }
    >
    > public void moveUp() {
    > yCoordinate -= interval;
    > repaint();
    > }
    >
    > public void moveDown() {
    > yCoordinate += interval;
    > repaint();
    > }
    >
    > public Dimension getPreferredSize() {
    > return new Dimension(200, 30);
    > }
    > }
    >
    >
    > What I don't get is why the book defines stuff like getXCoordinate(),
    > getYCoordinate(), and getInterval() when it doesn't even use them in
    > this very long code example. I tried reading over the section in the
    > book, but the author gives no explanation on why he included a bunch
    > of unused getters/setters. On top of that, the code seems to work fine
    > when I comment out these methods.
    >
    > Ideas?


    There are two approaches to getters and setters:
    * generate all except when you have a good reason not to
    * generate only those you absolutely need

    In this case I think the second approach is actually the best, but
    I am a lazy bastard so I would like just ask my IDE to add all
    the getters and setters anyway.

    Arne
    Arne Vajhøj, Jul 23, 2011
    #2
    1. Advertising

  3. Chad <> wrote:
    > What I don't get is why the book defines stuff like getXCoordinate(),
    > getYCoordinate(), and getInterval() when it doesn't even use them in
    > this very long code example. ...


    I can't speak for the authors, but I might have included these into
    a book for a few reasons: get the students more used to correctly
    camelCasing method names, and because they are standard methods
    typically found in widget libraries.

    > public Dimension getPreferredSize() {
    > return new Dimension(200, 30);
    > }


    Some others of these methods like getPreferredSize() are called by
    the framework, but I wouldn't expect that for the methods you speci-
    fically asked about.
    Andreas Leitgeb, Jul 23, 2011
    #3
  4. Chad

    markspace Guest

    On 7/22/2011 4:12 PM, Chad wrote:
    > What I don't get is why the book defines stuff like getXCoordinate(),
    > getYCoordinate(), and getInterval() when it doesn't even use them



    Dead code is often a fact of life. OTOH, some reasonable reasons might be:

    Those methods are called by a unit test harness, which is not shown.

    Those methods are used elsewhere in a different code base, and this
    class is a general purpose class developed by the author as part of his
    text book.

    You might look ahead and see if this class appears again in the book,
    maybe with the "unused" methods invoked there.
    markspace, Jul 23, 2011
    #4
  5. Chad

    lewbloch Guest

    Chad wrote:
    > The following code, which is taken from one of my school books,
    > displays 4 different boxes inside a gui [sic]
    >
    > import java.awt.*;
    > import javax.swing.*;
    >
    > public class TestMessagePanel extends JFrame {
    >
    >     public TestMessagePanel() {
    >         MessagePanel messagePanel1 = new MessagePanel("Top Left");
    >         MessagePanel messagePanel2 = new MessagePanel("Top Right");
    >         MessagePanel messagePanel3 = new MessagePanel("Bottom Left");
    >         MessagePanel messagePanel4 = new MessagePanel("Bottom Right");
    >         messagePanel1.setBackground(Color.RED);
    >         messagePanel2.setBackground(Color.CYAN);
    >         messagePanel3.setBackground(Color.GREEN);
    >         messagePanel4.setBackground(Color.WHITE);
    >         messagePanel1.setCentered(true);
    >
    >         setLayout(new GridLayout(2, 2));
    >         add(messagePanel1);
    >         add(messagePanel2);
    >         add(messagePanel3);
    >         add(messagePanel4);
    >     }
    >
    >     public static void main(String[] args) {
    >         TestMessagePanel frame = new TestMessagePanel();
    >         frame.setSize(300, 200);
    >         frame.setTitle("TestMessagePanel");
    >         frame.setLocationRelativeTo(null);
    >         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    >         frame.setVisible(true);
    >
    >     }//end main()
    >
    > }
    >
    > class MessagePanel extends JPanel {
    >
    >     private String message = "Nope";
    >     private int xCoordinate = 20;
    >     private int yCoordinate = 20;
    >     private int interval = 10;
    >     private boolean centered;
    >
    >     public MessagePanel() {
    >     }
    >
    >     public MessagePanel(String message) {
    >         this.message = message;
    >     }
    >
    >     public String getMessage() {
    >         return message;
    >     }
    >
    >     public void setMessage(String message) {
    >         this.message = message;
    >         repaint();
    >     }
    >
    >     public int getXCoordinate() {
    >         return xCoordinate;
    >     }
    >
    >     public void setXCoordinate(int x) {
    >         this.xCoordinate = x;
    >         repaint();
    >     }
    >
    >     public int getYCoordinate() {
    >         return yCoordinate;
    >     }
    >
    >     public void setYCoordinate(int y) {
    >         this.xCoordinate = y;
    >         repaint();
    >     }
    >
    >     public boolean isCentered() {
    >         return centered;
    >     }
    >
    >     public void setCentered(boolean centered) {
    >         this.centered = centered;
    >         repaint();
    >     }
    >
    >     public int getInterval() {
    >         return interval;
    >     }
    >
    >     public void setInterval(int interval) {
    >         this.interval = interval;
    >         repaint();
    >     }
    >
    >     protected void paintComponent(Graphics g) {
    >         super.paintComponent(g);
    >
    >         if (centered) {
    >             FontMetrics fm = g.getFontMetrics();
    >             int stringWidth = fm.stringWidth(message);
    >             int stringAscent = fm.getAscent();
    >             xCoordinate = getWidth() / 2 - stringWidth / 2;
    >             yCoordinate = getWidth() / 2 - stringAscent / 2;
    >         }
    >         g.drawString(message, xCoordinate, yCoordinate);
    >     }
    >
    >     public void MoveLeft() {
    >         xCoordinate -= interval;
    >         repaint();
    >     }
    >
    >     public void MoveRight() {
    >         xCoordinate += interval;
    >         repaint();
    >     }
    >
    >     public void moveUp() {
    >         yCoordinate -= interval;
    >         repaint();
    >     }
    >
    >     public void moveDown() {
    >         yCoordinate += interval;
    >         repaint();
    >     }
    >
    >     public Dimension getPreferredSize() {
    >         return new Dimension(200, 30);
    >     }
    >
    > }
    >
    > What I don't get is why the book defines stuff like getXCoordinate(),
    > getYCoordinate(), and getInterval() when it doesn't even use them in
    > this very long code example. I tried reading over the section in the
    > book, but the author gives no explanation on why he included a bunch
    > of unused getters/setters. On top of that, the code seems to work fine
    > when I comment out these methods.
    >
    > Ideas?


    The problem with this code is that it teaches the bad and bug-prone
    practice of creating GUI elements on the main thread instead of the
    EDT. Don't use this book. The author apparently didn't know what he
    was doing.

    It is standard practice to create accessors and mutators for class
    attributes. There's nothing wrong with that. The class is written as
    any good API writer (a.k.a. "programmer") should in that one respect.
    While you should not build features into a class on a remote chance of
    their use, if you have properties then you should provide the get/set
    methods for them quite nearly always.

    But you should never, never, never do GUI magic off the EDT!

    It's also bad practice to use import-on-demand (import '*') rather
    than single-type imports.

    Really, don't use this book. Get a good book.

    --
    Lew
    lewbloch, Jul 23, 2011
    #5
  6. Chad

    Guest

    In article <>,
    lewbloch <> wrote:
    > Chad wrote:
    > > The following code, which is taken from one of my school books,
    > > displays 4 different boxes inside a gui [sic]
    > >
    > > import java.awt.*;
    > > import javax.swing.*;


    [ snip ]

    > It's also bad practice to use import-on-demand (import '*') rather
    > than single-type imports.


    In code meant for compiling and execution, agreed. In code meant
    for display in dead-tree documentation, though .... I think there's
    a case to be made for the "import ...*" form, so that code examples
    aren't so full of uninteresting lines, accompanied by an explanation
    somewhere that in "real" code one would import only those classes
    needed.

    (By the way -- are you the person who used to post using the address
    , or a different Lew?)

    --
    B. L. Massingill
    ObDisclaimer: I don't speak for my employers; they return the favor.
    , Jul 23, 2011
    #6
  7. Chad

    lewbloch Guest

    wrote:
    > (By the way -- are you the person who used to post using the address
    > , or a different Lew?)
    >


    Same Lew.

    I recently relocated and my regular computer is in storage until I get
    a more permanent address. This somewhat limits my access to my Gmail
    account and web-based Usenet until I get my regular equipment back.

    --
    Lew
    lewbloch, Jul 23, 2011
    #7
  8. Chad

    Arne Vajhøj Guest

    On 7/23/2011 1:41 PM, wrote:
    > In article<>,
    > lewbloch<> wrote:
    >> Chad wrote:
    >>> The following code, which is taken from one of my school books,
    >>> displays 4 different boxes inside a gui [sic]
    >>>
    >>> import java.awt.*;
    >>> import javax.swing.*;

    >
    > [ snip ]
    >
    >> It's also bad practice to use import-on-demand (import '*') rather
    >> than single-type imports.

    >
    > In code meant for compiling and execution, agreed. In code meant
    > for display in dead-tree documentation, though .... I think there's
    > a case to be made for the "import ...*" form, so that code examples
    > aren't so full of uninteresting lines, accompanied by an explanation
    > somewhere that in "real" code one would import only those classes
    > needed.


    Having specific imports makes it easier to see where the classes
    come from.

    I would tend to say that is even more important for dead tree docs
    than for code.

    Arne
    Arne Vajhøj, Jul 23, 2011
    #8
  9. Chad

    Arne Vajhøj Guest

    On 7/23/2011 12:02 PM, lewbloch wrote:
    > Chad wrote:
    >> The following code, which is taken from one of my school books,
    >> displays 4 different boxes inside a gui [sic]
    >>
    >> import java.awt.*;
    >> import javax.swing.*;
    >>
    >> public class TestMessagePanel extends JFrame {
    >>
    >> public TestMessagePanel() {
    >> MessagePanel messagePanel1 = new MessagePanel("Top Left");
    >> MessagePanel messagePanel2 = new MessagePanel("Top Right");
    >> MessagePanel messagePanel3 = new MessagePanel("Bottom Left");
    >> MessagePanel messagePanel4 = new MessagePanel("Bottom Right");
    >> messagePanel1.setBackground(Color.RED);
    >> messagePanel2.setBackground(Color.CYAN);
    >> messagePanel3.setBackground(Color.GREEN);
    >> messagePanel4.setBackground(Color.WHITE);
    >> messagePanel1.setCentered(true);
    >>
    >> setLayout(new GridLayout(2, 2));
    >> add(messagePanel1);
    >> add(messagePanel2);
    >> add(messagePanel3);
    >> add(messagePanel4);
    >> }
    >>
    >> public static void main(String[] args) {
    >> TestMessagePanel frame = new TestMessagePanel();
    >> frame.setSize(300, 200);
    >> frame.setTitle("TestMessagePanel");
    >> frame.setLocationRelativeTo(null);
    >> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    >> frame.setVisible(true);
    >>
    >> }//end main()
    >>
    >> }
    >>
    >> class MessagePanel extends JPanel {
    >>
    >> private String message = "Nope";
    >> private int xCoordinate = 20;
    >> private int yCoordinate = 20;
    >> private int interval = 10;
    >> private boolean centered;
    >>
    >> public MessagePanel() {
    >> }
    >>
    >> public MessagePanel(String message) {
    >> this.message = message;
    >> }
    >>
    >> public String getMessage() {
    >> return message;
    >> }
    >>
    >> public void setMessage(String message) {
    >> this.message = message;
    >> repaint();
    >> }
    >>
    >> public int getXCoordinate() {
    >> return xCoordinate;
    >> }
    >>
    >> public void setXCoordinate(int x) {
    >> this.xCoordinate = x;
    >> repaint();
    >> }
    >>
    >> public int getYCoordinate() {
    >> return yCoordinate;
    >> }
    >>
    >> public void setYCoordinate(int y) {
    >> this.xCoordinate = y;
    >> repaint();
    >> }
    >>
    >> public boolean isCentered() {
    >> return centered;
    >> }
    >>
    >> public void setCentered(boolean centered) {
    >> this.centered = centered;
    >> repaint();
    >> }
    >>
    >> public int getInterval() {
    >> return interval;
    >> }
    >>
    >> public void setInterval(int interval) {
    >> this.interval = interval;
    >> repaint();
    >> }
    >>
    >> protected void paintComponent(Graphics g) {
    >> super.paintComponent(g);
    >>
    >> if (centered) {
    >> FontMetrics fm = g.getFontMetrics();
    >> int stringWidth = fm.stringWidth(message);
    >> int stringAscent = fm.getAscent();
    >> xCoordinate = getWidth() / 2 - stringWidth / 2;
    >> yCoordinate = getWidth() / 2 - stringAscent / 2;
    >> }
    >> g.drawString(message, xCoordinate, yCoordinate);
    >> }
    >>
    >> public void MoveLeft() {
    >> xCoordinate -= interval;
    >> repaint();
    >> }
    >>
    >> public void MoveRight() {
    >> xCoordinate += interval;
    >> repaint();
    >> }
    >>
    >> public void moveUp() {
    >> yCoordinate -= interval;
    >> repaint();
    >> }
    >>
    >> public void moveDown() {
    >> yCoordinate += interval;
    >> repaint();
    >> }
    >>
    >> public Dimension getPreferredSize() {
    >> return new Dimension(200, 30);
    >> }
    >>
    >> }
    >>
    >> What I don't get is why the book defines stuff like getXCoordinate(),
    >> getYCoordinate(), and getInterval() when it doesn't even use them in
    >> this very long code example. I tried reading over the section in the
    >> book, but the author gives no explanation on why he included a bunch
    >> of unused getters/setters. On top of that, the code seems to work fine
    >> when I comment out these methods.
    >>
    >> Ideas?

    >
    > The problem with this code is that it teaches the bad and bug-prone
    > practice of creating GUI elements on the main thread instead of the
    > EDT. Don't use this book. The author apparently didn't know what he
    > was doing.
    >
    > It is standard practice to create accessors and mutators for class
    > attributes. There's nothing wrong with that. The class is written as
    > any good API writer (a.k.a. "programmer") should in that one respect.
    > While you should not build features into a class on a remote chance of
    > their use, if you have properties then you should provide the get/set
    > methods for them quite nearly always.
    >
    > But you should never, never, never do GUI magic off the EDT!


    Maybe the book is just not new.

    It was common practice to initiate the Swing form from the
    main thread for some years until people got aware of the
    potential issue.

    Arne
    Arne Vajhøj, Jul 24, 2011
    #9
  10. Chad

    Guest

    In article <>,
    Steve Sobol <> wrote:
    > In article <4e2b4456$0$306$>, Arne Vajhøj
    > says...
    > >
    > > On 7/23/2011 1:41 PM, wrote:

    >
    > > >> It's also bad practice to use import-on-demand (import '*') rather
    > > >> than single-type imports.
    > > >
    > > > In code meant for compiling and execution, agreed. In code meant
    > > > for display in dead-tree documentation, though ....

    > >
    > > Having specific imports makes it easier to see where the classes
    > > come from.


    Well, there is that. Good point.

    > > I would tend to say that is even more important for dead tree docs
    > > than for code.


    I'm not sure I agree, but maybe you can convince me .... Why?

    > I agree. And I can't speak for other IDE's, but in Eclipse, updating
    > your list of specific imports can be done by hitting Ctrl-Shift-O.
    > ("Organize Imports")
    >
    > Takes a fraction of a second :)


    True, and one of the reasons I find Eclipse a useful tool despite
    my strong preference for editing any kind of text with, um, a
    different tool. :)?

    However, my point was not that it's difficult to generate a list
    of specific imports -- I know better -- but that including one in
    printed material clutters up the page with details unlikely to be
    important (though obviously not everyone agrees with me on that).

    --
    B. L. Massingill
    ObDisclaimer: I don't speak for my employers; they return the favor.
    , Jul 25, 2011
    #10
  11. Chad

    markspace Guest

    On 7/25/2011 1:27 PM, Patrick May wrote:
    > With the exception of cases like DAOs, getters
    > should be very rare and setters non-existent.



    I think perhaps you meant "DTO" here.
    markspace, Jul 25, 2011
    #11
  12. Chad

    lewbloch Guest

    On Jul 25, 1:27 pm, Patrick May <> wrote:
    > lewbloch <> writes:
    > > It is standard practice to create accessors and mutators for class
    > > attributes.  There's nothing wrong with that.

    >
    >      Actually, there is.  It encourages a style of programming where
    > objects have too much knowledge about each other.  Encapsulation is
    > important; objects should ask each other for services, not manipulate
    > each others internals.  With the exception of cases like DAOs, getters
    > should be very rare and setters non-existent.


    You don't create them for hidden members! Yeesh.

    By definition the attributes are those that you want to make public.

    What you choose to make public should be a matter of design, not
    dogma. I do not endorse making attributes public that shouldn't be.

    --
    Lew
    lewbloch, Jul 25, 2011
    #12
  13. Chad

    markspace Guest

    On 7/25/2011 1:27 PM, Patrick May wrote:
    > It encourages a style of programming where
    > objects have too much knowledge about each other.



    This is an interesting idea. However, I think it might be short
    sighted, or at least incomplete.

    For example, I've just been working on a project which involves sending
    commands over a network. There are up to four parameters for all
    commands, and it might be better style to perhaps only create some
    number of constructors which only allow valid combinations of these four
    parameters.

    However, I went instead with the "natural" mutator approach. First,
    supplying a constructor or method for each possible combination would
    result in a large number of constructors or methods, vs. the simplicity
    of just four mutators.

    Second the internal state of the object is not so hard to grasp that the
    mutators are hard to use. It's pretty easy and basic to set the
    parameters you want and then ship the command across the network.

    And last, large numbers of arguments can be difficult to work with.
    Users don't always remember the correct order, and swaping two
    parameters inadvertently is a hazard. Harder to do that with just a
    single parameter, and easier to spot an error in a code review.

    So, yes I think you have a point that mutators shouldn't be used in
    every case. But I think there's a rather large numbers of cases where
    they do work, and are best practice.
    markspace, Jul 26, 2011
    #13
  14. Chad

    Stefan Ram Guest

    markspace <-@.> writes:
    >On 7/25/2011 1:27 PM, Patrick May wrote:
    >>It encourages a style of programming where
    >>objects have too much knowledge about each other.

    >This is an interesting idea.


    I would not call an »interesting idea«, what is the
    common standard of object-oriented programming teaching.
    Obviously, Getters and Setters break encapsulation.

    To be specific, there are classic articles such as

    http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

    or

    http://c2.com/cgi/wiki?AccessorsAreEvil
    Stefan Ram, Jul 26, 2011
    #14
  15. Chad

    Eric Sosman Guest

    On 7/25/2011 8:00 PM, Patricia Shanahan wrote:
    > On 7/25/2011 3:56 PM, lewbloch wrote:
    >> On Jul 25, 1:27 pm, Patrick May<> wrote:
    >>> lewbloch<> writes:
    >>>> It is standard practice to create accessors and mutators for class
    >>>> attributes. There's nothing wrong with that.
    >>>
    >>> Actually, there is. It encourages a style of programming where
    >>> objects have too much knowledge about each other. Encapsulation is
    >>> important; objects should ask each other for services, not manipulate
    >>> each others internals. With the exception of cases like DAOs, getters
    >>> should be very rare and setters non-existent.

    >>
    >> You don't create them for hidden members! Yeesh.

    >
    > I've been doing some Java tutoring. I've seen coursework assignments
    > that *required* the student to create a getter and setter for every
    > field. :-(


    No problem: Make all the getters and setters `private'. :)

    --
    Eric Sosman
    d
    Eric Sosman, Jul 26, 2011
    #15
  16. On 26 Jul 2011 00:42:20 GMT, -berlin.de (Stefan Ram)
    wrote:

    >markspace <-@.> writes:
    >>On 7/25/2011 1:27 PM, Patrick May wrote:
    >>>It encourages a style of programming where
    >>>objects have too much knowledge about each other.

    >>This is an interesting idea.

    >
    > I would not call an »interesting idea«, what is the
    > common standard of object-oriented programming teaching.
    > Obviously, Getters and Setters break encapsulation.


    Getters: yes. Setters: maybe.

    What is wrong with something like:

    FilePrinter r=new FilePrinter();

    // General Options
    r.SetPrinter("\\Boojum");
    r.SetCopies(1);
    r.SetDoubleSided(true);

    r.SetFilename("c:\somedir\fileone");
    r.Print();

    r.SetFilename("c:\somedir\filetwo");
    r.Print();

    r.SetFilename("c:\somedir\filethree");
    r.SetCopies(5);
    r.Print();

    [snip]

    Sincerely,

    Gene Wirchenko
    Gene Wirchenko, Jul 26, 2011
    #16
  17. Chad

    Eric Sosman Guest

    On 7/25/2011 7:50 PM, markspace wrote:
    > On 7/25/2011 1:27 PM, Patrick May wrote:
    >> It encourages a style of programming where
    >> objects have too much knowledge about each other.

    >
    >
    > This is an interesting idea. However, I think it might be short sighted,
    > or at least incomplete.
    >
    > For example, I've just been working on a project which involves sending
    > commands over a network. There are up to four parameters for all
    > commands, and it might be better style to perhaps only create some
    > number of constructors which only allow valid combinations of these four
    > parameters.
    >[... uses "vanilla" constructor plus mutators ...]


    Another approach -- which may or may not make sense in your
    situation, but might be worthy of consideration -- is to make Command
    immutable, with one constructor that takes a single argument of the
    mutable CommandBuilder class.

    public class Command {
    private final int tweedeldum;
    private final Control[] tweedledee;
    ...
    public Command(CommandBuilder builder) {
    if (builder.isValid()) {
    tweedledum = builder.tweedledum;
    tweedledee = builder.tweedeldee.clone();
    ...
    } else {
    throw new IllegalArgumentException(
    builder.toString());
    }
    }
    }

    public class CommandBuilder {
    private int tweedledee = 42;
    private Control[] tweedledum = new Control[0];
    ...
    public CommandBuilder setTweedledee(int tweedledee) {
    this.tweedledee = tweedledee;
    return this;
    }
    public CommandBuilder setTweedledum(Control[] tweedledum) {
    this.tweedledum = tweedledum;
    return this;
    }
    ...
    }

    ...

    Command makeItSo = new Command(
    new CommandBuilder().setTweedledee(97));
    Command avastYeScurvySpalpeens = new Command(
    new CommandBuilder().setTweedledum(getControls())
    .setTweedledee(-86));

    True, the validation and exception-throwing still happen at
    run-time -- but it happens at Command construction, instead of later
    on when the Command is used and the source of the bad parameters may
    be more of a mystery.

    --
    Eric Sosman
    d
    Eric Sosman, Jul 26, 2011
    #17
  18. Chad

    Stefan Ram Guest

    Gene Wirchenko <> writes:
    >>I would not call an »interesting idea«, what is the
    >>common standard of object-oriented programming teaching.
    >>Obviously, Getters and Setters break encapsulation.

    >Getters: yes. Setters: maybe.
    >What is wrong with something like:
    >FilePrinter r=new FilePrinter();
    >// General Options
    >r.SetPrinter("\\Boojum");
    >r.SetCopies(1);
    >r.SetDoubleSided(true);


    Before I can answer this, I need to know, whether there are
    setters in the code above. How do you define »setter«? Is a
    »setter« any one-argument method, whose name begins with »Set«?

    (To apply my own definition, I would need to see the
    documentation of a method, to judge whether it is a »setter«.)
    Stefan Ram, Jul 26, 2011
    #18
  19. lewbloch <> writes:
    > Chad wrote:
    >> The following code, which is taken from one of my school books,


    > Really, don't use this book. Get a good book.


    I don't argue about that, but..
    TOP told us it's a school book. When at school, were you allowed to
    choose the books yourself?

    OTOH, it would probably be a good idea to point the faults out to the
    teacher.

    --
    Jukka Lahtinen
    Jukka Lahtinen, Jul 26, 2011
    #19
  20. On 11-07-25 09:42 PM, Stefan Ram wrote:
    > markspace <-@.> writes:
    >> On 7/25/2011 1:27 PM, Patrick May wrote:
    >>> It encourages a style of programming where
    >>> objects have too much knowledge about each other.

    >> This is an interesting idea.

    >
    > I would not call an »interesting idea«, what is the
    > common standard of object-oriented programming teaching.
    > Obviously, Getters and Setters break encapsulation.
    >
    > To be specific, there are classic articles such as
    >
    > http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html
    >
    > or
    >
    > http://c2.com/cgi/wiki?AccessorsAreEvil
    >
    > .
    > However, Java is not an fully object-oriented programming
    > language and therefore, for Java programming one should
    > adopt a Java style (not an OOP style). Getters and Setters
    > are parts of the Java culture and of the Java Beans
    > specification. Therefore, it is appropriate to use them in
    > Java programming whenever deemed advantageous.
    >

    Wikipedia has two definitions for encapsulation; the c2.com article is
    (legitimately IMO) questioning excessive use of accessors under the
    terms of the second Wikipedia definition. Note the word "questioning":
    that article has a bunch of nuanced arguments on both sides. It's in the
    context of this second definition specifically that Patrick advanced his
    objections.

    It's not black and white, obviously. Even if we are restricting our
    discussion to simple accessors (the getters and setters are simple
    assignments or returns) then it's clearly still possible that the nature
    of the particular object is such that no access can set the state to an
    invalid one.

    And as others have pointed out, it's entirely a situation-specific
    matter as to whether a profusion of accessors is even a code-smell: you
    want to use JPA entities and view-model classes with care, but their
    very nature argues for exposing their guts.

    But I do agree with some that in much teaching these ideas about
    accessors do not get advanced. Students are therefore left with the
    impression that _routine_ use of accessors is OK. What's worse is that
    they don't even get the scoop on writing proper accessors (e.g.
    mutability considerations), nor on object consistency or class
    invariants. _This_ is the actual smell, not the considered use of accessors.

    Getters and setters are not just "Java style". It's an issue for every
    OOP language. Real-world objects describe both data (state) and
    behaviour, and run the spectrum from [all state-no behaviour] to [no
    state-all behaviour]. Practical considerations mean that not all
    behaviour will have all of its required state in the same class: hence
    accessors.

    AHS
    Arved Sandstrom, Jul 26, 2011
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Berlin Brown
    Replies:
    5
    Views:
    873
    Darryl L. Pierce
    Jan 25, 2004
  2. George Armhold
    Replies:
    1
    Views:
    1,451
    Chris Riesbeck
    Sep 2, 2004
  3. Getters and Setters

    , Jun 9, 2006, in forum: Java
    Replies:
    7
    Views:
    653
    Eddy Young
    Jun 10, 2006
  4. Raaijmakers, Vincent (IndSys,GE Interlogix)

    Newbie in win32com: getters and setters

    Raaijmakers, Vincent (IndSys,GE Interlogix), Oct 23, 2003, in forum: Python
    Replies:
    0
    Views:
    266
    Raaijmakers, Vincent (IndSys,GE Interlogix)
    Oct 23, 2003
  5. =?ISO-8859-1?Q?Petter_Holmstr=F6m?=

    Getters and setters in python, common practise

    =?ISO-8859-1?Q?Petter_Holmstr=F6m?=, Apr 15, 2004, in forum: Python
    Replies:
    8
    Views:
    461
Loading...

Share This Page