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 / June 2005

Tip: Looking for answers? Try searching our database.

Why Generics?

Thread view: 
David Blickstein - 04 May 2005 19:36 GMT
In Java5, the powers that be added generics.

Can someone please explain to me what value they add to Java?   I think they
are one of the biggest (of many big) mistakes in C++.  And I always felt
that they only reason they were in C++ was because it made the huge mistake
of not having a common root for the entire class hierarchy: Java's Object
type.

Java didn't need any language features to implement container classes
because of this.   An reference of type Object can hold ANY Object.

The biggest objection I've ever heard to that is it forces you to cast down
when you extract from the container.  Big deal!

That's nothing compared to what I've always had to go thru to make generics
work in C++.

Am I missing something or did C++ weenies invade the language committee?
Eric Sosman - 04 May 2005 20:07 GMT
> In Java5, the powers that be added generics.
>
[quoted text clipped - 14 lines]
>
> Am I missing something or did C++ weenies invade the language committee?

   It was the C++ weenies, definitely.  You're entirely
correct: The C++ saboteurs have contaminated Java with
generics simply and only to make the language unattractive
and cause its ultimate demise.  The Java people have been
suckered into kissing the Bjarne Stone.

   Oh, yeah, and one other teeny-tiny thing: If you make
a mistake, it gets diagnosed at compile time instead of at
run time.  Which would you rather receive: a compiler error
that you alone see, or a ClassCastException with all the
honchos from The Big Customer watching?  If you'd prefer
the former, learn to like generics.

Signature

Eric.Sosman@sun.com

Betty - 04 May 2005 20:16 GMT
<snip>

> > Am I missing something or did C++ weenies invade the language committee?
>
[quoted text clipped - 10 lines]
> honchos from The Big Customer watching?  If you'd prefer
> the former, learn to like generics.

Just curious, would you say it is possible to write good
programs and not use the generics feature? Or does it make
some things so much better that it is compelling?
Eric Sosman - 04 May 2005 21:06 GMT
> <snip>
>
[quoted text clipped - 16 lines]
> programs and not use the generics feature? Or does it make
> some things so much better that it is compelling?

   Is it possible to write good code without generics?
Well, it depends on what you mean by "good."  What's your
opinion of all the Java code written in the first nine
years of the language's existence?  Is it uniformly "bad?"

   The value proposition of generics, it seems to me, lies
purely in the fact that they make some kinds of mistakes
diagnosable by the compiler instead of by the JVM.  Every
study I've ever heard of concludes that the cost of a bug
increases the longer it remains in the code, so a bug found
by the compiler should cost less than a bug found by testing
(or *not* found by testing ...).

Signature

Eric.Sosman@sun.com

John C. Bollinger - 04 May 2005 22:06 GMT
>     The value proposition of generics, it seems to me, lies
> purely in the fact that they make some kinds of mistakes
> diagnosable by the compiler instead of by the JVM.

I see some value in the additional self documentation provided by
generic declarations.  I also think there is a certain degree of
usefulness simply in organizing your thoughts at design and early
development time well enough to write type constraints.

Signature

John Bollinger
jobollin@indiana.edu

Chris Smith - 04 May 2005 23:40 GMT
> >     The value proposition of generics, it seems to me, lies
> > purely in the fact that they make some kinds of mistakes
[quoted text clipped - 4 lines]
> usefulness simply in organizing your thoughts at design and early
> development time well enough to write type constraints.

Absolutely!  The self-documentation aspect of generics is, IMHO, *far*
more important than the type-safety, which is really just a consequence
of the former.  I have never seen a ClassCastException myself except in
code designed to generate it for learning purposes... and I don't know
of anyone who has; but that doesn't mean that generics are useless.  
Anything that prevents a formulaic comment of the form "Elements are of
class String" is good.  I have nothing against comments, but I do have
problems with the need for them when it can be avoided.

Signature

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

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

miz - 05 May 2005 02:15 GMT
and if i never have to type ((MyBean)myArrayList.get(i)).getMyBeanMethod(),
all the better.

>> >     The value proposition of generics, it seems to me, lies
>> > purely in the fact that they make some kinds of mistakes
[quoted text clipped - 13 lines]
> class String" is good.  I have nothing against comments, but I do have
> problems with the need for them when it can be avoided.
Dale King - 25 May 2005 05:15 GMT
> Absolutely!  The self-documentation aspect of generics is, IMHO, *far*
> more important than the type-safety, which is really just a consequence
> of the former.  I have never seen a ClassCastException myself except in
> code designed to generate it for learning purposes... and I don't know
> of anyone who has; but that doesn't mean that generics are useless.  

I would ammend that to say that of the times that you actually would see
ClassCastExceptions, generics are actually not likely to help either as
you probably have a collection with a mixed contents unless you have
serious bugs.

Signature

 Dale King

John C. Bollinger - 25 May 2005 15:35 GMT
>> Absolutely!  The self-documentation aspect of generics is, IMHO, *far*
>> more important than the type-safety, which is really just a
[quoted text clipped - 7 lines]
> you probably have a collection with a mixed contents unless you have
> serious bugs.

You mean that probably the collection *intentionally* has mixed
contents, and therefore no appropriate type parameter can be applied?
Yes, in that case generics don't directly help you.  Even there,
however, they may make you think a little more about the design in the
first place, and that can only be a good thing when considering an
approach that defies static type checking.  I don't mean to say that
such approaches are always incorrect, but they are trickier and
typically more fragile.

Signature

John Bollinger
jobollin@indiana.edu

Thomas G. Marshall - 25 May 2005 23:48 GMT
Chris Smith coughed up:

>>>     The value proposition of generics, it seems to me, lies
>>> purely in the fact that they make some kinds of mistakes
[quoted text clipped - 14 lines]
> against comments, but I do have problems with the need for them when
> it can be avoided.

Your conclusion is probably correct, but you are discounting not to small a
segment of would-be generics users (in 1.4 and prior).  Many pre-1.5
engineers are spooked by the fact that a collection would hold any kind of
object, and as a result, they design a modified beast specific to the task.
In other words, part of the reason that you have not seen many CCE's is that
engineers have worked hard to avoid them.

Signature

"So I just, uh... I just cut them up like regular chickens?"
"Sure, just cut them up like regular chickens."

Chris Uppal - 26 May 2005 10:11 GMT
> Many pre-1.5
> engineers are spooked by the fact that a collection would hold any kind of
> object, and as a result, they design a modified beast specific to the
> task.

This observation (which I don't disagree with) can also be viewed the other way
around.  Pre 1.5 programmers would create real objects with real, thought-out,
responsibilities.  Now the temptation is just to use a generic utility class
instead.

Naturally, the picture isn't as black-and-white as I've painted it.  In some
cases the creation of custom type-safe classes was really just a waste of time,
which generics can reclaim for us.  In other cases generics will lure people
into poor OO.  Presumably there are intermediate cases too...

   -- chris
Thomas G. Marshall - 27 May 2005 00:31 GMT
Chris Uppal coughed up:

>> Many pre-1.5
>> engineers are spooked by the fact that a collection would hold any
[quoted text clipped - 11 lines]
> cases generics will lure people into poor OO.  Presumably there are
> intermediate cases too...

Right.  Which is why generics might end up being a win at the bottom line
after all.  And it certainly isn't enough to counter with "well I never saw
a ClassCastException", for the reason I gave.  Not that your logic derived
entirely from that---it's just a statement that I see floating around far
too often.

IMO, there are far too many variables here to try to boil it down to
something that simplistic.

Signature

Framsticks.  3D Artificial Life evolution.  You can see the creatures
that evolve and how they interact, hunt, swim, etc. (Unaffiliated with
me). http://www.frams.alife.pl/

David Blickstein - 06 Jun 2005 15:53 GMT
> Chris Smith coughed up:

> >> I see some value in the additional self documentation provided by
> >> generic declarations.

Interesting.   I see generics as a step BACKWARDS with regard to
"self-documentation".

In the realm of C++, I've always considered one of the DISADVANTAGES of
templates as being to provide a way to AVOID having to document an
interface.

Let me explain.

Correct me if I'm wrong, but... in C++ templates classes can implement
PRESUMPTIONS about the parameterized types.   That is, I can write a
template class that ASSUMES that one of the parameterized class-types I pass
in provides a method called "m".

This is commonly used in C++ to avoid the confusion, performance penalties
and overall ugliness of multiple-inheritance.

Now I haven't used generics in Java (I'm leaning heavily towards FORBIDDING
their use in all but the container classes but...

Isn't it true that I can write generics in Java that make presumptions about
the type that have absolutely ZERO "documentation" other than any comments
the implementer is gracious enough to provide?   ISn't it true that even
Javadoc will NOT give ANY indication of this vital piece of information?

That is, can't I (in Java as in C++) write a generic class that presumes the
class type passed in implements a particular combination of methods and
fields?   And is it not true that there's no way in the language (other than
comments) to say that "this type parameter must be assignment-compatible
with a particular class or interface?

So... unless I'm missing something about generics, it strikes me that while
it does provide a mildly useful piece of documentation about types, it also
opens the door for writing code that is far more likely to create a more
serious documentation gap than the one it "fixes"?

   db

p.s.  I must say that thus far, I personally have seen no remotely
compelling arguments for generics in Java.    But that's just my opinion.
To me templates in C++ were a mistake created to fix another of uncle
Bjarne's mistakes: not providing a common root for class types.   A classic
C++ blunder on top of blunder.

One of the things I like about Java is that unlike C++, it is very
well-designed and avoided the vast amount of mistakes made in C++.   It's a
bit disturbing to see a mistake in C++ start creeping in.

I've been told that the main reason that C++'s STL hasn't caught on is that
its so difficult to avoid the pratfalls set up by its use of templates (code
bloat, etc.... all those things mentioned in Meyer's "Defective C++" book).
(FYI: Sun's HotSpot is essential STL-free.)

Compare the adoption of STL with that of Java's JRE.    No one thinks twice
about using the JRE.
Chris Smith - 06 Jun 2005 16:48 GMT
> Interesting.   I see generics as a step BACKWARDS with regard to
> "self-documentation".
>
> In the realm of C++, I've always considered one of the DISADVANTAGES of
> templates as being to provide a way to AVOID having to document an
> interface.

Yes, that is true of C++.

> Now I haven't used generics in Java (I'm leaning heavily towards FORBIDDING
> their use in all but the container classes but...
[quoted text clipped - 3 lines]
> the implementer is gracious enough to provide?   ISn't it true that even
> Javadoc will NOT give ANY indication of this vital piece of information?

No, none of that is true.  Type parameters to types in Java have bounds,
and the class of potential operations on a type is limited to those that
can safely be performed within those bounds.  For example, you can look
at a class that is declared as:

   class MyClass<T extends Number> { ... }

and know that the class does not use the type parameter T in any way
except what can be done to a generic number.

In other words, all of your concerns about templates in C++ are valid,
but they do not apply to generics in Java (by which I don't mean that
they only partially apply; I mean they do not apply at all).

> It's a bit disturbing to see a mistake in C++ start creeping in.

This is a case where you should learn how something works before you
criticize it.  There are lots of ways to criticize Java's generics, and
I agree with most of them (especially that they create unsolvable
compile-time warnings, especially when working with older APIs) but this
isn't one.

Signature

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

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

David Blickstein - 06 Jun 2005 20:04 GMT
> This is a case where you should learn how something works before you
> criticize it.  There are lots of ways to criticize Java's generics, and
> I agree with most of them (especially that they create unsolvable
> compile-time warnings, especially when working with older APIs) but this
> isn't one.

I did read up on generics, but given that I saw ABSOLUTELY zero pragmatic
value to them (moving detection of an error that rarely happens from runtime
to compiletime, and a minor "documentation" value) and lots of reasons to
dislike them (which you seem to acknowledge) I guess I didn't commit what I
learned to permanent memory.

Look, I still think that they do NOT add any substantive value to the
language.  And while it would appear that the Java folks have eliminated
many of Uncle Bjarne's goofs, at the end of the day they don't add to Java
as much as they add to C++.  And the only reason that they add anything
substantive to C++ is because of ANOTHER of Uncle Bjarne's goofs (not
providing a root for the class system).
Thomas G. Marshall - 07 Jun 2005 00:23 GMT
David Blickstein coughed up:
>> This is a case where you should learn how something works before you
>> criticize it.  There are lots of ways to criticize Java's generics,
[quoted text clipped - 5 lines]
> pragmatic value to them (moving detection of an error that rarely
> happens from runtime to compiletime,

You may have read up on it, and you may have drawn such a conclusion, yet I
noticed that you snipped away and didn't comment on Chris's correction of
your suppositions.

Furthermore, as I've pointed out repeatedly, the fact that an error rarely
happens doesn't mean that there isn't something considerable to gain by
having it detected.  The fact that CCE's rarely happen is due in large part
to the fact that engineers are aware of its danger.  Generics have at least
the potential to lessen the degree of defensive coding needed.  I have
suspicions that generics don't save much in regards to the bottom line, but
it isn't because the CCE rarely happened.  Saying so is just a bunch of
broken logic.

> and a minor "documentation"
> value) and lots of reasons to dislike them (which you seem to
[quoted text clipped - 7 lines]
> that they add anything substantive to C++ is because of ANOTHER of
> Uncle Bjarne's goofs (not providing a root for the class system).

Signature

Sometimes life just sucks and then you live.

David Blickstein - 07 Jun 2005 15:12 GMT
> You may have read up on it, and you may have drawn such a conclusion, yet I
> noticed that you snipped away and didn't comment on Chris's correction of
> your suppositions.

I'm not sure what sort of comment you were expecting.

I think I did "acknowledge" the correction via saying that DESPITE the fact
that Java generics fix one of the biggest of Uncle Bjarne's mistakes with
templates, the justification I've heard for them doesn't even fall within
earshot of the line of sufficiency.
Phillip Lord - 05 May 2005 10:10 GMT
>>>>> "Eric" == Eric Sosman <eric.sosman@sun.com> writes:

 >> Just curious, would you say it is possible to write good programs
 >> and not use the generics feature? Or does it make some things so
 >> much better that it is compelling?

 Eric>     Is it possible to write good code without generics?
 Eric> Well, it depends on what you mean by "good."  What's your
 Eric> opinion of all the Java code written in the first nine years
 Eric> of the language's existence?  Is it uniformly "bad?"

Good or bad code is clearly not determinable by the language features
used. Or, indeed, the language used.

 Eric> The value proposition of generics, it seems to me, lies purely
 Eric> in the fact that they make some kinds of mistakes diagnosable
 Eric> by the compiler instead of by the JVM.  Every study I've ever
 Eric> heard of concludes that the cost of a bug increases the longer
 Eric> it remains in the code, so a bug found by the compiler should
 Eric> cost less than a bug found by testing (or *not* found by
 Eric> testing ...).

The difficulty here is that there are also costs associated with
generics. In the case of Java generics, the system is relatively
dumb; you have to tell the compiler a lot in code to get it to give
you the guarantees that it can. Actually this is true for Java types
in general

Frame f = new Frame()

Why two "Frame"'s (I do know why! Please don't tell me!). It would be
nice if the type system could infer more from less information.

Of course, it's very hard to judge whether some feature is worth the
cost or not. In the end, it depends on how easy it is for a programmer
to use the system, which depends on how sensible it seems to them.

Personally, I was always a big fan of the idea of generics, and
watched from the early possible implementions (GJ, poors mans
generics, Pizza and all that jazz). Sadly, after all of these years of
waiting, I write very litte code, so haven't got around to trying
generics in anger. For me, therefore, the question of whether they are
good or not, will remain unanswered.

Cheers

Phil
Bent C Dalager - 05 May 2005 14:28 GMT
>Good or bad code is clearly not determinable by the language features
>used. Or, indeed, the language used.

If this is true in general, then it shouldn't be possible to construct
a programming language that forces you to write "bad" code. I'd like
to see you write anything beyond a trivial program in Intercal and be
able to call the result "good code." :-)

In fact, even a trivial program would be impressive.

Intercal is a programming language deliberately designed to be
idiotic. While it is little more than a joke taken a bit too far, it
does demonstrate that it is possible to make a programming language
that gives you little to no chance of producing "good" code. As such,
it serves to lend credence a statement of the type "it is possible to
construct a programming language that forces programmers to write
worse code than what they would have done had they used programming
language X". X being your favourite language.

If this is the case, then it is reasonable to assume that there exists
some sort of scale, at (or near) the one extreme of which you can find
Intercal and at the other end there exists a hypothetical (perhaps
impossible) language that forces you to always write good code.

Somewhere in between these two, then, we will find the workhorse
languages that we all know and love. It would be remarkable if Java,
C, C++, C#, Pascal, Fortran, etc., all happened to be at exactly the
same spot on this scale. Rather, it is reasonable to assume that the
different languages lend themselves to varying degrees to writing
"good" code. (I certainly don't dismiss the idea that this goodness
scale may be a multi-dimensional beast - chances are that it is - but
that isn't terribly important for the current discussion.)

So I don't think it is clear at all that good or bad code is not
determinable by the language chosen (although I can only provide
compelling evidence for the case of a language determining that your
code should be bad). More importantly, though, I expect that different
languages have widely varying properties in this respect and that your
choice of language puts an upper limit on how good your code can be
(for your given domain). Moreover, I expect that choosing a "good"
language is likely to enable you to produce good code with
considerably less cost than you could with a "worse" language.

Cheers
    Bent D
Signature

Bent Dalager - bcd@pvv.org - http://www.pvv.org/~bcd
                                   powered by emacs

Tim Tyler - 10 May 2005 17:44 GMT
Bent C Dalager <bcd@pvv.ntnu.no> wrote or quoted:

> >Good or bad code is clearly not determinable by the language features
> >used. Or, indeed, the language used.
[quoted text clipped - 8 lines]
> Intercal is a programming language deliberately designed to be
> idiotic. [...]

http://www.catb.org/~esr/intercal/

See also:

http://c2.com/cgi/wiki?WhitespaceLanguage
http://www.madore.org/~david/programs/unlambda/
http://www.muppetlabs.com/~breadbox/bf/

Those programmers need to get girlfriends ;-)
Signature

__________
|im |yler  http://timtyler.org/  tim@tt1lock.org  Remove lock to reply.

Thomas G. Marshall - 05 May 2005 16:28 GMT
Phillip Lord coughed up:
>>>>>> "Eric" == Eric Sosman <eric.sosman@sun.com> writes:

...[rip]...

>  Eric>     Is it possible to write good code without generics?
>  Eric> Well, it depends on what you mean by "good."  What's your
[quoted text clipped - 3 lines]
> Good or bad code is clearly not determinable by the language features
> used. Or, indeed, the language used.

Right.  Well, except in the case of Perl, where all such code is uniformly
bad.  :)

>  Eric> The value proposition of generics, it seems to me, lies purely
>  Eric> in the fact that they make some kinds of mistakes diagnosable
[quoted text clipped - 14 lines]
> Why two "Frame"'s (I do know why! Please don't tell me!). It would be
> nice if the type system could infer more from less information.

Interesting point.   I suppose a valid default might have been:

   Frame f = new(asdfasdfasdf)

Allowing of course for this as well:

   Frame f = new SubFrame(asdfasdf);

for Poly-m. {shrug}

...[rip]...

Signature

Everythinginlifeisrealative.Apingpongballseemssmalluntilsomeoneramsitupyournose.

Phillip Lord - 05 May 2005 17:16 GMT
>>>>> "Thomas" == Thomas G Marshall <tgm2tothe10thpower@replacetextwithnumber.hotmail.com> writes:

 Thomas> Phillip Lord coughed up:
 >>>>>>> "Eric" == Eric Sosman <eric.sosman@sun.com> writes:

 Thomas> ...[rip]...

 Eric> Is it possible to write good code without generics?  Well, it
 Eric> depends on what you mean by "good."  What's your opinion of
 Eric> all the Java code written in the first nine years of the
 Eric> language's existence?  Is it uniformly "bad?"
 >>
 >> Good or bad code is clearly not determinable by the language
 >> features used. Or, indeed, the language used.

 Thomas> Right.  Well, except in the case of Perl, where all such
 Thomas> code is uniformly bad.  :)

I'm a bioinformatician, so I write a lot of perl. I have some distinct
sympathy with this position. Although, I suspect it comes from a
position of ignorance. Many people think that all perl is write
only. Believe me, it really is possible to make this harder than it
needs to be. The distressing thing with Perl is that there are too
many perl hackers who think that incomprehensible code is
"clever". It's not.

 Eric> The value proposition of generics, it seems to me, lies purely
 Eric> in the fact that they make some kinds of mistakes diagnosable
 Eric> by the compiler instead of by the JVM.  Every study I've ever
 Eric> heard of concludes that the cost of a bug increases the longer
 Eric> it remains in the code, so a bug found by the compiler should
 Eric> cost less than a bug found by testing (or *not* found by
 Eric> testing ...).
 >>
 >> The difficulty here is that there are also costs associated with
 >> generics. In the case of Java generics, the system is relatively
 >> dumb; you have to tell the compiler a lot in code to get it to
 >> give you the guarantees that it can. Actually this is true for
 >> Java types in general
 >>
 >> Frame f = new Frame()
 >>
 >> Why two "Frame"'s (I do know why! Please don't tell me!). It
 >> would be nice if the type system could infer more from less
 >> information.

 Thomas> Interesting point.  I suppose a valid default might have
 Thomas> been:

 Thomas>     Frame f = new(asdfasdfasdf)

 Thomas> Allowing of course for this as well:

 Thomas>     Frame f = new SubFrame(asdfasdf);

 Thomas> for Poly-m. {shrug}

Or just

f = new Frame.

We now know that f is at least Frame. If I choose to use it later with

f = new SubFrame()

this is okay. If I do

f = new ClassWhichIsNotFrameOrSubClass()

then it's not. Of course, it's not necessarily possible to just bolt
this sort of technology on to a language. SML gets it right in this
regard, but is highly unusuable in other ways. Whether the
unusuability in other ways is an (indirect and necessary) consequence
of the good type system, I'm not really qualified to say.

Phil
Thomas G. Marshall - 06 May 2005 00:48 GMT
Phillip Lord coughed up:
>>>>>> "Thomas" == Thomas G Marshall
>>>>>> <tgm2tothe10thpower@replacetextwithnumber.hotmail.com> writes:
[quoted text clipped - 16 lines]
>
> I'm a bioinformatician, so I write a lot of perl

(?) Why does one imply the other?

> I have some distinct
> sympathy with this position. Although, I suspect it comes from a
> position of ignorance.

Which: Is it my position or your sympathy that comes from ignorance?

I assure you that I've done Quite A Lot (tm) in perl.  But I have been
around the block enough times to know that when a language lends itself to
terseness and obfuscation that there will be many an engineer that will
attempt the most terse and most obfuscated production code.

Everyone knows that a language is better when it has things like $| and $<
in it with such obvious meanings. :)

> Many people think that all perl is write
> only. Believe me, it really is possible to make this harder than it
> needs to be. The distressing thing with Perl is that there are too
> many perl hackers who think that incomprehensible code is
> "clever". It's not.

...[rip]...

>  >> The difficulty here is that there are also costs associated with
>  >> generics. In the case of Java generics, the system is relatively
[quoted text clipped - 22 lines]
>
> f = new Frame.

No, because now you're in dynamically typed language territory, and that
would (without doubt) ignite a flame war :) .  What we were discussing were
mere shortcuts, or so I thought.  Unless of course that the f = new Frame is
short cut for Frame f = new Frame, and not something else like Object f =
new Frame.

...[rip]...

Signature

Forgetthesong,I'dratherhavethefrontallobotomy...

Adam P. Jenkins - 06 May 2005 05:40 GMT
> Phillip Lord coughed up:
>> Thomas> Allowing of course for this as well:
[quoted text clipped - 9 lines]
> No, because now you're in dynamically typed language territory, and that
> would (without doubt) ignite a flame war :) .  

Not at all.  Check out SML (http://www.smlnj.org), OCaml
(http://caml.inria.fr/ocaml/), Haskell (http://www.haskell.org/), Clean
(http://www.cs.ru.nl/~clean/), or google for "type inferencing".  All of
these languages have stricter static typing than Java IMO yet they all
allow things like the above.  The compilers use type inference to allow
type declarations to be omitted in most cases.  It's still possible in
these languages to explicitly declare the types of variables or
functions to resolve ambiguity in certain cases, or just for
documentation purposes.

For example in OCaml if I write
  let pi = 3.14
The compiler knows that pi is a float.  If I write
  let square x = x * x
The compiler infers that 'square' is a function of type
  int -> int
(In this case it knows because the * operator is only for ints in OCaml.)
Thomas G. Marshall - 06 May 2005 23:51 GMT
Adam P. Jenkins coughed up:

...[rip]...

> [...] or google for "type
> inferencing".  All of these languages have stricter static typing
> than Java IMO yet they all allow things like the above.  The
> compilers use type inference to allow type declarations to be omitted
> in most cases.

Oh I know this, I was being glib really, sorry for the confusion.  I put in
a smiley mostly because things of this form:

   <no type> <variable name> = new <class/type name>

Are enough to smell like DTL and is shaking a bottle of nitro in these
parts.  Again, another smiley: :)

My replies now are a little scattered, but the jist is that what you are
talking about is a short-cut.  And you don't speak to this point, but using
the shortcut means that you are not declaring the variable as a superclass
of the actual instantiating class (for polym).  In that case you would need
to forego the shortcut and specify the typed construct.  Whatever....

...[rip]...

Signature

If I can ever figure out how, I hope that someday I'll
succeed in my lifetime goal of creating a signature
that ends with the word "blarphoogy".

Phillip Lord - 06 May 2005 10:28 GMT
>>>>> "Thomas" == Thomas G Marshall <tgm2tothe10thpower@replacetextwithnumber.hotmail.com> writes:

 Thomas> Right.  Well, except in the case of Perl, where all such
 Thomas> code is uniformly bad.  :)
 >>
 >> I'm a bioinformatician, so I write a lot of perl

 Thomas> (?) Why does one imply the other?

Perl is, still, largely the language of choice in bioinformatics. For
a variety of reasons, we tend to use fairly old fashioned technology,
including many different flat files. So we write lots of parsers and
extracters, at which perl excels. Also a lot of analyses are
experimental and the code base is used once or twice and thrown
away. Again, perl is very good at this. When I come back to Java, I
often forget to compile the code, and then get really annoyed that I
have to. Of course the compilation has advantages.

One day, bioinformaticians will not use perl. But it won't be for a
long time.

 >> I have some distinct sympathy with this position. Although, I
 >> suspect it comes from a position of ignorance.

 Thomas> Which: Is it my position or your sympathy that comes from
 Thomas> ignorance?

 Thomas> I assure you that I've done Quite A Lot (tm) in perl.  But I
 Thomas> have been around the block enough times to know that when a
 Thomas> language lends itself to terseness and obfuscation that
 Thomas> there will be many an engineer that will attempt the most
 Thomas> terse and most obfuscated production code.

 Thomas> Everyone knows that a language is better when it has things
 Thomas> like $| and $< in it with such obvious meanings. :)

My experience has been that many people who knock perl haven't
actually used it that much. The syntax is obtuse, but not so bad once
you are used to it.

I didn't know whether this is true in your case, which is why I said
"suspect". Now I know better.

You are definitely correct

 >>
 >> Or just
 >>
 >>
 >> f = new Frame.

 Thomas> No, because now you're in dynamically typed language
 Thomas> territory

No, this isn't true. What I want is for Java to figure out more. I
still want f to be strongly typed.

 Thomas> , and that would (without doubt) ignite a flame war :) .

Heaven forbid.

 Thomas> What we were discussing were mere shortcuts, or so I
 Thomas> thought.  Unless of course that the f = new Frame is short
 Thomas> cut for Frame f = new Frame, and not something else like
 Thomas> Object f = new Frame.

I wasn't suggesting a syntactic shortcut per se. More the hope that
more can be done with less requirement for the programmer to annotate
the code base with types everywhere. In short, a cleverer type
system. Whether this is possible, I don't know. It's an aspiration.

Cheers

Phil
Andrew McDonagh - 06 May 2005 11:15 GMT
>>>>>>"Thomas" == Thomas G Marshall <tgm2tothe10thpower@replacetextwithnumber.hotmail.com> writes:
>
[quoted text clipped - 70 lines]
>
> Phil

lots of bioinformatics use a variety of languages (Perl, C, C++, Java,
PLSQL, etc), Lion Bio-science have a system that is predominately J2EE
based.
Tim Tyler - 10 May 2005 17:38 GMT
Eric Sosman <eric.sosman@sun.com> wrote or quoted:

>     The value proposition of generics, it seems to me, lies
> purely in the fact that they make some kinds of mistakes
[quoted text clipped - 3 lines]
> by the compiler should cost less than a bug found by testing
> (or *not* found by testing ...).

I don't think those studies were performed by fans of smalltalk -
or other dynamic languages.

Those guys say - in a nutshell - that peppering your code with type
information typically slows down development, makes refactoring
harder, and reduces code reabability - while the benefits of
finding bugs at compile time are much over-rated - since an
intelligent lint prorgam can often infer types anyway - and
the bugs type checking catches are generally trivial bugs
which are easily caught by unit tests anyway.

That's not the whole story, but there's a lot of truth in
what these guys say - especially when engaging in activities
such as RAD, prototyping or debugging - e.g. see:

``Smalltalk v. Java: Which is More Productive?
 A Java Developer Answers the Question''

- http://www.whysmalltalk.com/articles/raab/productivity.htm

As essentially a rather static language, Java needed generics.

However - IMO - as a rather static language, Java places itself
aside from the mainstream of future language development.

My expectation is that future mainstream programming languages
will offer both static and dynamic features - with the latter
being used for prototyping, RAD work and interactive debugging -
with the former will be used for building libraries and basic
interfaces.
Signature

__________
|im |yler  http://timtyler.org/  tim@tt1lock.org  Remove lock to reply.

Thomas G. Marshall - 05 May 2005 02:48 GMT
Eric Sosman coughed up:
>> In Java5, the powers that be added generics.
>>
[quoted text clipped - 21 lines]
> and cause its ultimate demise.  The Java people have been
> suckered into kissing the Bjarne Stone.

I knew it!!!!   The @#$%ers.....

>    Oh, yeah, and one other teeny-tiny thing: If you make
> a mistake, it gets diagnosed at compile time instead of at
> run time.  Which would you rather receive: a compiler error
> that you alone see, or a ClassCastException with all the
> honchos from The Big Customer watching?  If you'd prefer
> the former, learn to like generics.

Signature

"So I just, uh... I just cut them up like regular chickens?"
"Sure, just cut them up like regular chickens."

Chris Uppal - 05 May 2005 09:58 GMT
>     It was the C++ weenies, definitely.  You're entirely
> correct: The C++ saboteurs have contaminated Java with
> generics simply and only to make the language unattractive
> and cause its ultimate demise.  The Java people have been
> suckered into kissing the Bjarne Stone.

Funny thing, I know you intended this as sarcasm, but I agree with it as
written.  Well. not quite literally -- I don't suppose there's any
conspiracy -- but I do think that generics have been introduced out of
ill-considered, or unconsidered, C++-envy.

I don't see anything like enough value in (Java's) generics to justify the new
level of complexity.  John's post captured perfectly the (perfectly real) value
in generics, so much so that I'm going to quote it again here -- John C.
Bollinger wrote:

> I see some value in the additional self documentation provided by
> generic declarations.  I also think there is a certain degree of
> usefulness simply in organizing your thoughts at design and early
> development time well enough to write type constraints.

I (like Chris Smith, it seems) think the above virtues are /way/ more important
than the error trapping of static type checking.  But I question whether
generics actually supply /enough/ of the above good things to make up for their
complexity.  The arcane effects of erasure, the seemingly arbitrary
restrictions (especially on the use of primitive types -- a problem compounded
rather than eased by auto-boxing), the weird upper/lower bounds
notation/concept... All these mean, as far as I can see, that programmers are
being distracted from the real work of producing working programs, and are
instead being forced to waste time thinking about how to keep the compiler
happy.

Added to that, I am getting the impression that generics are also distracting
people from sound OO -- tending to use generics /instead/ of objects with
clearly defined roles.  I'm not really sure that the tendency is widespread,
but if it is, then that's a Bad Thing indeed.

Oh, yes.  I also suspect that the implementation is buggy.  At least, when I
tried some moderately complex generical programming, I was getting some Very
Strange error messages from the compiler.  That suspicion does not in itself
prove that there's anything even slightly wrong with generics -- of course ! --
but what /is/ relevant here is that either the implementation is buggy,
implying that the concepts are over-complicated, or if the implementation is
(mostly) fine, then my understanding must be badly flawed.  If the latter is
true, then there is a further choice: either I that am a lot less competent
than I think, or that the generics concepts are a lot more complicated than
is acceptable. Guess which option I'm currently plumping for ;-)

>     Oh, yeah, and one other teeny-tiny thing: If you make
> a mistake, it gets diagnosed at compile time instead of at
> run time.  Which would you rather receive: a compiler error
> that you alone see, or a ClassCastException with all the
> honchos from The Big Customer watching?  If you'd prefer
> the former, learn to like generics.

This is, of course, contentious.  There are many people who disagree
(violently! ;-).  I happen to be among them.  But my point here is not to ague
the point one way or another, but to correct the impression that you may be
giving to less experienced programmers (more my your tone than by the actual
content) that this is a cut-and-dried issue, that the jury has returned its
verdict, and that the book has been closed.

Early error trapping is obviously a Good Thing -- if it's free.  The problem is
that it is not.  The gains have to be compared with the costs (in brittleness
of design/implementation, in extra complexity, in extra verbosity).  The
question of whether the gain pays for the costs of static type checking is far
from closed; there is simply no consensus on the issue.  In particular we can
look at the /incremental/ gain in early error trapping provided by generics
(over and above what we already got from Java's pre-generics type-system), and
compare that with the incremental costs (in complexity, etc) of the new
generics.  Regardless of whether Java's old type system really earned its keep,
we can consider whether generics are a nett benefit as an add-on.  I do not
believe that they are.

   -- chris
Mike Schilling - 05 May 2005 19:22 GMT
>>     It was the C++ weenies, definitely.  You're entirely
>> correct: The C++ saboteurs have contaminated Java with
[quoted text clipped - 6 lines]
> conspiracy -- but I do think that generics have been introduced out of
> ill-considered, or unconsidered, C++-envy.

Why C++, in particular?  The next version of C# has generics, and the
current one has auto-boxing, variable-length argument lists, for-loops over
collections, etc.  Given that Java competes for mindshare with .NET, I think
competition with C# is a more likely motive for the 1.5 changes.
David Blickstein - 05 May 2005 22:23 GMT
>>     It was the C++ weenies, definitely.You're entirely
>> correct: The C++ saboteurs have contaminated Java with
>> generics simply and only to make the language unattractive
>> and cause its ultimate demise.  The Java people have been
>> suckered into kissing the Bjarne Stone.

> Why C++, in particular?  The next version of C# has generics, and the
> current one has auto-boxing, variable-length argument lists, for-loops over
> collections, etc.  Given that Java competes for mindshare with .NET, I think
> competition with C# is a more likely motive for the 1.5 changes.

Would be the least bit surprised if C++  weenies infected the C# design as
well.

Or it could be that it's not so much as competing for C# mindshare as
competing to get the C++ mindshare.   All those people who bought into C++
because it was hyped as the early 90's "it" language and too late realized
what an amazing piece of  ATROCIOUS language design it is, and how much
money it is costing them.

Y'know... if I may..this all reminds me of what I see here in my home state
of NH.

In the 80s NH had the 2nd lowest per-capita taxes in the nation and modest
services.   In sharp contrast our southern neighbors in Massachussetts had
very nearly the HIGHEST per-capita taxes (source: US Statistical Abstract).

So in the late 80s and 90s, there was a wave of Mass refugees moving to NH
attracted by the lower taxes.  And the first things they started to do was
ask for new government services to be added - the sort of things that caused
their MA tax rates to be so high.

It's like they couldn't make the connection between services and taxes.

I think we might see something similar here with Java.

My understanding is that C++ is dying (I wish *I* could be the one to pull
out the feeding tube).   Everyone is hearing about the advantages of the
modern languages like C# and Java.

So they're all moving to these other languages and trying to drag their
familiar C++ methods with them not recognizing that it's their ABSENCE that
made Java and C# so attractive.
Thomas G. Marshall - 06 May 2005 03:35 GMT
David Blickstein coughed up:
>>>     It was the C++ weenies, definitely.You're entirely
>>> correct: The C++ saboteurs have contaminated Java with
[quoted text clipped - 29 lines]
> started to do was ask for new government services to be added - the
> sort of things that caused their MA tax rates to be so high.

Right about your observation, and right metaphor as well.  I grew up in NH
and later moved to MA.  I know precisely the phenomenon you are talking
about (from observation).  As an aside, the thing that confuses the MA
people as they move to NH is that nearly everything in NH is powered from
the property tax---NH has no income /nor/ sales taxes.  The MA folks freak
out over this often by assuming that this unfairly clobbers land owners.
They forget that even /rent/ is affected by property tax: someone somewhere
owns the property and pays---this payment of tax sooner or later results in
higher rent.  It's all part of the same economic puzzle as in all states.
The only difference is that NH chooses to have only a few targeted avenues
of taxation, whereas MA prefers them to be multiple and varied.

> It's like they couldn't make the connection between services and
> taxes.
[quoted text clipped - 8 lines]
> their familiar C++ methods with them not recognizing that it's their
> ABSENCE that made Java and C# so attractive.

Signature

Forgetthesong,I'dratherhavethefrontallobotomy...

Chris Uppal - 06 May 2005 09:26 GMT
> [me:]
> > Funny thing, I know you intended this as sarcasm, but I agree with it as
[quoted text clipped - 3 lines]
>
> Why C++, in particular?

My reason is simply that people have been discussing adding "templates" to Java
since well before C# was invented (or at least publicly admitted to).  Same
goes for enums.

> The next version of C# has generics, and the
> current one has auto-boxing, variable-length argument lists, for-loops
> over collections, etc.  Given that Java competes for mindshare with .NET,
> I think competition with C# is a more likely motive for the 1.5 changes.

I agree that C# provides competition and a source of ideas (both good and
bad).  I don't doubt for a minute that Java's auto-boxing etc, have been added
more in imitation of C# than convergently with it.

BTW, do you know of a description (readable, rather than a formal spec) of the
semantics/implementation of C#''s generics ?  I gather that it's being done at
the VM level rather than by compiler kludgery.  If so then it may be that C#''s
generics are less problematic than Java's.

   -- chris
Mike Schilling - 06 May 2005 17:40 GMT
> BTW, do you know of a description (readable, rather than a formal spec) of
> the
> semantics/implementation of C#''s generics ?

No, unfortunately.  My biggest complaint about .NET (as opposed to Java) is
the lack of good conceptual documentation.  You can find specs and
step-by-step instructions (e.g. click this button, choose the third tab,
fill in the box, check the third box, and choose "OK") but not much in
between.

> I gather that it's being done at
> the VM level rather than by compiler kludgery.  If so then it may be that
> C#''s
> generics are less problematic than Java's.

That's my understanding too, that generics result in the creation of new
first-class type objects at runtime.
Chris Uppal - 07 May 2005 08:18 GMT
> > I gather that it's being done at
> > the VM level rather than by compiler kludgery.  If so then it may be
[quoted text clipped - 3 lines]
> That's my understanding too, that generics result in the creation of new
> first-class type objects at runtime.

Yummy!

   -- chris
David Blickstein - 06 May 2005 19:33 GMT
> My reason is simply that people have been discussing adding "templates" to Java
> since well before C# was invented (or at least publicly admitted to).  Same
> goes for enums.

Enums were truly needed.  They eliminated a class of (what I consider to be)
type-related errors that in my experience was very common: using the wrong
constant in the wrong context.   Like substituting  LAYOUT.LEFT_JUSTIFIED
for LAYOUT.WEST in a layout manager.

There's a C# feature that I also think is desperately needed in Java.

C# allows you to use the SAME syntax for fields and nyladic (zero arguments)
methods.   This allows you to abstract the implementation of the field so
that fields can be re-implemented as methods without breaking existing code.

This is a very common occurrence.   SOmething starts out with a static value
and ends up being a dynamic value.

I'm getting someone on the Java committee to propose this.
Mike Schilling - 06 May 2005 20:26 GMT
>> My reason is simply that people have been discussing adding "templates"
>> to
[quoted text clipped - 16 lines]
> that fields can be re-implemented as methods without breaking existing
> code.

A syntax change doesn't help much here.  Unless the bytecode is also changed
to make field references and zero-argument method calls identical, a change
will cause incompatibility with existing binaries.
Thomas G. Marshall - 07 May 2005 03:31 GMT
David Blickstein coughed up:
>> My reason is simply that people have been discussing adding
>> "templates" to Java since well before C# was invented (or at least
[quoted text clipped - 6 lines]
> using the wrong constant in the wrong context.   Like substituting
> LAYOUT.LEFT_JUSTIFIED for LAYOUT.WEST in a layout manager.

If that's what you were worried about then enums were not "truly needed" at
all.  The examples you gave are examples of poorly designed type-UN-safe
enums.

Consider this type-SAFE pseudo-enum instead:

       public class TrafficColorEnum
       {
           public static final RED = new TrafficColorEnum();
           public static final GREEN = new TrafficColorEnum();
           public static final YELLOW = new TrafficColorEnum();
       }

       public void setColor(TrafficColorEnum color)
       {
           if (color == TrafficColorEnum.RED)
               // do something red specific...
       }

There are (of course) much more complicated versions of this, including very
detailed AbstractEnum superclasses that allow values to be tagged to the
enums, but you get the idea.  Each constant is an enum element, each of type
TrafficColorEnum.

> There's a C# feature that I also think is desperately needed in Java.
>
[quoted text clipped - 7 lines]
>
> I'm getting someone on the Java committee to propose this.

Signature

"It's easier to be terrified by an enemy you admire."
-Thufir Hawat, Mentat and Master of Assassins to House Atreides

Lasse Reichstein Nielsen - 07 May 2005 12:19 GMT
> If that's what you were worried about then enums were not "truly needed" at
> all.  The examples you gave are examples of poorly designed type-UN-safe
> enums.
>
> Consider this type-SAFE pseudo-enum instead:

Indeed. The Java Tiger Enums are merely syntactic sugar for creating
such type-safe enums. One reason for having enums in the language is
to make it easier to make good enums. I don't think it's the most
important reason.

We already made type-safe enums in our code. The syntactic sugar makes
it explicit what the conde means. It makes it more readable, as well as
writable.

I consider it a "Good Thing" to make common idioms explict, instead of
merely relying on naming conventions. I like the concept of C#'s
properties for the same reasons - they make it explicit what is a getter
and a setter instead of encoding it in the method names. (I don't know
whether the implementation is as good as the idea, haven't tried it in
practice :).

It's also a reason for annotations. Not all methods are alike. Some of
them might have something in common, and an annotation can make that
explicit, no matter what name the methods might have.

Hmm, maybe we should have the annotations @Setter("propname") and
@Getter("propname") instead of using name-prefixing. :)

/L
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'

David Blickstein - 09 May 2005 16:07 GMT
> If that's what you were worried about then enums were not "truly needed" at
> all.

I agree with you, but only in the "possible" sense of "needed", not in the
"desirable" sense.  In that sense of the word, your claim is already proven
by the fact that the new enumerations are (in my understanding) just a
little syntactic sugar provided by the javac compiler.   So clearly type
safe enums were always possible.

However, you could say the same thing about the new enhanced "for"
statement.   Yes, it's possible for me to to write a loop that is
effectively coding "for each element of this list", but (IMO) it is
substantially better to be able to CODE it as "for each element" rather than
"something that translates to for each element".

For example... which is more readable:

            int sum = 0;
           for (int i=0, i<a.length() ; i++) {sum += a[i]} ;
           print(sum/a.length());

or:
           print(average(a));

The problem with the example you gave (IMHO) is in what I call the
"exposition".  The advantage of enumerations (and for each and a bunch of
the othernew features) is that they provide a syntax to DIRECTLY express a
basic operation, and thus expose the operation more directly.
Thomas G. Marshall - 09 May 2005 23:44 GMT
David Blickstein coughed up:

>> If that's what you were worried about then enums were not "truly
>> needed" at all.
[quoted text clipped - 4 lines]
> understanding) just a little syntactic sugar provided by the javac
> compiler.

Actually, it's proven just by understanding what a class is.  But sure.
We're done with this part of the discussion.  It was hard to tell your level
of understanding simply by your statements.

> The problem with the example you gave (IMHO) is in what I call the
> "exposition".  The advantage of enumerations (and for each and a
> bunch of the othernew features) is that they provide a syntax to
> DIRECTLY express a basic operation, and thus expose the operation
> more directly.

You'll need to explain this part a little better.  I'm not sure: you started
with the problem with my enum example, and then followed with the advantage
of enumerations.

Signature

Everythinginlifeisrealative.Apingpongballseemssmalluntilsomeoneramsitupyournose.

David Blickstein - 10 May 2005 20:05 GMT
> You'll need to explain this part a little better.  I'm not sure: you started
> with the problem with my enum example, and then followed with the advantage
> of enumerations.

The simplest explanation is in your example, it wasn't easy to derive that
what was being done was an enumeration.

As someone else mentioned, simple common programming concepts deserve direct
support from the language even if all it provides is a little syntactic
sugar.  The justification being is that the syntax makes it clear that an
enumeration is being used.

If you think about it, take any two languages that provide a Turing machine.
You "can" implement the same program in either of them.  What mostly makes
them different is how efficiently the algorithm is expressed/exposed via the
language syntax.
Thomas G. Marshall - 10 May 2005 23:32 GMT
David Blickstein coughed up:

>> You'll need to explain this part a little better.  I'm not sure: you
>> started with the problem with my enum example, and then followed
[quoted text clipped - 12 lines]
> What mostly makes them different is how efficiently the algorithm is
> expressed/exposed via the language syntax.

I see it as /very/ clear what it is.  Besides, my example would be probably
be this:

       public class TrafficLiteColor extends AbstractEnum
       {
               // etc.
       }

Which is even more clear.  Besides, knowing that an enum is an enum is not
the bottom line.  Seeing how it is /used/ is, and that would be, of course,
evident from the code.  It does you no good to know that something is an
enum if you don't know how or where it is used.

Signature

Whyowhydidn'tsunmakejavarequireanuppercaselettertostartclassnames....

David Blickstein - 11 May 2005 15:38 GMT
> I see it as /very/ clear what it is.  Besides, my example would be probably
> be this:
[quoted text clipped - 7 lines]
> the bottom line.  Seeing how it is /used/ is, and that would be, of course,
> evident from the code.

We just disagree, and some of it is a "where you draw the line on a sliding
scale" difference.

Providing language syntax for enums just makes the declaration more terse.
From where i sit, your example just has a bit of excess and nominally
irrelevant verbage needed for Java to setup the underlying class mechanisms.

> It does you no good to know that something is an  enum if you don't know
how or where it is used.

My opinion is that knowing it is an enum is the largest part of finding out
"how" it is used.

It tells me that the abstract usage (this is one selection where limited
number of selections are allowed).    Not knowing it is an enum, a usage
might appear to be an assignment of a constant value (enumeration values are
NOT constants - they are just typically implemented that way), or a
selection of a particular class object.

I think the only thing that really tells me otherwise in your example is the
naming convention.

Again, just differences of reasonable opinion here.
Chris Uppal - 11 May 2005 08:34 GMT
> If you think about it, take any two languages that provide a Turing
> machine. You "can" implement the same program in either of them.  What
> mostly makes them different is how efficiently the algorithm is
> expressed/exposed via the language syntax.

Or how effective the language's syntax is in allowing you to express concepts
and structures transparently /without/ adding special syntax.

Of the front-line programming languages, Java is probably the least supportive
in this respect (Fortran and Cobol may be worse -- I don't know either well
enough to have an opinion -- but they surely can't be /that/ much worse).
Incidentally, this is -- just for once ;-) -- not intended as criticism of
Java, merely an observation about the position that it occupies in the language
design space.

   -- chris
Mike Schilling - 11 May 2005 15:47 GMT
>> If you think about it, take any two languages that provide a Turing
>> machine. You "can" implement the same program in either of them.  What
[quoted text clipped - 10 lines]
> well
> enough to have an opinion -- but they surely can't be /that/ much worse).

FORTRAN-77 is far worse.  I don't know the newer languages called FORTRAN.
But C and C++ are also worse, and C# almost identical, so I don't know which
languages you consider "front-line".
Chris Uppal - 11 May 2005 16:39 GMT
> FORTRAN-77 is far worse.  I don't know the newer languages called FORTRAN.
> But C and C++ are also worse, and C# almost identical, so I don't know
> which languages you consider "front-line".

C and C++ both have macros (albeit kinda stunted).  C++ has operator
overloading.  Both provide means by which programmers can express the meaning
of the code more directly/transparently than would be possible in the "base"
language.  I.e. a way of stating directly what concept is involved rather than
relying of the reader recognising an idiom.

My understanding of David's position is that when an idiom can be converted
into syntax, there's a gain in transparency in the language.  It's a POV that I
would agree with, except that adding new syntax for each idiom add complexity
too, and I don't like that.  So I wanted to emphasise that there was an
alternative -- to the extent that the language design allows it, it may be
possible to express concepts directly without relying on the reader to
recognise idioms but without requiring a syntax extension.

Java -- as I said -- has basically no abilities in that direction[*].  C and
C++ have /some/ abilities (easily abused, I agree) in that direction.
LISP/Scheme is /packed/ with that kind of ability, and so in a very different
way is Smalltalk (and yes, I do consider both of those to be "front-line" -- I
understand that you may not agree).

([*] except insofar as OO itself can be thought of as a kind of language
extension mechanism -- viewing each class library as a small "language" for the
corresponding domain.)

   -- chris
David Blickstein - 11 May 2005 18:12 GMT
> My understanding of David's position is that when an idiom can be converted
> into syntax, there's a gain in transparency in the language.  It's a POV that I
> would agree with, except that adding new syntax for each idiom add complexity
> too, and I don't like that.

>So I wanted to emphasise that there was an alternative...

Do you like the "for" statement?  Because for the most part, it is
unnecessary once you have a "while" statement.

I'm presuming that your position isn't that a feature shouldn't be added if
it's already possible to code something equivalent - an "alternative".    If
that was the case, once you have a complete Turning machine, all subsequent
language additions are bad.

So what I don't understand is what Uppal language inclusion test does
"enums" fail but "for" pass?

> Java -- as I said -- has basically no abilities in that direction[*].

I think the "for" statement is a counter-example.
Thomas G. Marshall - 11 May 2005 19:04 GMT
David Blickstein coughed up:

>> My understanding of David's position is that when an idiom can be
>> converted into syntax, there's a gain in transparency in the
[quoted text clipped - 17 lines]
>
> I think the "for" statement is a counter-example.

Hmmmm....

I think that this is impossible to judge using the single adjective of
"alternative".  This is missing the metric of "complexity".

To that limited extent, I am glad that there are enums, but *only* because
so many folk just never even /thought/ through how to make them easily
type-safe, which I find so *utterly* irritating.  I actually worked with a
couple of guys that built their own enum class in such a way that the enums
were always of the type Enum.  Jesus.  I consider my example to be easy.
And sun was a huge abuser of unsafe "enums".

I was reacting mostly because you stated that type safe enums were not
possible, which you clarified to mean "not easily possible".  The
disagreement now is (as you know) what is easy, and what is obvious by
syntax alone.

I would argue, that my example is both easy, and as obvious as nearly any
other class.  Remember, that the class

       ArrayList

only makes immediate sense because of its name.  The example I gave:

       public class TrafficColorEnum
       {
           public static final RED = new TrafficColorEnum();
           public static final GREEN = new TrafficColorEnum();
           public static final YELLOW = new TrafficColorEnum();
       }

is no different IMO.  {shrug}

Signature

"Well, ain't this place a geographical oddity!
Two weeks from everywhere!"

beliavsky@aol.com - 12 May 2005 14:11 GMT
<snip>

> > Or how effective the language's syntax is in allowing you to express
> > concepts
> > and structures transparently /without/ adding special syntax.
> >
> > Of the front-line programming languages, Java is probably the least

> > supportive
> > in this respect (Fortran and Cobol may be worse -- I don't know either
[quoted text clipped - 4 lines]
> But C and C++ are also worse, and C# almost identical, so I don't know which
> languages you consider "front-line".

Fortran 90 has user-defined types with operator overloading, and
Fortran 95 added elemental functions, which can take scalars or
multidimensional arrays as arguments. Fortran 2003 adds classes with
inheritance, but it does not have the support for generic programming
(templates and the Standard Library) of C++, although it has better
built-in array handling.
Thomas G. Marshall - 12 May 2005 18:09 GMT
beliavsky@aol.com coughed up:

> <snip>
>
[quoted text clipped - 20 lines]
> (templates and the Standard Library) of C++, although it has better
> built-in array handling.

Interesting.

I'm beginning to wonder if the biggest thing that fortran has going against
itself is its name....

Signature

"I don't want FOP, God dammit!  I'm a DAPPER DAN MAN!"

Dale King - 25 May 2005 05:51 GMT
> I agree with you, but only in the "possible" sense of "needed", not in the
> "desirable" sense.  In that sense of the word, your claim is already proven
> by the fact that the new enumerations are (in my understanding) just a
> little syntactic sugar provided by the javac compiler.   So clearly type
> safe enums were always possible.

There is actually one part of enums that was not possible before and
that was the ability to use them as cases in a switch statement.
Signature

 Dale King

Chris Uppal - 25 May 2005 09:49 GMT
> [../] the new enumerations are (in my
> > understanding) just a little syntactic sugar provided by the javac
> > compiler.   So clearly type safe enums were always possible.
>
> There is actually one part of enums that was not possible before and
> that was the ability to use them as cases in a switch statement.

It was always possible, the new enums don't generate code that couldn't be
expressed in "normal" Java.  Supporting switch would require a fairly
unpleasant amount of wordy duplication, though.  You'd have to have a public
static final int field corresponding the the 'ordinal' of each enum object,
which is obviously error prone unless the compiler does it for you.

OTOH, if you use your own implementation of the type-safe enum pattern, then
their object-nature is not hidden by the compiler and so you can use
polymorphism to avoid having to use switch statements in the first place.

   -- chris
Thomas G. Marshall - 25 May 2005 14:40 GMT
Chris Uppal coughed up:

>> [../] the new enumerations are (in my
>>> understanding) just a little syntactic sugar provided by the javac
[quoted text clipped - 14 lines]
> so you can use polymorphism to avoid having to use switch statements
> in the first place.

Correct.  As a result there are numerous versions of AbstractEnum classes
and the like that I've both written and seen float about that accomplish
ordinality, etc., fairly easily and seamlessly.

But again, while it wasn't strictly needed, the enums have the advantage
that it makes the less senior engineers, who don't know better, less likely
to try to use integer replacements for the enums themselves.  Like sun's
code mostly has, which [very] unfortunately has become a roll model of
sorts.

Again, for those who don't know better.

Signature

Unix users who vehemently argue that the "ln" command has its arguments
reversed do not understand much about the design of the utilities.  "ln
arg1 arg2" sets the arguments in the same order as "mv arg1 arg2".
Existing file argument to non-existing argument.  And in fact, mv
itself is implemented as a link followed by an unlink.

Phillip Lord - 25 May 2005 15:20 GMT
 Chris> Dale King wrote:

 >> [../] the new enumerations are (in my
 >> > understanding) just a little syntactic sugar provided by the
 >> > javac compiler.  So clearly type safe enums were always
 >> > possible.
 >>
 >> There is actually one part of enums that was not possible before
 >> and that was the ability to use them as cases in a switch
 >> statement.

 Chris> It was always possible, the new enums don't generate code
 Chris> that couldn't be expressed in "normal" Java.  Supporting
 Chris> switch would require a fairly unpleasant amount of wordy
 Chris> duplication, though.  You'd have to have a public static
 Chris> final int field corresponding the the 'ordinal' of each enum
 Chris> object, which is obviously error prone unless the compiler
 Chris> does it for you.

I think, actually, you are wrong and it doesn't work. The problem is
that with switch case, the value of the cases must be a int or char
definable at compile time.

If you do

class Enum{
public static final int ord;
private static int number;
Enum()
{
  ord = number++;
}

Enum a = new Enum();
Enum b = new Enum();

}

case  a.ord

won't work, because we don't know the value of a.ord. Actually, we can
work this out but the compile wasn't clever enough.

Now under the hood, switch case is implemented as a hash (so it's
constant time to any case idependent of the number of cases). It uses
the knowledge of the case values to determine who this look up happens
(sparse or otherwise).

The syntactic sugar that switch/case is translated into cascading
if/then/else statements.

So the OP was correct. You couldn't use switch/case. In a sense, you
still can't, as you do not get the constant time access when
switch/case is used with a enum, that you do otherwise.

     
 Chris> OTOH, if you use your own implementation of the type-safe
 Chris> enum pattern, then their object-nature is not hidden by the
 Chris> compiler and so you can use polymorphism to avoid having to
 Chris> use switch statements in the first place.

Which is how I generally did it, although you are moving from a Enum
pattern toward a Command pattern I think.

Phil
Chris Uppal - 25 May 2005 18:21 GMT
>   Chris> It was always possible, the new enums don't generate code
>   Chris> that couldn't be expressed in "normal" Java.  Supporting
[quoted text clipped - 7 lines]
> that with switch case, the value of the cases must be a int or char
> definable at compile time.

No, there's no problem except wordy, error-prone, repetition.

Suppose that we want an enumeration of the three primary colours (this probably
wouldn't compile but you'll be able to see what I mean, I hope):

   public final class Colour
   {
       public static final int
           __RED_ORDINAL = 0,
           __GREEN_ORDINAL = 1,
           __BLUE_ORDINAL = 2;

       public static final Colour
           RED = new Colour("RED", __RED_ORDINAL),
           GREEN = new Colour("RED", __GREEN_ORDINAL),
           BLUE = new Colour("BLUE", __BLUE_ORDINAL);

       private final static Colour s_values[] =
               { RED, BLUE, GREEN };

       private final int m_ordinal;
       private final String m_name;

       private Colour(String name, int ordinal)
       {
           m_name = name;
           m_ordinal = ordinal;
       }

       public int oridinal() { return m_ordinal; }
       public String toString() { return m_name; }

       public static Colour[]
       values()
       {
           return (Colour[])(s_values.clone());
       }
   }

and then a case statement can be written like:

   public boolean
   isPutrid(Colour colour)
   {
       switch (colour.ordinal())
       {
       case Colour.__RED_ORDINAL:
       case Colour.__BLUE_ORDINAL:
           return false;
       case Colour.__GREEN_ORDINAL:
           return true;
       default: // WTF ??
           return false;
       }
   }

Which is almost exactly what the Java compiler does at the bytecode level.  Of
course it would be a pain to maintain and use (and not allow people to /ab/use)
the __XXX_ORDINAL numbers in parallel to the "real" enumeration objects --
that's what I meant when I called it wordy and error-prone, but it isn't at all
impossible.

Note that the implementation of switch is a /real/ switch (a tableswitch
bytecode instruction) which can be implemented as a pure jump table.  There is
no cascade of if-thens, nor is there any hashing going on.

Actually, the bytecode generated by javac uses one more level of indirection.
The ordinal number is used to lookup an integer value in a synthetic int[]
array, and then the value from the array is used in the generated switch
statement. I'm not sure why it does that.  Possibly it's to allow switch
statements to continue to work if the enum definition is changed after it has
been compiled, though I don't really see how that would work..

   -- chris
Phillip Lord - 25 May 2005 18:54 GMT
>>>>> "Chris" == Chris Uppal <chris.uppal@metagnostic.REMOVE-THIS.org> writes:

 Chris> Phillip Lord wrote:

 Chris> It was always possible, the new enums don't generate code
 Chris> that couldn't be expressed in "normal" Java.  Supporting
 Chris> switch would require a fairly unpleasant amount of wordy
 Chris> duplication, though.  You'd have to have a public static
 Chris> final int field corresponding the the 'ordinal' of each enum
 Chris> object, which is obviously error prone unless the compiler
 Chris> does it for you.
 >>
 >> I think, actually, you are wrong and it doesn't work. The problem
 >> is that with switch case, the value of the cases must be a int or
 >> char definable at compile time.

 Chris> No, there's no problem except wordy, error-prone, repetition.

 Chris> Suppose that we want an enumeration of the three primary
 Chris> colours (this probably wouldn't compile but you'll be able to
 Chris> see what I mean, I hope):

 Chris>     public final class Colour {
 Chris>         public static final int
 Chris>             __RED_ORDINAL = 0, __GREEN_ORDINAL = 1,
 Chris>             __BLUE_ORDINAL = 2;

 Chris> and then a case statement can be written like:

 Chris>     public boolean isPutrid(Colour colour) {
 Chris>         switch (colour.ordinal()) { case
 Chris>         Colour.__RED_ORDINAL: case Colour.__BLUE_ORDINAL:
 Chris>             return false;
 Chris>         case Colour.__GREEN_ORDINAL:
 Chris>             return true;
 Chris>         default: // WTF ??
 Chris>             return false;
 Chris>         }
 Chris>     }

 Chris> Which is almost exactly what the Java compiler does at the
 Chris> bytecode level.  Of course it would be a pain to maintain and
 Chris> use (and not allow people to /ab/use) the __XXX_ORDINAL
 Chris> numbers in parallel to the "real" enumeration objects --
 Chris> that's what I meant when I called it wordy and error-prone,
 Chris> but it isn't at all impossible.

Ah, okay, that would work.

The error prone bit is a serious problem.

 Chris> Note that the implementation of switch is a /real/ switch (a
 Chris> tableswitch bytecode instruction) which can be implemented as
 Chris> a pure jump table.  There is no cascade of if-thens, nor is
 Chris> there any hashing going on.

Perhaps I have made a poor use of the word "hash".

I was sure that they implemented things with if-thens. Perhaps this is
what happened in an early version of the spec when I read it.

 Chris> Actually, the bytecode generated by javac uses one more level
 Chris> of indirection.  The ordinal number is used to lookup an
 Chris> integer value in a synthetic int[] array, and then the value
 Chris> from the array is used in the generated switch statement. I'm
 Chris> not sure why it does that.  Possibly it's to allow switch
 Chris> statements to continue to work if the enum definition is
 Chris> changed after it has been compiled, though I don't really see
 Chris> how that would work..

Hmm. That is strange.

Thanks for the information. Always good to learn more!

Phil
Chris Uppal - 25 May 2005 18:14 GMT
I wrote:

> OTOH, if you use your own implementation of the type-safe enum pattern,
> then their object-nature is not hidden by the compiler and so you can use
> polymorphism to avoid having to use switch statements in the first place.

I must correct myself.  It /is/ possible to define methods against enums
(considered as a special kind of class).  I'm not sure how I missed it, but
miss it I did.

The documentation that ships with JDK1.5.0 has a few examples, one shows that
enums can have their own methods (and data too though that's not shown here):

==============
public enum Operation {
   PLUS, MINUS, TIMES, DIVIDE;

   // Do arithmetic op represented by this constant
   double eval(double x, double y){
       switch(this) {
           case PLUS:   return x + y;
           case MINUS:  return x - y;
           case TIMES:  return x * y;
           case DIVIDE: return x / y;
       }
       throw new AssertionError("Unknown op: " + this);
   }
}
==============

Another demonstrates so-called 'constant specific methods':

==============
public enum Operation {
 PLUS   { double eval(double x, double y) { return x + y; } },
 MINUS  { double eval(double x, double y) { return x - y; } },
 TIMES  { double eval(double x, double y) { return x * y; } },
 DIVIDE { double eval(double x, double y) { return x / y; } };

&