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

C

Chad

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
 
A

Arne Vajhøj

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
 
A

Andreas Leitgeb

Chad said:
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.
 
M

markspace

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.
 
L

lewbloch

Chad said:
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.
 
B

blmblm

Chad said:
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
(e-mail address removed), or a different Lew?)
 
L

lewbloch

(By the way -- are you the person who used to post using the address
(e-mail address removed), 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.
 
A

Arne Vajhøj

Chad said:
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
 
A

Arne Vajhøj

Chad said:
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
 
B

blmblm

Well, there is that. Good point.

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).
 
L

lewbloch

     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.
 
M

markspace

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.
 
E

Eric Sosman

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'. :)
 
G

Gene Wirchenko

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
 
E

Eric Sosman

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.
 
S

Stefan Ram

Gene Wirchenko said:
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«.)
 
J

Jukka Lahtinen

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.
 
A

Arved Sandstrom

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top