Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2006

Tip: Looking for answers? Try searching our database.

Converting constants-only interfaces to abstract classes

Thread view: 
Rhino - 05 Feb 2006 23:19 GMT
I was advised in another thread to avoid creating interfaces that contained
only constants; I was told that abstract classes were a better choice for
something that only contains constants. I was also given the reasons why it
is bad to make an interface contain only constants and I am satisfied that
those are good reasons.

I started to convert two existing constants interfaces to abstract classes
and immediately got into trouble. I changed my first interface,
ResumeConstants, to an abstract class, and that was no problem. But now, the
compiler is complaining in all of the classes that contain "implements
ResumeConstants"; the messages are quite reasonable: you can't implement an
abstract class.

I realize that you usually _extend_ abtract classes but many of the classes
that used to implement ResumeConstants are already extending other classes,
like JApplet or ResumeFileCreator.

How do I handle those cases? I'm afraid my OO theory isn't too strong so
forgive me if the answer seems obvious to you; it isn't obvious to _me_

Signature

Rhino

Stefan Ram - 05 Feb 2006 23:43 GMT
>How do I handle those cases? I'm afraid my OO theory isn't too
>strong so forgive me if the answer seems obvious to you; it
>isn't obvious to _me_

 Here is an example of a class using two constant variables
 from other classes:

class Math { final static double pi = java.lang.Math.atan( -1 )* -4; }
class Phys { final static double c_m_s = 299792458; }
public class Main
{ public static void main( final java.lang.String[] args )
 { java.lang.System.out.println( Math.pi );
   java.lang.System.out.println( Phys.c_m_s ); }}

 "import static" can be used to get rid of the class prefix:

import static java.lang.Math.PI;
import static java.awt.Color.RED;
public class Main
{ public static void main( final java.lang.String[] args )
 { java.lang.System.out.println( PI );
   java.lang.System.out.println( RED ); }}

 In Java, only interfaces have constants; classes have constant
 variables.
Daniel Dyer - 05 Feb 2006 23:48 GMT
>   In Java, only interfaces have constants; classes have constant
>   variables.

Isn't that an oxymoron?  It's like the sticker on my old Sony VAIO that  
informed me of the available "optional essentials".

Dan.

Signature

Daniel Dyer
http://www.dandyer.co.uk

Stefan Ram - 06 Feb 2006 00:09 GMT
>>In Java, only interfaces have constants; classes have constant
>>variables.
>Isn't that an oxymoron? It's like the sticker on my old Sony
>VAIO that informed me of the available "optional essentials".

 A variable is a storage location and has an associated type.
 A final variable may only be assigned to once.

 The JLS seems to use the term "constant" when referring to
 enum constants or fields of interfaces only.
Tony Morris - 06 Feb 2006 03:22 GMT
> >>In Java, only interfaces have constants; classes have constant
> >>variables.
> >Isn't that an oxymoron? It's like the sticker on my old Sony
> >VAIO that informed me of the available "optional essentials".

Whatever the case, it is wrong.

>   A variable is a storage location and has an associated type.
>   A final variable may only be assigned to once.

Not quite - a final is "write once" only if it is a field.
A final local may be "write never" - definite assignment rules mandate that
it has been "definitely written once" upon first use.

>   The JLS seems to use the term "constant" when referring to
>   enum constants or fields of interfaces only.

Where?

When a final is not a constant
http://jqa.tmorris.net/GetQAndA.action?qids=13

Signature

Tony Morris
http://tmorris.net/

Stefan Ram - 06 Feb 2006 03:40 GMT
>>A variable is a storage location and has an associated type.
>>A final variable may only be assigned to once.
>Not quite - a final is "write once" only if it is a field.

 Both sentences are quotations from the
 Java Language Specification, Third Edition.

>>The JLS seems to use the term "constant" when referring to
>>enum constants or fields of interfaces only.
>Where?

 I was referring to the noun "constant" - not the adjective.
 The domain of my assertion is not localized in the Java
 Language Specification, Third Edition: One has to find every
 usage of the noun "constant" in the Java Language
 Specification, Third Edition and then classify its meaning.

 I have gained the impression that this will always refer to
 interface or enumeration constants, but I  will recognize any
 counter-example, when someone points to it.
Tony Morris - 06 Feb 2006 03:59 GMT
> >>A variable is a storage location and has an associated type.
> >>A final variable may only be assigned to once.
> >Not quite - a final is "write once" only if it is a field.
>
>   Both sentences are quotations from the
>   Java Language Specification, Third Edition.

The JLS is full of contradictory text. I do not envy anyone who chooses to
implement such a specification.
It is for this reason, and many more, that I have resigned from my current
position.
Last day this Friday!!! yippeeeee!!!
In case you can't tell, I can't wait :)

Signature

Tony Morris
http://tmorris.net/

Chris Uppal - 06 Feb 2006 13:53 GMT
> The JLS is full of contradictory text. I do not envy anyone who
> chooses to implement such a specification.
> It is for this reason, and many more, that I have resigned from my
> current position.
> Last day this Friday!!! yippeeeee!!!
> In case you can't tell, I can't wait :)

Congrats !

Are you shunning the JLS ?  Java ?  Programming ?  I'm just curious:
please ignore this question if you don't care for it.

   -- chris
Tony Morris - 06 Feb 2006 22:13 GMT
> > The JLS is full of contradictory text. I do not envy anyone who
> > chooses to implement such a specification.
[quoted text clipped - 9 lines]
>
>     -- chris

If I shunned the JLS, I'd also be implicitly shunning all the other
specifications that are written in a horribly ambiguous language called
English. I concede to the reality - we have a very suboptimal situation. I
have always disliked the notion of passive whinging - that is, whinging
about something and not taking any proactive measures to change it - I am
doing my best as time permits.

4 days to go!! :)

Signature

Tony Morris
http://tmorris.net/

Roedy Green - 06 Feb 2006 03:41 GMT
On Sun, 05 Feb 2006 23:48:18 -0000, "Daniel Dyer"
<dan@dannospamformepleasedyer.co.uk> wrote, quoted or indirectly
quoted someone who said :

>>   In Java, only interfaces have constants; classes have constant
>>   variables.
>
>Isn't that an oxymoron?  It's like the sticker on my old Sony VAIO that  
>informed me of the available "optional essentials".

do interface constants have to be evaluated at compile time?
or can they be postponed till load time?
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Stefan Ram - 06 Feb 2006 03:47 GMT
>do interface constants have to be evaluated at compile time?
>or can they be postponed till load time?

     »Every field in the body of an interface must have an
     initialization expression, which need not be a constant
     expression. The variable initializer is evaluated and the
     assignment performed exactly once, when the interface is
     initialized.«

 Java Language Specification, Third Edition, 9.3.1,
Chris Uppal - 06 Feb 2006 11:44 GMT
> > do interface constants have to be evaluated at compile time?
> > or can they be postponed till load time?
[quoted text clipped - 4 lines]
>       assignment performed exactly once, when the interface is
>       initialized.«

But note that interface constants, being final, will normally be evaluated by
the compiler and hard-wired into the code that uses them.  The exceptions are
constants that are not initialised to a compile-time constant-valued expression
of numerical, boolean, or String type.

   -- chris
Roedy Green - 06 Feb 2006 01:54 GMT
>  In Java, only interfaces have constants; classes have constant
>  variables.

Java needs a terminology overhaul.

There are five quite different animals that people sometimes call
constants:

I attempt to follow a more precise terminology described at:

http://mindprod.com/jgloss/constants.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Andrew McDonagh - 05 Feb 2006 23:58 GMT
> I was advised in another thread to avoid creating interfaces that contained
> only constants; I was told that abstract classes were a better choice for
[quoted text clipped - 15 lines]
> How do I handle those cases? I'm afraid my OO theory isn't too strong so
> forgive me if the answer seems obvious to you; it isn't obvious to _me_

before you would have done something like.....

public interface ResumeConstants {
  public String HEADER = "Header";
}

public class ResumeWriter implements ResumeConstants {

   public void writeResume() {
      System.out.println(HEADER);
   }

}

Which you now know is not a good use of interfaces - its even thought of
as a anti-pattern.

So what to do....convert the interface into a class (as you have done),
and make the constants 'static'.

public class ResumeConstants {
   public static final String HEADER = "Header";
}

Now to make use of it...

public class ResumeWriter {

   public void writeResume() {
      System.out.println(ResumeConstants.HEADER);
   }

}

By making the constants static, it saves you having to instantiate the
ResumeConstants class in order to use its constants....e.g.

public class ResumeWriter {

   public void writeResume() {
      ResumeConstants  rc = new ResumeConstants();
      System.out.println( rc.HEADER );
   }

}

Now this business about making the constants class an abstract class....

If you try and use Inheritance you will always run into this type of
problem. This situation only ever calls for Delegation, not Inheritance.

In fact your designs will generally be much better if you 'favor
Delegation Over Inheritance' (nice and google-able term)

Even with Delegation, there's really only one valid reason for going the
Abstract class route, with these constants classes.... its to make it
difficult to instantiate the class like I just did above.  However,
making it Abstract merely prevents some one 'newing' the class directly,
it does not stop them creating a derived class and newing that instead.
 A better approach for be to make the default constructor 'private'.

As in...

public class ResumeConstants {
   public static final String HEADER = "Header";

   private ResumeConstants() {}
}

We sometimes do this if we think its a good thing to prevent this, but
there's always cases where we don't want to do this.

Going this route can actually leave you in as much trouble as having the
interface constants.  For example, say your constants were just that,
constants, but then we have a new business requirement that says we need
two or more different sets of constants, depending upon the user's
locale.  We'd be buggered if we used the approach above.

Instead, what we'd want to do it not directly access the constants
values, we want to get them via access methods (getters), but we'd want
to instantiate different ResumeUserLocaleConstants classes depending
upon locale, then use them in a polymorphic manner.

public interface UserLocaleDependantConstants {
   public String getHeader();
   public String getFooter();
   ...
}

public class UkUserConstants implements UserLocaleDependantConstants {
  // ... load UK values for the user constants...
}

public class USAUserConstants implements UserLocaleDependantConstants {
  // ... load USA values for the user constants...
}

public class FrenchUserConstants implements UserLocaleDependantConstants {
  // ... load French values for the user constants...
}

...

so we still have constants, just a different set are created at
application start up, or read from a server, or file, or....

HTH

Andrew
Chris Uppal - 06 Feb 2006 14:07 GMT
> Even with Delegation, there's really only one valid reason for going the
> Abstract class route, with these constants classes.... its to make it
> difficult to instantiate the class like I just did above.  However,
> making it Abstract merely prevents some one 'newing' the class directly,
> it does not stop them creating a derived class and newing that instead.

Granting the (unlikely, IMO, but not impossible) hypothesis that a
constants-only class is required, I find myself asking:

   a) Why would anyone want to instantiate it ?

   b) If someone did, why would one want to prevent them from doing so ?

   c) If this /is/ an issue, then what of Thomas Hawtin's point that an
       interface will achieve exactly the same thing with less clutter and
       semantic noise ?

> Going this route can actually leave you in as much trouble as having the
> interface constants.  For example, say your constants were just that,
> constants, but then we have a new business requirement that says we need
> two or more different sets of constants, depending upon the user's
> locale.  We'd be buggered if we used the approach above.

Agreed.  I just wanted to point out that if there /isn't/ an [anticipated]
business requirement to do so, then this kind of messing around is
over-engineering.  No criticism of your point intended, but I suspect that
Rhino's getting a bit confused with the range of "best-practise" that's being
recommended ;-)

   -- chris
Andrew McDonagh - 10 Feb 2006 23:36 GMT
>>Even with Delegation, there's really only one valid reason for going the
>>Abstract class route, with these constants classes.... its to make it
>>difficult to instantiate the class like I just did above.  However,
>>making it Abstract merely prevents some one 'newing' the class directly,
>>it does not stop them creating a derived class and newing that instead.

Sorry for the delay...been away on business all week...

> Granting the (unlikely, IMO, but not impossible) hypothesis that a
> constants-only class is required, I find myself asking:
>
>     a) Why would anyone want to instantiate it ?

I don't know, nor would I care personally.  But as the OP was after a
best practise and how they relate to Abstracts, I gave what we typically
see.

>     b) If someone did, why would one want to prevent them from doing so ?

ditto above...

>     c) If this /is/ an issue, then what of Thomas Hawtin's point that an
>         interface will achieve exactly the same thing with less clutter and
>         semantic noise ?

It doesn't achieve the same thing though.  A class making use of another
constants class via delegation encapsulates that usage.

If that class derives from a constants class or implements a constants
interface, then that class's own public interface now exposes those
constants - breaking encapsulation.

>>Going this route can actually leave you in as much trouble as having the
>>interface constants.  For example, say your constants were just that,
[quoted text clipped - 9 lines]
>
>     -- chris

Sure, I was merely attempting to give a (granted overly complex) example
of what possible benefits of putting constants  behind a class and using
getters to retrive them.

Andrew
Thomas Hawtin - 11 Feb 2006 12:13 GMT
>>     c) If this /is/ an issue, then what of Thomas Hawtin's point that an
>>         interface will achieve exactly the same thing with less
[quoted text clipped - 7 lines]
> interface, then that class's own public interface now exposes those
> constants - breaking encapsulation.

My point was that if you declare constants (and only constants) in an
interface then you can ditch the "public static final" noise. From the
source or the JavaDocs it is easy to see an interface of this form for
what it is. I was not suggesting the interface should be implemented.

I do not think legislating against stupidity on the part of client code
is a high priority. The author of the client code has to set out to
implement the interface, and if they do that then it's their own fault.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Andrew McDonagh - 10 Feb 2006 23:36 GMT
>>Even with Delegation, there's really only one valid reason for going the
>>Abstract class route, with these constants classes.... its to make it
[quoted text clipped - 12 lines]
>         interface will achieve exactly the same thing with less clutter and
>         semantic noise ?

oh... for those interested...

http://java.sun.com/j2se/1.5.0/docs/guide/language/static-import.html
Rhino - 06 Feb 2006 15:53 GMT
>> I was advised in another thread to avoid creating interfaces that
>> contained only constants; I was told that abstract classes were a better
[quoted text clipped - 121 lines]
> so we still have constants, just a different set are created at
> application start up, or read from a server, or file, or....

Thank you VERY much Andrew! Your explanation was very clear and
well-reasoned in all respects.
Once you explained that I shouldn't be implementing or extending the
classes, everything else fell into place.

I see why this is the recommended approach and have gone ahead and changed
my two constants interfaces into classes containing only public static final
constants along the lines you proposed. Naturally, I'll follow this approach
in future projects as well and will gradually retrofit this approach to
older projects as time permits.

I feel better knowing that I'm doing things the proper way. I just wish I'd
known that interfaces were a bad way to handle constants earlier; I feel
like I'm only just discovering something that the rest of the (Java) world
has known for years :-)

--
Rhino
Tony Morris - 06 Feb 2006 03:26 GMT
> I was advised in another thread to avoid creating interfaces that contained
> only constants; I was told that abstract classes were a better choice for
> something that only contains constants.

You have been misled.
Assuming your true objective is not fulfilled by an enumeration, and indeed
requires you to write code that uses constant expressions, the optimal
solution is the use of a final class - which is mutually exclusive from an
abstract class and is quite the opposite. The class should declare a private
constructor with a throws clause that specifies a single unchecked exception
(such as java.lang.UnsupportedOperationException). The constructor should
explicitly throw this exception as its only statement. Your constants should
be specified using public static final fields, which indeed should be
constants - and not finals, which is a common cause of confusion.

Signature

Tony Morris
http://tmorris.net/

zero - 06 Feb 2006 12:54 GMT
> Assuming your true objective is not fulfilled by an enumeration, and
> indeed requires you to write code that uses constant expressions, the
> optimal solution is the use of a final class - which is mutually
> exclusive from an abstract class and is quite the opposite.

A final class may indeed be better for this purpose.  Note that in my
original post about this, I said "Use a non-instantiable (for example
abstract) and preferably final class"

I completely disagree with the fact that abstract and final are mutually
exclusive.  While it is true that the concepts are eachother's opposites
(abstract classes are meant to be extended, final classes can't be), it is
perfectly possible to have code like this:

public abstract class AbstractFinal
{
  private AbstractFinal() {}

  // a bunch of constants and perhaps static methods
  // never call the AbstractFinal constructor
}

While this class is not declared as final, it is effectively final because
it cannot be extended.  This can be made even more clear if the constructor
throws an InstantiationException.

Yes this is an improper use of abstract classes, and the same could (and
maybe should) be done just by having a final class with a private
constructor.  However I don't see the above code ever leading to problems.
Chris Smith - 06 Feb 2006 21:20 GMT
> I completely disagree with the fact that abstract and final are mutually
> exclusive.

The JLS doesn't, though.  8.1.1.2: "A compile-time error occurs if a
class is declared both final and abstract".

Your example shows a non-final abstract class, which can't be
subclassed.  The concepts of "class that can't be instantiated" and
"abstract class" are related, but not identical.  The latter is a subset
of the latter.

Put in a more interesting way, the keyword "abstract" carries certain
implications, beyond the mere inability to create an instance.  It
implies that correct usage of that class involves overriding some class
behaviors.  For that reason, it doesn't make sense to make a class
abstract if it shouldn't be subclassed.  The lack of an accessible
constructor is good enough to express that idea.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Tony Morris - 06 Feb 2006 22:14 GMT
> > Assuming your true objective is not fulfilled by an enumeration, and
> > indeed requires you to write code that uses constant expressions, the
[quoted text clipped - 7 lines]
> I completely disagree with the fact that abstract and final are mutually
> exclusive.

When I said it, I mean, a class can be abstract, final, neither, but never
both.
A class with a private constructor is not final - and not even "effectively
final" - I'll leave it at that for anyone curious who wishes to investigate
the issue more thoroughly.

Signature

Tony Morris
http://tmorris.net/

Adam Maass - 06 Feb 2006 05:03 GMT
>I was advised in another thread to avoid creating interfaces that contained
>only constants; I was told that abstract classes were a better choice for
[quoted text clipped - 15 lines]
> How do I handle those cases? I'm afraid my OO theory isn't too strong so
> forgive me if the answer seems obvious to you; it isn't obvious to _me_

Implementing an interface to get the constants it defines is considered an
anti-pattern; you have at least one (and possibly many) instances of this
anti-pattern in your code. The required change is to:

1) Remove the "implements ResumeConstants" phrase from the class
declaration;
2) Qualify all references to constants:

where before you had:

A

you now need:

ResumeConstants.A

Hope that helps...
Chris Uppal - 06 Feb 2006 12:32 GMT
> I was advised in another thread to avoid creating interfaces that
> contained only constants;

So far so good ;-)

> I was told that abstract classes were a better
> choice for something that only contains constants.

It may, and in my experience nearly always does, make more sense to attach the
constants to the class to which they pertain.  I.e. while there can be reasons
to create a class just to hold constants, it is rarely necessary or desirable.
(And, frankly, in those rare cases it makes no difference at all whether you
use an abstract class or an interface -- it's a hack either way -- just don't
make the mistake of trying to inherit ("extends" or "implements") the class
containing the constants.  Use the constants, don't inherit them).

Classes that are clients of other classes can use the constants defined by the
other classes if those constants are public (which they should be /if/ they
are intended for use by other classes).

   -- chris
Roedy Green - 06 Feb 2006 14:22 GMT
On Mon, 6 Feb 2006 12:32:36 -0000, "Chris Uppal"
<chris.uppal@metagnostic.REMOVE-THIS.org> wrote, quoted or indirectly
quoted someone who said :

>It may, and in my experience nearly always does, make more sense to attach the
>constants to the class to which they pertain.  

If you do have a Configure class where configuring constants are
concentrated for tweaking, you can get the interface-like ability to
access the fields without qualification if you use the import static
feature of JDK 1.5.

The advantage of using a Configure class over a properties file, is
you can do computation if need be to decide the various parameters.
Further you get very good syntax checking on it long before execution
starts.  You can configure things other than simple strings.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Rhino - 06 Feb 2006 14:32 GMT
>> I was advised in another thread to avoid creating interfaces that
>> contained only constants;
[quoted text clipped - 10 lines]
> to create a class just to hold constants, it is rarely necessary or
> desirable.

Ahh, now we get to the heart of the issue....

In my case, I have several classes that are writing various formats of
resumes. (Yes, that same project we've been discussing for weeks now.) The
various resume writer classes share a variety of constants, like the fonts
to use in particular parts of the document, the color palette to use, the
name of the log file to use for reporting errors, etc. I want all of the
classes in _this_ project to use certain values for those things but I don't
want all of the classes in _all_ of my projects to use those same values.

It makes no sense to me to define LOG_FILE_NAME separately in each of 10 or
15 classes that use it, particularly if there is a chance that I may want to
change the value of that constant. If my log file is current "Resume.log"
and I decide to change it to "CV.log", I _really_ don't want to have to
change its value in 10 or 15 separate classes; I just want to change it once
and have each class see the change.

Surely you're not suggesting that I should have 10 or 15 separate
definitions of LOG_FILE_NAME and then have to change each individually? This
seems like a very obvious case for storing these definitions once - whether
in an interface or a class - and then sharing them amongst all of the
classes that need them. Or does OO propose a different way althogether of
handling this very common situation?

> (And, frankly, in those rare cases it makes no difference at all whether
> you
[quoted text clipped - 3 lines]
> class
> containing the constants.  Use the constants, don't inherit them).

Okay, fair enough. But what is the _right_ way to share constants amongst a
subset of your classes if interfaces or classes containing only constants
are a hack?

> Classes that are clients of other classes can use the constants defined by
> the
> other classes if those constants are public (which they should be /if/
> they
> are intended for use by other classes).

How? Is this where 'import static' comes in, as Stephan and others have
suggested elsewhere in this thread?

--
Rhino
Robert Klemme - 06 Feb 2006 15:10 GMT
> Ahh, now we get to the heart of the issue....
>
[quoted text clipped - 22 lines]
> propose a different way althogether of handling this very common
> situation?

From what you write your constants seem to be rather some kind of
configuration information.  In that case I'd consider using Properties
(although they do have some drawbacks as Roedy pointed out; you can of
course wrap them in some class that gives safer / better access to config
values).

Kind regards

   robert
Ed - 06 Feb 2006 15:56 GMT
Robert Klemme skrev:

> From what you write your constants seem to be rather some kind of
> configuration information.  In that case I'd consider using Properties
[quoted text clipped - 5 lines]
>
>     robert

Just what I was thinking.

And I do have a wrapper Option interface (other big beneft: no GUI
updates for each new configuration parameter); various packages
retrieve the specific option implementation they need by doing
something like:

Option option = options.getOption("parser type");

Except that that string is, of course, a final string declared in a
central location. Where? In the Options interface. Which brings us back
to your original point.

Option option = options.getOption(Options.PARSER_TYPE_TAG);

.ed

--
www.EdmundKirwan.com - Home of The Fractal Class Composition.
Rhino - 06 Feb 2006 16:41 GMT
>> Ahh, now we get to the heart of the issue....
>>
[quoted text clipped - 28 lines]
> course wrap them in some class that gives safer / better access to config
> values).

Yeah, I guess something like Properties or Roedy's variant on Properties
might be a better way to go.... But as Ed has pointed out in this thread,
that would appear to call for constants being defined somewhere as well,
probably in an interface.

If I'm going to end up with constants in an interface anyway, it makes me
wonder why I would complicate my life with Properties or Configure classes
_AND_ an interface when an interface alone is working just fine right now.
Doesn't some variant of Occam's Razor suggest that an interface alone is
better than an interface plus other classes to accomplish the same end?

If every solution ultimately ends with an interface of constants anyway, is
this just an exercise in coming up with the most sound reason for having an
interface of constants rather than convincing ourselves that an interface of
constants is a bad idea altogether? Maybe we're just proving that an
interface of constants needs to be in the solution regardless but are just
quibbling over WHY it needs to be there?

--
Rhino
Andrea Desole - 06 Feb 2006 15:57 GMT
> Ahh, now we get to the heart of the issue....
>
[quoted text clipped - 19 lines]
> classes that need them. Or does OO propose a different way althogether of
> handling this very common situation?

I don't really know how your code works, but what about a logger class?
There you can define your log operations and your static LOG_FILE_NAME,
which, by the way, doesn't even need to be public, since it's used only
by the logger.
Rhino - 06 Feb 2006 16:32 GMT
>> Ahh, now we get to the heart of the issue....
>>
[quoted text clipped - 25 lines]
> which, by the way, doesn't even need to be public, since it's used only by
> the logger.

That might be reasonable in the specific case of the log file but I was just
using that as an example of the bigger question of managing constants that
are used by several classes when I usually want all of those classes to
share the exact same values for the constants.

I don't think I want to create new classes for each and every constant that
is shared among multiple classes just to keep from using an interface
containing only constants; that would appear to make the cure worse than the
disease. Or am I not understanding your point correctly?

--
Rhino
Andrea Desole - 06 Feb 2006 17:19 GMT
> That might be reasonable in the specific case of the log file but I was just
> using that as an example of the bigger question of managing constants that
> are used by several classes when I usually want all of those classes to
> share the exact same values for the constants.

i know. The point is that it's difficult to tell more because I don't
know the code, so I wanted to use your example to tell how a constant is
 declared in the class it refers to, without declaring an external
class/interface. This is, I guess, what also Chris meant

> I don't think I want to create new classes for each and every constant that
> is shared among multiple classes just to keep from using an interface
> containing only constants; that would appear to make the cure worse than the
> disease. Or am I not understanding your point correctly?

that's not really what I mean. The first thing I thought when I saw your
log example was "well, that constant refers to logging, as well as all
the log operations; that would fit nicely into a log class". Another
option is to think "the location/name of the log file is something that
should be configured, together with some other properties; this would
fit nicely into a configuration class". This is something that has
already been suggested, I guess.
So my point is that you usually use a constant that is related to
something, or is used by something, and that something is usually a
class. There you can declare your constant. Where and how (and also if,
since it may not be the case) depends on your code. For example, you
might have a class ResumeWriter which takes care of writing your text.
That class is subclassed by all the specific format writer. In that
class you can declare your constant font information as static
variables. Or you can add it to the already mentioned configuration
object; which, by the way, seems a better solution, since I would
personally like all this information to be configurable.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.