Identifying fields of a class

S

Sameer

When we create a class in java we use several variables for
internal functioning of the class. The procedures of the class may
also contain local variables.
We introduce variables as we need it.
But how many of these variables be treated as fields of the class?
Do we have to decide a particular variable is going to be a field and
may be accessed from other classes?

For example in creating a GUI for an application we need to
define variables like

private JMenuBar menuBar;
private JMenu menuFile, menuLookAndFeel;
private JMenuItem menuItemExit, menuItemAbout;
public JLabel statusBar;
public JPanel contentPanel;

and they are generally declared as fields of the class.

But they do not fit in the role of fields of the class as we have
defined them for GUI creation only and a menu may not be
accessed externally.

Are there any guidelines in designing fields of the class?
How to differentiate between a field and an ordinary variables?
-Sameer
 
T

Thomas Hawtin

Sameer said:
private JMenuBar menuBar;
private JMenu menuFile, menuLookAndFeel;
private JMenuItem menuItemExit, menuItemAbout;
public JLabel statusBar;
public JPanel contentPanel;
Are there any guidelines in designing fields of the class?

Make all instance fields private. Where fields are never altered, make
them final. Don't make anything a field that needn't be stored there.
How to differentiate between a field and an ordinary variables?

If you need some form of hungarian-like notation, then that indicates
unclear code. So, for instance, keep the size of methods down.

Tom Hawtin
 
R

Roedy Green

Are there any guidelines in designing fields of the class?
How to differentiate between a field and an ordinary variables?

My rule is to always make them instance variables. This allows you to
access them in multiple methods, even if you don't need that right
away. E.g. in a app you sometimes want to split code between the
constructor and addNotify. In Applets you later add code to stop() or
destroy() that you may leave out in your first cut.

It also fits the principle of least astonishment. Others reading your
code expect to find a complete list of Components as instance
variables.

The exception would be JOptionPanes.
 
R

Raymond DeCampo

Roedy said:
My rule is to always make them instance variables. This allows you to
access them in multiple methods, even if you don't need that right
away. E.g. in a app you sometimes want to split code between the
constructor and addNotify. In Applets you later add code to stop() or
destroy() that you may leave out in your first cut.

Am I reading this correctly, i.e., that you never use local variables
but always make them instance variables? I must be losing something in
the translation from Canadian. :)

In any case, let me suggest that you stop doing that and use the
refactoring tools of Eclipse to turn a local variable into a field when
necessary.
It also fits the principle of least astonishment. Others reading your
code expect to find a complete list of Components as instance
variables.

This statement appears to indicate that the statement concerning "always
make them instance variables" applies only to Components perhaps?
The exception would be JOptionPanes.


Ray
 
T

Thomas G. Marshall

Raymond DeCampo coughed up:
Am I reading this correctly, i.e., that you never use local variables
but always make them instance variables? I must be losing something
in the translation from Canadian. :)

Canada legalized pot? {shrug} ;)

In any case, let me suggest that you stop doing that and use the
refactoring tools of Eclipse to turn a local variable into a field
when necessary.


This statement appears to indicate that the statement concerning
"always make them instance variables" applies only to Components
perhaps?

I'm not sure, particularly when the "law of least surprise" is particularly
violated by having variables that are not needed outside of a single method
accessible by the entire class.
 
T

Thomas G. Marshall

Roedy Green coughed up:
My rule is to always make them instance variables. This allows you to
access them in multiple methods, even if you don't need that right
away.

Maybe don't do that.

When you have declared something as a member variable then you are
specifically communicating to the reader of your code that there is a need
for it.

When you declare something as a stack-local variable, then you are
specifically communicating to the reader of your code that he only needs to
worry about the value of it within the confines of this method.

Having excess ID's visible in scopes unnecessarily large only makes it
harder to maintain as a result.
 
R

Roedy Green

This statement appears to indicate that the statement concerning "always
make them instance variables" applies only to Components perhaps?

Yes, I am talking only about Components. Obviously local variables
have a place.

The reason is mainly for documentation. You want a nice tidy list of
all the components in one place. If you use locals for a few of them
the code is harder to follow.
 
T

Thomas Hawtin

Roedy said:
Yes, I am talking only about Components. Obviously local variables
have a place.

The reason is mainly for documentation. You want a nice tidy list of
all the components in one place. If you use locals for a few of them
the code is harder to follow.

I tend to assign none of my components to instance variables. Create,
set up behaviour, throw at screen, forget. Only cases I keep them are
where I need to mainpulate, say, rows of components, but that's a
different structure altogether.

Tom Hawtin
 
T

Thomas G. Marshall

Roedy Green coughed up:
Yes, I am talking only about Components. Obviously local variables
have a place.

The reason is mainly for documentation. You want a nice tidy list of
all the components in one place. If you use locals for a few of them
the code is harder to follow.

Roedy, I have to take what I said back. I fully agree with you. It was not
clear to me from your initial statement in your first post that you were
talking about gui components. Later in the post you did, but I thought you
were leaving the statement open-ended, which of course doesn't make sense
for a senior engineer to even ponder. Sorry.

I often spend quite a bit of time establishing many gui components as member
variables. Iit keeps everything in one place regardless as to whether or
not they are needed by more than one method. It would be confusing, for
example, to have 75% of the members of a gridbaglayout held by variable
within a method, and 25% of them outside as members.
 
O

Oliver Wong

Sameer said:
When we create a class in java we use several variables for
internal functioning of the class. The procedures of the class may
also contain local variables.
We introduce variables as we need it.
But how many of these variables be treated as fields of the class?
Do we have to decide a particular variable is going to be a field and
may be accessed from other classes?

For example in creating a GUI for an application we need to
define variables like

private JMenuBar menuBar;
private JMenu menuFile, menuLookAndFeel;
private JMenuItem menuItemExit, menuItemAbout;
public JLabel statusBar;
public JPanel contentPanel;

and they are generally declared as fields of the class.

But they do not fit in the role of fields of the class as we have
defined them for GUI creation only and a menu may not be
accessed externally.

Are there any guidelines in designing fields of the class?

I've read the other replies to this thread, but they seem to mainly be
focusing on GUI programming. In the type of programming I do, I usually
don't have to worry about GUI stuff too much (my apps are more of a
console-based string-crunching nature).

With that in mind, I believe that you generally want to limit the scope
of variables as much as possible. Therefore, you should prefer to use local
variables, then private fields, then protected fields, then default-visible
fields, then public fields.

But really when I'm designing code, that's not how I think. Rather, I
ask myself "This piece of data I'm thinking about... Does it constitute a
part of the state of the object, or is it more a place to store the results
of a calculation?" If the data represents the state of the object, then it
makes sense to make it a field. If it's just to store the result of a
calculation, then it should probably be a local var.

I also like to make all my fields private, and only give access to them
via getters and setters. Some of my programmer friends disagree and make
their some of their fields public. This last issue is just a stylistic one,
and you can make robust, workable code with either technique.
How to differentiate between a field and an ordinary variables?

I always prefix fields with "this.". So if you see "this.a", you know
"a" is a field. If you see just "a", then you know "a" is a local variable.

- Oliver
 
C

Chris Head

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Oliver Wong wrote:
[snip]
With that in mind, I believe that you generally want to limit the scope
of variables as much as possible. Therefore, you should prefer to use local
variables, then private fields, then protected fields, then default-visible
fields, then public fields.
[snip]

Hi,
You mean local, private, default, protected, and public. Protected is
MORE visible than default. Default can be seen by any other class in the
same package. Protected can be seen by any class in the same package AND
by subclasses.

Chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)

iD8DBQFDGI396ZGQ8LKA8nwRAmhoAJ9De8i/gINMUrv6W9jpTvgAiNX8KwCgxckm
WiPDzQlvzFK+Nb+MobNC0kg=
=mpJw
-----END PGP SIGNATURE-----
 
O

Oliver Wong

Chris Head said:
Hi,
You mean local, private, default, protected, and public. Protected is
MORE visible than default. Default can be seen by any other class in the
same package. Protected can be seen by any class in the same package AND
by subclasses.

Yes, you are correct. Sorry.

- Oliver
 
T

Thomas G. Marshall

Oliver Wong coughed up:
I also like to make all my fields private, and only give access to
them via getters and setters. Some of my programmer friends disagree
and make their some of their fields public. This last issue is just a
stylistic one, and you can make robust, workable code with either
technique.

Not in a great many situations no. It is usually *not* a stylistic
technique.

1. many accesses/mutations of said variable cannot occur without mucking
with another thread's larger compound operation that requires that variable
stay unmolested. You cannot do that without synchronization, and you cannot
have synchronization without methods.

2. Even if you are not using MT, or are so, but not accessing that variable
in any compound kind of way, the code is extremely fragile in that MT with
mutex requiring access could easily be added by an engineer later. Just one
posibility is to think in terms of someone adding a MT test harness, or
worse, a watchdog to keep track of id's during the runtime that needs to
access a non-mucked-with id within a loop.

IMO, there is a place for such direct field access, but I'm betting that its
in far *far* fewer places than you and especially your programmer friends
may realize.
 
O

Oliver Wong

Thomas G. Marshall said:
Oliver Wong coughed up:

Not in a great many situations no. It is usually *not* a stylistic
technique.

1. many accesses/mutations of said variable cannot occur without mucking
with another thread's larger compound operation that requires that
variable stay unmolested. You cannot do that without synchronization, and
you cannot have synchronization without methods.

2. Even if you are not using MT, or are so, but not accessing that
variable in any compound kind of way, the code is extremely fragile in
that MT with mutex requiring access could easily be added by an engineer
later. Just one posibility is to think in terms of someone adding a MT
test harness, or worse, a watchdog to keep track of id's during the
runtime that needs to access a non-mucked-with id within a loop.

IMO, there is a place for such direct field access, but I'm betting that
its in far *far* fewer places than you and especially your programmer
friends may realize.

While I think you're right that getters and setters make for better MT
code, I think writing good MT code is difficult, in the sense that you have
to actually think long and hard to make your code thread-safe. If you're NOT
thinking long and hard about it, I think it's better to make it obvious that
your code is not thread-safe, rather than putting a half-hearted attempt.

That being said, I still prefer using getters and setters to direct
field access.

- Oliver
 
T

Thomas G. Marshall

Oliver Wong coughed up:
"Thomas G. Marshall"


While I think you're right that getters and setters make for
better MT code, I think writing good MT code is difficult, in the
sense that you have to actually think long and hard to make your code
thread-safe. If you're NOT thinking long and hard about it, I think
it's better to make it obvious that your code is not thread-safe,
rather than putting a half-hearted attempt.

Make your code horribly dangerous just so folks know it is? That is a
strategy that is going to bite you in the ass. Both your "make it obvious"
and "half-hearted attempt" concepts (either one) will result in fragile (if
not dead as a doornail) code.

If you don't know how to write MT code properly, then either 1. try not to,
or 2. learn how to.

....[rip]...
 
O

Oliver Wong

Thomas G. Marshall said:
Oliver Wong coughed up:

Make your code horribly dangerous just so folks know it is? That is a
strategy that is going to bite you in the ass. Both your "make it
obvious" and "half-hearted attempt" concepts (either one) will result in
fragile (if not dead as a doornail) code.

I didn't say to make it horribly dangerous on purpose. I'm just saying
don't mislead people into believe your code is MT safe if it isn't. One of
the worst things you can do is throw the keyword "synchronized" in an
undocumented, MT-unsafe program. The existence of the keyword "synchronized"
in that program implies that whoever wrote it was trying to make it thread
safe. With no documentation, people will have to read through the code to
try and guess if it's really is MT-safe or not, and they might guess
incorrectly.

In other words, I am saying "MT-safety is not a good reason to use
getters and setters unless you've actually ensured that the rest of your
code is MT-safe". Saying "Oh, I'll make the getters and setters safe, and
worry about MT-safety of the rest of the code later" is a bad practice in my
opinion.
If you don't know how to write MT code properly, then either 1. try not
to, or 2. learn how to.

The above statement is true but misleading. It implies that knowing how
to write MT code nescessarily entails that the code you write will be
MT-safe. I think a lot of people who know how to write MT code don't
actually make most of their code MT-safe. Sun, as one giant entity, for
example, knows (more or less) how to write MT-safe code, and yet you see the
phrase "This class is not thread safe" sprinkled all over their
documentation.

That's what I mean by make it obvious.

- Oliver
 
T

Thomas G. Marshall

Oliver Wong coughed up:
"Thomas G. Marshall"
....[rip]...
If you don't know how to write MT code properly, then either 1. try
not to, or 2. learn how to.

The above statement is true but misleading. It implies that
knowing how to write MT code nescessarily entails that the code you
write will be MT-safe.

Fair enough, I understand your statements better now. I was reacting to the
initial reference to "good MT code", which overtook your later reference to
"thread-safe".

I think a lot of people who know how to write
MT code don't actually make most of their code MT-safe. Sun, as one
giant entity, for example, knows (more or less) how to write MT-safe
code, and yet you see the phrase "This class is not thread safe"
sprinkled all over their documentation.

I agree, but the emphasis is wrong. You probably agree that It is ok to
purposefully produce a facility that is not thread safe, particularly when
there are runtime efficiency issues. It is not ok to use such a facility in
a thread un-safe way, which might be a term renamed to something akin to
"disasterous".

We were talking past each other, and I think that's cleared up now.
 
D

Dale King

Roedy said:
My rule is to always make them instance variables. This allows you to
access them in multiple methods, even if you don't need that right
away. E.g. in a app you sometimes want to split code between the
constructor and addNotify. In Applets you later add code to stop() or
destroy() that you may leave out in your first cut.

I try to never make them instance variables of the class that created
them. They may be instance variables of an object which would likely be
an event listener object, perhaps an anonymous inner class of the
creation method.

If I am creating fields to hold references to the components, I consider
it a failure. It usually means I am trying to do too many things with a
single object rather than creating other objects. Or perhaps I am
incorrectly interacting with the component itself rather than the model
behind the component.

It's not an absolute and I can't say that I have created tons of GUIs,
but it is the goal I strive for.
 
T

Thomas G. Marshall

Dale King coughed up:
I try to never make them instance variables of the class that created
them. They may be instance variables of an object which would likely
be an event listener object, perhaps an anonymous inner class of the
creation method.

If I am creating fields to hold references to the components, I
consider it a failure. It usually means I am trying to do too many
things with a single object rather than creating other objects. Or
perhaps I am incorrectly interacting with the component itself rather
than the model behind the component.

It's not an absolute and I can't say that I have created tons of GUIs,
but it is the goal I strive for.


It's not a bad goal. But regarding GUI's, I tend to want the entirety of
the gui elements all in one place. Sometimes a gui element is best being
accessed directly by more than one method in a class, others don't, yet I
don't want them listed out in two places. Furthermore, even though listener
events tend to give you the element that correspond to the particular event,
that listener often needs to do something /else/ to a different component,
in both cases: be it directly or by back channeling back to the C (of the
MVC) and then ultimately back to the V.
 
D

Dale King

Thomas said:
Dale King coughed up:




It's not a bad goal. But regarding GUI's, I tend to want the entirety of
the gui elements all in one place.

And I find that usually means I am trying to do too much in one place.
It shows I am trying to put all the logic in one place rather than
distributing it over a bunch of lightweight objects.
Sometimes a gui element is best being
accessed directly by more than one method in a class, others don't, yet I
don't want them listed out in two places. Furthermore, even though listener
events tend to give you the element that correspond to the particular event,
that listener often needs to do something /else/ to a different component,
in both cases: be it directly or by back channeling back to the C (of the
MVC) and then ultimately back to the V.

I question whether it is the gui component it should talk to or the
model, but we'll sidestep that one.

And the answer is simply that the object that implements the listener
interface itself has the reference to the other component.

So if the listener for component a needs to talk to component b then you
might have:

a.addFooListener( new AFoolistener( b ) );
 

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,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top