Skip to main content

Makes switch() and case: work with any object or primitive

118 replies [Last post]
patrikbeno
Offline
Joined: 2004-10-11
Points: 0

switch { case: ... default: ... }
should be just a syntactic sugar for
if (...) else if (...) else {}

1) in switch(whatever()), expression is evaluated
2) in case: value, result of the evaluated expression is compared to 'value' in case statement using Object.equals().

This makes switch(){} statement more flexible, it is backward compatible and makes Java more object oriented.

This is really low priority request, of course

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tackline
Offline
Joined: 2003-06-19
Points: 0

OO friendly solutions:

o Add method to MyShape.
o Use GoF visitor pattern.
o When you still have the shape referred to by the more specific type (e.g. just after you have created it), create an associated object with shape specific code. Details will depend upon the situation.

hlovatt
Offline
Joined: 2003-11-18
Points: 0

You can use multiple dispatch to achieve what you want and more and it is safe from problems associated with switch statements, sets of instanceof tests, etc. See:

https://pec.dev.java.net/nonav/compile/index.html

Particularly:

https://pec.dev.java.net/nonav/compile/javadoc/pec/compile/multipledispa...

and

https://pec.dev.java.net/nonav/compile/javadoc/pec/compile/multipledispa...

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

Now this is the right example of how object-enabled switch/case might get too complex. Also, this would dramatically change switch/case semantics (hope it's obvious).

I would understand all objections if I would have proposed this. But compared to this, my proposal is a simple ==/equals with no change to the core.

While I cannot say I dislike this one, I think that this just too much and it is not wise to lead it this way.

So, -1, I never meant it like this.

monika_krug
Offline
Joined: 2004-10-14
Points: 0

Nevertheless I think switching on the object type is a good thing.

Monika.

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> > I think the jury is still out on this point.
>
> You are the only person I know that is against
> generics ;-) .

Yes but even with-in this discussion topic (Mustang), there have been others who have spoken out against the over complication of the languge. I also no many others that are also not for the the feature but you won't most likely hear from them in this forum which is unfortunate.
>

>
> I still don't get it. Why does inheritance with
> interfaces make everything look the same?

Strict type'ing works by saying.. you are this, only this. and you can't be anything else. Interitance/interfaces say, well, ignore what he's saying..... you can be this or some other thing is you like. It's sort of like trying to poke an amoeba :)

>
> Only with reflection, arent't they?

You can run into situations where classloaders, configuration issues and versioning can leave you open to class cast exceptions is another example. Bype code engineering opens you up as another....

> > you don't need to fetch it out of the heap.. but
> this
> > is an detail of the implementation ;)
>
> It's not (only) because of speed primitives should be
> primitives. People think of numbers as numbers, not
> as objects. 5 + 3 makes them think 5 plus 3, not send
> the plus message to the 5 object with the 3
> parameter.

How ever you say it, the result is the same. In this world, + is not an operator (though it maybe implemented as such), it's a symbol like any other which means you can use it (a.k.a. operator overloading but since you don't have operators... you have nothing to overload).

>
> People do not think of if constructs or loops as
> objects, either.

But this ties into closures that everyone is asking for. And what is the problem with

aBoolean ifTrue: aClosure ifFalse: anotherClosure.

or if you like

aBoolean.ifThenElse( trueClosure, falseClosure);

true implements ifThenElse like this

trueClosure.execute();

false....

falseClosure.execute();

nice isn't is.. no need to rebuild context to know what to do.. the context is in the containing object. I know what to do because of where I am.

Unfortunately, to put this (or a better version of it) into Java would so radically change the langauge that I'd never purpose it.

> > this and can seperate the two. Disasterous if one
> > cannot.
>
> Well, who can't?

As I said, I run into metric measurements all the time that suggest many developers don't really get it. In the last month, I've been working in C++ and I've been looking at different pieces of code. I would say that most of the developers are writting very procedurally. I don't see wh they would change if they moved to Java and I do see why they'd miss C++ features.

>
> > I do a lot of work with OO metrics. The two
> > sets of metrics that are of interest to this
> > conversation are those that measure relationships
> and
> > those that measures bulk. In general what I've
> found
> > is that code that seperates the use of primitives
> > from objects tend to produce less bulk and create
> > simpler relationships. Halstead (vocabulary,
> volume)
> > metrics are good for measuring bulk, Parameter
> > counts, Demeter, fan out and depth of inheritance
> are
> > but a few interesting relationship metrics.
>
> This sounds as being in favor of leaving primitives
> as primitives to me.

Actually, what it is saying is that if you don't confuse people with syntax, they generally do a better job. People are doing much more in Java than they did in C++. They didn't quite accept Smalltalk because it is very different from what they are expecting to see.

> Syntax maybe not, but I find thinking in Smalltalk a
> lot more cumbersome than thinking in Java.

Is this a function of the amount of time you spend in quasi OO languages as appose to an implementation such as Smalltalk (or Ruby)? I have to say that then I spend equal amounts of time in Smalltalk and C++, C++ feels way more cumbersome. To each their own ;)

rickcarson
Offline
Joined: 2004-03-04
Points: 0

Let me put my hand up to say that I *loathe and despise* generics with a passion.

I *also* don't like any of the other 'features' which mean that my 8+ yrs of highly tuned mental parsing of other peoples crap Java code just got made obsolete... (especially the syntactic sugar ones).

Oh, the people who love generics go: 'oh but they're so easy' and then they give a trivial example (where it was barely (read as: not really) worth the effort)...

And then you go poking around the java.sun.com forums, and it was obvious that for anything except absolutely trivial applications generics go 'off the deep end' in complexity very very quickly (read as: immediately).

They are distinctly unintuitive, they don't play well with others (read as: don't work well with subtypes and interfaces), and they break reflection (used to be one of the best things about Java) in new and disturbing ways.

Every time I try to steel myself to try to look at them without barfing, I run into something like the definition for an enum:

Class Enum>

So what I don't get is whether that is a recursive generic, or whether there is a 'hidden' Enum declaration somewhere...

Is this really a class which extends itself? (The mind boggles at what bad/inexperienced programmers will get up to with this sort of thing)

Ah well, the changes to the language are nothing if not consistent. (Regex in 1.4, Templates in 1.5) Cunning plan -> add all the horrible features from other languages to make Java unreadable... until Perl 10 = Java 10.

monika_krug
Offline
Joined: 2004-10-14
Points: 0

> Class Enum>
>
> So what I don't get is whether that is a recursive
> generic, or whether there is a 'hidden' Enum
> declaration somewhere...
>
> Is this really a class which extends itself?

Of course this class does not extend itself. It does not say class Enum extends Enum, does it? It just says that the type parameter is an Enum (that is Enum or a subclass of Enum), too.

It is used for e.g. int compareTo(E o). This results in Enum objects only being compared to objects of the same Enum type.

Monika.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

Sure but he tries to say that it is ugly and unreadable. And he's right.

Anyway, the best way to figure out what it means is to look at the API where such type parameter is used (your compareTo() is a good example).

But honestly, does anyone have a better idea how to declare this kind of constraint in Java (or whatever other language)?

rickcarson
Offline
Joined: 2004-03-04
Points: 0

> Sure but he tries to say that it is ugly and
> unreadable. And he's right.

Of course, that is 'right' as in right for me (and other members of the loyal opposition), not 'right' as in some kind of 'univeral truth'.

Python (and Ruby) are good examples of this. Some people love the whitespace thing, some people hate it. The thing I don't like about Python is the underscores (due to a bad experience as a young programmer with underscores). Ruby even more so, in that you have special characters at the front of the variable name (like Hungarian notation*) which indicate the scope of the variable. To me they look horrible. I would much rather spell the variables purpose out in English (even if it means a couple of extra keystrokes).

... But ... what I have to ask myself is how would I feel about Ruby if English wasn't my first language? And what if Ascii wasn't my 'native' character set?

* I know one of the problems with Hungarian notation was that due to the 'magic of casting' you could have a variable which started out life as one thing and then turned into something quite different, so 'lpszFoo' might not be a long pointer to a zero terminated string anymore... I'm not sure whether that applies to Ruby, from my cursory glance their prefixes deal with scope, rather than type, and so shouldn't have that problem? (Wonders about closures breaking scoping rules...?)

As for generics and Enums, even after reading the explanation, I still have too much 'pre 1.5 inertia' for it to make any sense.

What is the reaction from people using 1.5 out in the wild? Are we mostly just using the new Collections and Enums, or are people out there trying to use their own 'home brewed' generics liberally throughout their 'userland' code?

monika_krug
Offline
Joined: 2004-10-14
Points: 0

> ... But ... what I have to ask myself is how would I
> feel about Ruby if English wasn't my first language?
> And what if Ascii wasn't my 'native' character set?

But almost all programming languages are "English", not only Ruby, Java is too.

In Java one can at least use umlauts etc. in identifiers, but it's not recommended when exchanging files with people who use different platforms. (We had nasty problems with umlauts when a Mac programmer in our group uploaded his files to CVS.)

Monika.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

> It is the strongly type'ing
> requirement that is forcing class cast exceptions. In
> an untyped system, you get method not found
> exceptions (which are still possible in Java btw).

So what's the difference? Code does not work either. However, in Java you know what went wrong and why because of strong typing, in an untyped system you just don't have a clue. Or at least your chances are much better with strongly typed system.

In an "untyped" system you may call method that has the name you expect, it has the arguments you expect but does not do what you expect because MyClass.doSomething() is supposed to do something else that AnotherUnrelatedClass.doSomething() (and you called doSomething() on wrong instance).

Java type system just extends naming system. You don't work with plain methods, you work with fully qualified methods.

Untyped system allows you to call method doSomething() on whatever, if such method exists. Untyped system does not allow you to verify that you call proper method. To make it worse, you won't find out that method does not exist unless you attempt to call it (static vs. runtime checking).

Java protects you from such errors. You cannot call method doSomething() even if the object does have one because there is no such thing as plain old single method. You always call MyInterface.doSomething() or MyClass.doSomething().

I think that's much better for big projects.
Loose or lazy typing is suitable for small applications, I dare to say - scripts only.

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> > It is the strongly type'ing
> > requirement that is forcing class cast exceptions.
> In
> > an untyped system, you get method not found
> > exceptions (which are still possible in Java btw).
>
> So what's the difference? Code does not work either.
> However, in Java you know what went wrong and why
> because of strong typing, in an untyped system you
> just don't have a clue.

I think that if you'd actually had used a langauge like that.. you'd quickly figure out that you do have a clue and in Smalltalk.. you have much better debugging facilities then those that exist in Java so it's actually much easier to fix.

> In an "untyped" system you may call method that has
> the name you expect, it has the arguments you expect
> but does not do what you expect because
> MyClass.doSomething() is supposed to do something
> else that AnotherUnrelatedClass.doSomething() (and
> you called doSomething() on wrong instance).

Yeah, and what prevents this in any langugage, type'ing.. I think not. You can abuse any language if you don't use your brain ;)

> Untyped system does not allow you to verify that you
> call proper method.
wrong.. if the method doesn't exist.... the Smalltalk compiler WILL complain.

> I think that's much better for big projects.
> Loose or lazy typing is suitable for small
> applications, I dare to say - scripts only.

Humm that would mean that the Texas Instruments, IBM, some very large shipping companies, a few educational institutions, a fair number of major banks and investment firms, an online commodities trader, power utilities, and a fairly large number of other large scale users of Smalltalk just got it wrong then ;)

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

> > MyClass.doSomething() is supposed to do something
> > else that AnotherUnrelatedClass.doSomething() (and
> > you called doSomething() on wrong instance).
>
> Yeah, and what prevents this in any langugage,
> type'ing.. I think not. You can abuse any language if
> you don't use your brain ;)

What I wanted to point out is the fact that in Java you cannot call MyClass.doSomething() on AnotherUnrelatedClass instance, even though it has doSomething() method, too.
In Smalltalk, AFAIK, you can do this, and that's bad.

> wrong.. if the method doesn't exist.... the Smalltalk
> compiler WILL complain.

Smalltalk:
So you need to cast Object to specific type before you call its method?
Is there runtime checking if the object is of expected type?

> Humm that would mean that the Texas Instruments, IBM,
> some very large shipping companies, ... Smalltalk just
> got it wrong then ;)

No that means that we have something better now. Big projects were written in assembler, also, but nobody would use it again now that one has a choice.

Smalltalk was a good choice once, I don't doubt this.
Now you have a better ones, IMHO :-)

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

>
> What I wanted to point out is the fact that in Java
> you cannot call MyClass.doSomething() on
> AnotherUnrelatedClass instance, even though it has
> doSomething() method, too.
> In Smalltalk, AFAIK, you can do this, and that's
> bad.

I would too and as such.. would never do it even if the compiler did allow it. Now, the question is, is it bad that the compiler will allow it? I guess it all depends on the cost of disallowing it.

>
> > wrong.. if the method doesn't exist.... the
> Smalltalk
> > compiler WILL complain.
>
> Smalltalk:
> So you need to cast Object to specific type before
> you call its method?
> Is there runtime checking if the object is of
> expected type?

If the compiler cannot resolve the symbol.. it will complain... it's smarter than you thought isn't it ;)

>
>
> > Humm that would mean that the Texas Instruments,
> IBM,
> > some very large shipping companies, ... Smalltalk
> just
> > got it wrong then ;)
>
> No that means that we have something better now. Big
> projects were written in assembler, also, but nobody
> would use it again now that one has a choice.

I beg to differ, I got an email from a recruiter about three weeks ago about a new project in London requiring GemStone/S skills in London.. interested?

All of the other projects are on going.

>
> Smalltalk
is
> was a good choice

for certian problem domains. IMHO, it is still one of the best prototyping languages avaliable because of speed of implementation. When I write throw-away code, speed of implementation is important.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

> I would too and as such.. would never do it even if
> the compiler did allow it. Now, the question is, is
> it bad that the compiler will allow it? I guess it
> all depends on the cost of disallowing it.

It IS bad if compiler allows it because this way you postpone error resolution to runtime. Too late. Further, if method name matches, error you receive is much harder to track down.

> > Smalltalk:
> > So you need to cast Object to specific type before
> > you call its method?
> > Is there runtime checking if the object is of
> > expected type?
>
> If the compiler cannot resolve the symbol.. it will
> complain... it's smarter than you thought isn't it
> ;)

You did not answer question completely :-(
I thought that you can do following in Smaltalk (Java equivalent):

Object o = new Something();
o.doSomething(); // Object does not have such method, but Something has

If you can do this, it's bad.

> I beg to differ, I got an email from a recruiter
> about three weeks ago about a new project in London
> requiring GemStone/S skills in London.. interested?

There are and always be legacy systems that are maintained or developed. New projects are rarely started with old tools.

> > Smalltalk
> is
> > was a good choice
>
> for certian problem domains. IMHO, it is still one of
> the best prototyping languages avaliable because of
> speed of implementation. When I write throw-away
> code, speed of implementation is important.

Well, I agree with you completely on this.
But I was talking about real huge applications, not throw-away code or prototypes.

brucechapman
Offline
Joined: 2004-03-18
Points: 0

Has anyone else noticed how this discussion is getting very narrow (minded?). :)

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> Has anyone else noticed how this discussion is
> getting very narrow (minded?). :)

Yes... it is quite tiring trying to talk to someone about language ideas when they've 1) obviously never worked with the language and 2) then start to critize how that language functions.

I do dislike the fact that the threads of discussion seem to be chasing C++ when there are other much more interesting directions to turn.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

But recent argument was not about particular language. It was about strong static typing vs. loose dynamic typing. You don't need to work with Smalltalk to be able to discuss this.

And please note that it was you who headed this thread's discussion off topic.

It was about "is it a good idea to make our good old switch work with objects?". You wanted it to be "do we need switch at all?". Sounds to me like you don't dare to request removing switch/case from the language so you started to fight your own little war (or is it propaganda?). No offense intended, this is how I feel it.

All I want is to make switch/case more useful. And it would be more useful. I use it very rarely, usually when pure OOP and polymorphism seem to be too big a hammer. When when it comes to it, I allways regret it does not work with objects.

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> But recent argument was not about particular
> language. It was about strong static typing vs. loose
> dynamic typing. You don't need to work with Smalltalk
> to be able to discuss this.

Sorry, I disagree. I think that if you are going to discuss the merits of one technique overy another, you should have some experience with both techniques.

>
> And please note that it was you who headed this
> thread's discussion off topic.

What I think I was trying to offer was alternatives to switch that are more in line with the principles of OO. I don't believe that this is off topic.
>
> It was about "is it a good idea to make our good old
> switch work with objects?". You wanted it to be "do
> we need switch at all?". Sounds to me like you don't
> dare to request removing switch/case from the
> language

Humm, I see it as do we need switch with objects. I don't feel that switch has a place in a language that supports OO concepts. That said, Java has a functional side to it in that it exposes some things as primitives. You do need to be able to work with these and manipluate them which is why we have switch, for, while, if then else, do while, operators +, -, etc... in the language. Since these constructs are necessary and removing them would break backwards compatability, you quite correct, I would not suggest that they be removed from the language.

> or is it propaganda?

I'm sorry if you feel that my disagreement with proposals that further complicate the syntax in the language as propganda. As for the war.. yes I'm fighting a war against complexity. I am fighing for simplicity and minimalisum in expression. Everything we know about language (computer and natural) tells us that more syntax/grammer only adds complexity.

). No offense intended

No offese taken, this is a technical discussion on the merits of different techniques and in which direction we should move Java. I'm for simplicity and as I see it, you are for complexity. Sometimes you need complexity but you always need to minimize it.

> All I want is to make switch/case more useful.

And I'm unhappy that we have to keep this construct in the language. As such, I work to minimize it's influence ;)

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

> Sorry, I disagree. I think that if you are going to
> discuss the merits of one technique overy another,
> you should have some experience with both
> techniques.

And I do have experience. Not with Smalltalk but surely with the technique in question. That's why I value strong static typing so much.

> What I think I was trying to offer was alternatives
> to switch that are more in line with the principles
> of OO.

OO is not just about polymorphism.
Current switch/case is primitive legacy tool. If it supported objects, it would be an "OO switch".

> Humm, I see it as do we need switch with objects. I
> don't feel that switch has a place in a language that
> supports OO concepts.

if/else, switch/case, do/while, for/foreach, all these are basic language flow control tools. They have their place even in OO language. It is the same for operators. They do not exist only because of primitives. You can do all these things with methods, OO, polymorphism, etc. But why? These are effective, well-understood idioms.

> ... further complicate the syntax ...

particularly object-enabled switch/case does not complicate syntax, it eliminates the unnecessary limitation. Syntax does not change at all.

> direction we should move Java. I'm for simplicity and
> as I see it, you are for complexity.

It depends. I love simplicity and I prefer it when designing solutions. I always ask one question: how can I make this simpler?
If making it simpler introduces some complexity into the language, I vote for it. I guess there there were people in the times of functional programming languages who objected that creating object-oriented language with polymorphism support introduces unnecessary complexity into the language. Would you agree with them?
[b]
Simplicity of the language is not of my primary interest (but i want it too, of course). It is simplicity of the solutions I can design using this language that matters.
[/b]

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> > Sorry, I disagree. I think that if you are going
> to
> > discuss the merits of one technique overy another,
> > you should have some experience with both
> > techniques.
>
> And I do have experience. Not with Smalltalk but
> surely with the technique in question. That's why I
> value strong static typing so much.

Then you should use this experience to talk through you arguments. I used Smalltalk because I've worked in it and understand it capabilities. I have much less experience with Ruby and Haskel so I won't comment on how someone should use these langauges nor on what the capabilities of the tools are that surround these languages.

> Current switch/case is primitive legacy tool. If it
> supported objects, it would be an "OO switch".

I don't believe that switch and OO are compitable.

>
> if/else, switch/case, do/while, for/foreach, all
> these are basic language flow control tools. They
> have their place even in OO language.

I do believe that developers have been poorly educated into believing that these are the mechanisums of choice in a language. In effect, they have been brain washed to reject languages that do not contain these types of structures and continue to ignore the evidence that we can do perfectly fine without them. In fact, even in java, these things ONLY work with primitive values and with slightly different language/library support (see Filter thread and closures) we would only need them when we couldn't pass a code block as a method parameter. It would seem that filters would try to achieve this in a very static manner which is still better than the situation that we have today.

> It depends. I love simplicity and I prefer it when
> designing solutions. I always ask one question: how
> can I make this simpler?
> If making it simpler introduces some complexity into
> the language, I vote for it.

Ok, maybe way off topic but that is the law of threads isn't it ;)

The most important feature about any language, natural or otherwise is simplicity. In natural languages, isolated language groups tend to be very complex and difficult for out siders to learn. It is only when you have preasure to interact that the complexities of language are shed. I see this in english all the time. Airlines now incorrectly use regular rules of grammer to smooth out irregularities. They do this on purpose because it simplifies the language and in doing so, ensures that non-native english speakers understand what they are saying.

I know a interpreter in the European parliment. He says that a majority of the discussions occur in english. People listen to the speakers without much difficulty untill a British speaker starts. He told me that it was at this point the the members would be scrambling for headsets to listen to the interpreters.

Interestingly enough, the Smalltalk world did not mix well with the C++ world. That point is clear in the differences in vocabulary for identical things. For example, operator overloading is now a four letter word but in Smalltalk, since there are no operators, one would regularly use the + or - symbol to define methods and no one would object. C++ is mired in complexity. Smalltalk is concered too strange because of the lack of "convential" structures. In steps Java which appears to be an interesting balance between the two that represents a simplifcation with the inclusion of "expected" structures.

Maybe the "complications" being introduced into the language are a sign that we are now past the stage of adoption. To be sure, in creating complexities we are ignoring the overwhelming evidence that what makes a language work [b]is[/b] simplicity.

The parallel between this development and what is happening in the natural language world is striking isn't it?

> Simplicity of the language is not of my primary
> interest (but i want it too, of course). It is
> simplicity of the solutions I can design using this
> language that matters.

Java is a general purpose language. Maybe what you are looking for is a domain specific languages.

dog
Offline
Joined: 2003-08-22
Points: 0

> > Some thing Java programmers don't miss because
> they
> > don't know true bliss yet:
> > - Interactive debugging: where you hit a bug..
> drop
> > to the appropiate stack frame, change the code,
> and
> > continue from where the program left off (lets see
> > you do THAT in Java/Ruby/Python/Perl/C++/whatever)
>
> This exists in Eclipse' debugging for Tomcat
> applications. It does not work all the time ("hot
> code replace failed").

I didn't know about the "hot code replace". It's 2004 now.. this was available in the early 80s! It certainly isn't as intuitive in Java.

>
> > - A non-flat view of you code
>
> What does that look like?
>

In OO the code is organized in Classes and methods.. there is no concept of "file" in OO. So why should it look that way?

Generally code is displayed in a browser and categorized. Sophisticated versions of Smalltalk allow you to look at code revisions, repository versions and such (modern Java IDEs have started to support this concept so you probably don't think it is such a big deal but remember where it came from and how long those guys were using it before we rediscovered it)

> > Java has NO advantage over Smalltalk (except maybe
> > the fact that it is statically typed.. which is a
> > debatable "advantage").
>
> I never understood why people argue against statical
> typing. I think it's one of the most important
> features when choosing a language.

Well.. here goes the debate again!!

Eclipse really shows the strength of static typing (since it "spell checks" your code in ways that dynamically typed languages can't).

But with static typing comes extreme complexity:
- Interfaces
- Generics
- Casting
... and other stuff is the result of trying to make your language more dynamic when it is not really set up to be so. Some OO purists argued that a language is not "pure OO" if it isn't dynamically typed.

I don't know if I agree with one view or the other, but the advantages of dynamic typing are obvious. For example: I'm much much more adept at Java than PHP, and yet I implemented a program much faster in PHP than Java (even tho I spent most of the time looking at tutorials).

The increase in productivity is very real. In Smalltalk, you can even evaluate your code as you write it.. not sure that your little algorithm works? right-click inspect and make sure. In Java it will never be as smooth.

Of course the downside is you need more Unit tests.. but when your productivity is so high, you have extremely good and fast resumable debuggers, then MAYBE maintenance is not so hard.. so MAYBE the lack of static typing is not so bad.

So no... I think the jury is still out.

(Disclosure: I currently prefer static typing of Java (esp. checked exceptions) for my projects)

>
> > Not a toy language by any stretch.
>
> Certainly not. It was a very influential language.
> But I think Java is better.

Java is better because it has broad open source support and industry support.

But as a computer language (from a "pure OO" perspective) Smalltalk is vastly superior because it does a better job at abstracting code (a la "language oriented programming") since it has a very simple linguistic mechanism that smoothly extends for even the most complex concepts (LISP programmers argue this strength in their language too).

Java is just clunky in comparison with all its needless keywords. I believe Smalltalk has 0 keywords and yet is more expressive than Java.

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

>
> Well.. here goes the debate again!!
>
> Eclipse really shows the strength of static typing
> (since it "spell checks" your code in ways that
> dynamically typed languages can't).
>
> But with static typing comes extreme complexity:
> - Interfaces
> - Generics
> - Casting
> ... and other stuff is the result of trying to make
> your language more dynamic when it is not really set
> up to be so. Some OO purists argued that a language
> is not "pure OO" if it isn't dynamically typed.

Fair assesment.... is it dynamic typing or late binding that is important?

>
> The increase in productivity is very real. In
> Smalltalk, you can even evaluate your code as you
> write it.. not sure that your little algorithm works?
> right-click inspect and make sure. In Java it will
> never be as smooth.
>
> Of course the downside is you need more Unit tests..
> but when your productivity is so high, you have
> extremely good and fast resumable debuggers, then
> MAYBE maintenance is not so hard.. so MAYBE the lack
> of static typing is not so bad.
>
> So no... I think the jury is still out.

fair points... and I agree that the jury is still out and we should take a more pragmatic look at the issue.

>
> Java is better because it has broad open source
> support and industry support.

This is the big win... this is why I do Java. There are enough Smalltalk jobs avalible but once people really understood the power of interfaces and how to use them, it became clear that Java was going to win.
>
> But as a computer language (from a "pure OO"
> perspective) Smalltalk is vastly superior because it
> does a better job at abstracting code (a la "language
> oriented programming") since it has a very simple
> linguistic mechanism that smoothly extends for even
> the most complex concepts (LISP programmers argue
> this strength in their language too).

This is what I miss.... a simple linguistic mechanism.. this is why I'm being so vocal about further changes/complications to the language. I like the new for syntax (sans generic requirement). That said, the other request for a filter on collections is a much neater solution. For ideas on that, just look at Martin Fowlers recent publishing on Ruby and closures.

monika_krug
Offline
Joined: 2004-10-14
Points: 0

> Some thing Java programmers don't miss because they
> don't know true bliss yet:
> - Interactive debugging: where you hit a bug.. drop
> to the appropiate stack frame, change the code, and
> continue from where the program left off (lets see
> you do THAT in Java/Ruby/Python/Perl/C++/whatever)

This exists in Eclipse' debugging for Tomcat applications. It does not work all the time ("hot code replace failed").

> - A non-flat view of you code

What does that look like?

> Java has NO advantage over Smalltalk (except maybe
> the fact that it is statically typed.. which is a
> debatable "advantage").

I never understood why people argue against statical typing. I think it's one of the most important features when choosing a language.

> Not a toy language by any stretch.

Certainly not. It was a very influential language. But I think Java is better.

Monika.

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> > Some thing Java programmers don't miss because
> they
> > don't know true bliss yet:

>
> > - A non-flat view of you code
>
> What does that look like?

Code organized for you in method categories. Eclipse tries to do this but IMHO, alphabetical listings are annoying. I want to group by my own scheme.
>
> > Java has NO advantage over Smalltalk (except maybe
> > the fact that it is statically typed.. which is a
> > debatable "advantage").
>
> I never understood why people argue against statical
> typing. I think it's one of the most important
> features when choosing a language.

I disagree that static typing as important as people make it out to be. This is part of the brainwashing that people get in many engineering programs. You don't need static type'ing in a language. There is no evidence that static type'ing improves code quality or reduces defect rates. That fact that code still suffers from ClassCastExceptions is only further evidence that type'ing and inherantence with interfaces sort of work against each other.
>
> > Not a toy language by any stretch.
>
> Certainly not. It was

is

> a very influential language.
> But I think Java is better.

In your opinon, in what way is Java better? I think that it is better in a few aspects but it is certianly deficent in many others. Interfaces good, distinction (at the langauge level) between primitives and objects not so good as one example for each.

monika_krug
Offline
Joined: 2004-10-14
Points: 0

> You
> don't need static type'ing in a language. There is no
> evidence that static type'ing improves code quality
> or reduces defect rates.

I think this is self-evident.

> That fact that code still
> suffers from ClassCastExceptions

Many of which can be avoided with generics.

> is only further
> evidence that type'ing and inherantence with
> interfaces sort of work against each other.

Can you explain why these two work against each other?

> In your opinon, in what way is Java better? I think
> that it is better in a few aspects but it is
> certianly deficent in many others. Interfaces good,
> distinction (at the langauge level) between
> primitives and objects not so good as one example for
> each.

I think not everything needs to be an object. Primitive data types, if structures, loops, methods should be just that, not be forced into being objects. "Almost everything is an object" as in Java is great, "absolutely everything is an object" as in Smalltalk makes the language unnecessarily complicated.

Monika.

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

>
> > That fact that code still
> > suffers from ClassCastExceptions
>
> Many of which can be avoided with generics.

I think the jury is still out on this point.

>
> > is only further
> > evidence that type'ing and inherantence with
> > interfaces sort of work against each other.
>
> Can you explain why these two work against each
> other?

On the one hand, you have a system that wants to strongly type something and on the other hand you have a system that wants to relax that constraint to the point where everything looks the same (ie. everything is an object). It is the strongly type'ing requirement that is forcing class cast exceptions. In an untyped system, you get method not found exceptions (which are still possible in Java btw).
>
> > In your opinon, in what way is Java better? I
> think
> > that it is better in a few aspects but it is
> > certianly deficent in many others. Interfaces
> good,
> > distinction (at the langauge level) between
> > primitives and objects not so good as one example
> for
> > each.
>
> I think not everything needs to be an object.
> Primitive data types, if structures, loops, methods
> should be just that, not be forced into being
> objects. "Almost everything is an object" as in Java
> is great,

fair enough.... two thoughts.. first, the language is the interface.. not the implementation! The choice in the language is, do you expose primitives or do you let the compiler look after sorting that stuff out. I vote for the compiler as I'm not interested in weither or not a place holder is a primitive or an object and I don't really care about the implementation as long as it give me the performance that I need. Smalltalk does this by treating primitives as immediate objects (the value is there.. you don't need to fetch it out of the heap.. but this is an detail of the implementation ;)

Secondly, a consequence of exposing primitives is that it forces two types of thinking, object and functional. That.. is evident in the grammers that exist to support both systems. Ok if one understands this and can seperate the two. Disasterous if one cannot. I do a lot of work with OO metrics. The two sets of metrics that are of interest to this conversation are those that measure relationships and those that measures bulk. In general what I've found is that code that seperates the use of primitives from objects tend to produce less bulk and create simpler relationships. Halstead (vocabulary, volume) metrics are good for measuring bulk, Parameter counts, Demeter, fan out and depth of inheritance are but a few interesting relationship metrics.

"absolutely everything is an object" as in
> Smalltalk makes the language unnecessarily
> complicated.

I'm sorry but I don't see how anyone can say that Smalltalk syntax is complicated. In fact, it's rather simple. I've taught 95% of all the Smalltalk syntax that exists in less than 30 minutes of instruction to many developers. You most certianly can't teach Java syntax in any where near that short a time frame. Look at Dr. Heinz Kabutz's newsletter (The Java Specialist). He has published many (in fact he just published is 100th newsletter though it's not about syntax) newsletters regarding interesting or confusing points in Java syntax. Smalltalk syntax is hardly worth talking about.

monika_krug
Offline
Joined: 2004-10-14
Points: 0

> > > That fact that code still
> > > suffers from ClassCastExceptions
> >
> > Many of which can be avoided with generics.
>
> I think the jury is still out on this point.

You are the only person I know that is against generics ;-) .

> > > type'ing and inherantence with
> > > interfaces sort of work against each other.
> >
> > Can you explain why these two work against each
> > other?
>
> On the one hand, you have a system that wants to
> strongly type something and on the other hand you
> have a system that wants to relax that constraint to
> the point where everything looks the same (ie.
> everything is an object).

I still don't get it. Why does inheritance with interfaces make everything look the same?

> It is the strongly type'ing
> requirement that is forcing class cast exceptions. In
> an untyped system, you get method not found
> exceptions

So, what makes a method not found exception better than a class cast exception?

> (which are still possible in Java btw).

Only with reflection, arent't they?

> > I think not everything needs to be an object.
> > Primitive data types, if structures, loops,
> > methods
> > should be just that, not be forced into being
> > objects. "Almost everything is an object" as in
> > Java is great,
>
> fair enough.... two thoughts.. first, the language is
> the interface.. not the implementation! The choice in
> the language is, do you expose primitives or do you
> let the compiler look after sorting that stuff out. I
> vote for the compiler as I'm not interested in
> whether or not a place holder is a primitive or an
> object and I don't really care about the
> implementation as long as it give me the performance
> that I need. Smalltalk does this by treating
> primitives as immediate objects (the value is there..
> you don't need to fetch it out of the heap.. but this
> is an detail of the implementation ;)

It's not (only) because of speed primitives should be primitives. People think of numbers as numbers, not as objects. 5 + 3 makes them think 5 plus 3, not send the plus message to the 5 object with the 3 parameter.

People do not think of if constructs or loops as objects, either.

> Secondly, a consequence of exposing primitives is
> that it forces two types of thinking, object and
> functional. That.. is evident in the grammers that
> exist to support both systems. Ok if one understands
> this and can seperate the two. Disasterous if one
> cannot.

Well, who can't?

> I do a lot of work with OO metrics. The two
> sets of metrics that are of interest to this
> conversation are those that measure relationships and
> those that measures bulk. In general what I've found
> is that code that seperates the use of primitives
> from objects tend to produce less bulk and create
> simpler relationships. Halstead (vocabulary, volume)
> metrics are good for measuring bulk, Parameter
> counts, Demeter, fan out and depth of inheritance are
> but a few interesting relationship metrics.

This sounds as being in favor of leaving primitives as primitives to me.

> I'm sorry but I don't see how anyone can say that
> Smalltalk syntax is complicated.

Syntax maybe not, but I find thinking in Smalltalk a lot more cumbersome than thinking in Java.

Monika.

dog
Offline
Joined: 2003-08-22
Points: 0

> Syntax maybe not, but I find thinking in Smalltalk a lot more cumbersome than thinking in Java.

this discussion started with someone bemoaning the lack of a "pure OO language". Smalltalk is pure OO.. it is simple, not cumbersome at all, everything works the same way.

All these rules about when something works this way or that IS cumbersome. I know, because I've had to teach those concepts.

Pure OO is good for OO programming because it is PURE.. so you don't have to readapt concepts over an over again.. just think one way. This is a feature not a bug.

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> I think one of the key things about switch statements
> is that you know (or hope) they are implemented
> efficiently.
Java switch is currently implemented with one of two byte-codes. The first is a jump table used the case values are contigious and the other supports a list which works out to be O(n).

That said, IMHO, switch is really a poor mans substitution for polymorphisum. I've never really felt a need for a switch unless I was dealing with primitives. Even then, the number of cases were fairly limited.

peterkessler
Offline
Joined: 2004-10-27
Points: 0

I think one of the key things about switch statements is that you know (or hope) they are implemented efficiently. If I have a switch with hundreds of cases I expect the compiler to sort the cases [i]at compile-time[/i] and to use a jump table if the cases are dense, or a binary search if the cases aren't dense, or a tree of if-then-else's if there aren't enough cases to worry about. If you require that switch statements compile to chained if-then-else's, you have broken the ability to implement switches efficiently.

Then you might as well write the if-then-else's yourself, and have it staring you in the face that if-then-else's with hundreds of branches aren't going to be efficient, and maybe think about implementing your control flow with something like polymorphism, or enums.

It doesn't take many calls to Object.equals(Object) to lose out to any of the usual ways of implementing switches. For better or for worse, modern machines are good at comparing integers. Since I don't know how expensive it is to call your overridden Object.equals(Object) method, you've broken my ability to reason about the efficiency of my switch statement.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

First of all, switch is about syntax. Nowhere in JLS or JVM spec it is said how it should be implemented (besides the fact opcode is reserved for it).

To optimize your code, you have to find bottleneck. we use profilers for this. I have never seen an application where if/else bottleneck could be optimized by rewriting it to switch/case. Bottlenecks were and are always elsewhere.

Not sure about you, but if I should write if/else or switch/catch with more than 10 variants, I'd rather pick up another solution (polymorphism and alike). Switch with hundreds of 'cases' is never a good code, no matter how fast it is.

[i]> Since I don't know how expensive it is to call your overridden Object.equals(Object) method, you've broken my ability to reason about the efficiency of my switch statement. [/i]

But you never know how expensive it is, and object-enabled switch/case is not guilty of this.
E.g. in interpreted JVM, polymorphic, nested equals() call can be pretty expensive. On the other hand, hotspot may optimize out enum comparison to inlined == comparison (can't be faster).

[b]Object-enabled switch/case is particularly useful for constructs that reasonably take advantage of fall-through feature which would be very ugly and unreadable when written using if/else cosntructs[/b]

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> I have never seen an
> application where if/else bottleneck could be
> optimized by rewriting it to switch/case.

Actually, I have seen a case where the bottleneck was in a method with a small number of if then else statements (and a few other things). The most optimal solution was to use a switch statement. That said, it was a bit of an edge case....

>
> [b]Object-enabled switch/case is particularly useful
> for constructs that reasonably take advantage of
> fall-through feature which would be very ugly and
> unreadable when written using if/else cosntructs[/b]

[b]which is really a poor sub for polymorphisum[/b]

yishai
Offline
Joined: 2003-11-16
Points: 0

> Enum switches do not behave with == (Well,
> technically, this may be true, but we should not
> care.)
> Truth is that
> 1) Enums are Objects,
> 2) They are used in switch/case
> 3) Their equals() method is final and implemented
> using ==
> operator

I did a little digging ( http://jcp.org/aboutJava/communityprocess/jsr/tiger/enum.html ) and it seems that it doesn't use equals at all, it uses the ordinal. The fact that an enum's equals method uses == is an implementation detail, and is not documented in the Enum javadocs.

> How can you tell enums use == in switch/case? On high
> level, you can still think of it as if equals() was
> used. The fact that equals() uses == does not make
> any difference.
>
> There is nothing confusing about this.
> Logically, switch() evaluates expression, and this
> expression is checked for match in 'case' statement.

I would like to think that is the case, but in fact I think it would get too confusing. We would have three behaviors on switch. 1, for primitives, where only constants can be used. 2, for enums, where only enums can be used, and 3 for objects, where any reference can be used, not just constants. Why can't enum switches use references as well? Well, I guess you could change that, but that would make enums hard to understand, and could lead to some truely wicked switch statements.

Bottom line for me:

I would like to see it, but I understand the argument that it makes the language unpredictable, and voilates the principle of least surprise.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

[i]> I would like to see it, but I understand the argument that it makes the language unpredictable, and voilates the principle of least surprise.[/i]

This and all other is simply not true.
You have expression in switch() and you have expression in 'case:'. If these match, code is executed.

A Match is evaluated in precisely defined semantics: if you compare objects, equals() is used, in case of primitives, '==' is used.

You don't (and you should not) need to know anything about implementation details. You only care about how it works (evaluate, check for match, execute).

It is simple and trasparent, I still can't see what problem you all talk about.

yishai
Offline
Joined: 2003-11-16
Points: 0

> It is simple and trasparent, I still can't see what
> problem you all talk about.

I think what we talking past each other is the limitations of the case label.

[pre]

int i = 1, j =2;
if (someBoolean) i =3;
switch(someValue) {
case i: doSomething(); break;
case j: doSomethingElse(); break;
}

[/pre]

is not acceptable in switches currently, or in enums for that matter. But it would have to be for objects. I could live with the primative/object duality, but I am not sure I would like the primative/enum/object three-state switch.

Now you could probably retrofit enum's to behave like objects, but then you would lose performance advantages, something that many would complain about. Bottom line, looks like it isn't worth it.

A little personal disclaimer here, I never use switches for code I care about. (An if/else is easier to read, harder to make a mistake about (forget to put in a break; ) and simple to change if you move away from a primative.). The only thing that I would find a switch useful for is complex fall-through scenarios, where if/else can't get the job done. But those are hard to read and understand, so I would rather design a better solution using polymorphism. But I still have to read and maintain switch statements, so I do care about them being understandable.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

> is not acceptable in switches currently, or in enums
> for that matter. But it would have to be for objects.
> I could live with the primative/object duality, but I
> am not sure I would like the primative/enum/object
> three-state switch.

There would be no three-state switch. Semantics would always be the same.

Even now you can think of enums in switches as if they used equals() for match evaluation in switch/case. The result is always the same. The fact that you can compare enums using == is utilized to make enums work with switch. It's a kind of hack from OOP point of view.

But we don't need to care. There would be no difference if enums were compared using equals() in switch.

[b]So, there would be no more than primitive/object duality in object-enabled switch/case. Once we have it, there's no need to treat enums especially.[/b] They would be just objects.

yishai
Offline
Joined: 2003-11-16
Points: 0

> [b]So, there would be no more than primitive/object
> duality in object-enabled switch/case. Once we have
> it, there's no need to treat enums especially.[/b]
> They would be just objects.

I think you missed my point. The difference between enums and objects would be if you require constants in the case clause. If you remove the requirement for enums, then performance suffers. If you don't, you have a three-state switch.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

I see.
But please understand following:

- constants, as defined in Java (final keyword), are variables that cannot be re-assigned, that's all. If you create [tt]final Map MYMAP[/tt], it does not mean that MYMAP object cannot be changed, it means that MYMAP variable cannot be assigne danother value

- for constants as final objects, if the object itself does not guarantee immutability, it is constant by definition, not 'by virtue'

- while talking about syntax, you should IMHO never talk about performance in the same breath.

[i]> If you remove the requirement for enums, then performance suffers. If you don't, you have a three-state switch. [/i]

I cannot disagree more. How can you tell there is something like three-state switch based on any performance benchmark?

Further, note that the performance is solely dependent on a particular implementation and no specification says that object-enabled switch/case cannot be as fast as primitive in some scenarios.

Compiler can safely detect that MyClass.equals() method is final and implemented as "return this==other;". This means that compiler (hotspot or even javac) can optimize any switch that uses MyClass instances in 'case' statements to be as fast as possible and equivalent to the way current primitive or enum switches work.

The point is that you can always have the fastest code available without changing syntax.
Another point is that you should never assume performance from syntax.

yishai
Offline
Joined: 2003-11-16
Points: 0

> - constants, as defined in Java (final keyword), are
> variables that cannot be re-assigned, that's all. If
> you create [tt]final Map MYMAP[/tt], it does not mean
> that MYMAP object cannot be changed, it means that
> MYMAP variable cannot be assigne danother value

Sure, but switches (even enum switches) work on primatives, not objects (mutable or otherwise), so the usage of a constant only ensures the compiler can inline an int (or long, or whatever it uses).

> - for constants as final objects, if the object
> itself does not guarantee immutability, it is
> constant by definition, not 'by virtue'
>
> - while talking about syntax, you should IMHO never
> talk about performance in the same breath.

I think that alot of the justification of a switch statement from the days of C is performance. It would never have been thought of otherwise. There would only be if/else. Java carries on that legacy.

> [i]> If you remove the requirement for enums, then
> performance suffers. If you don't, you have a
> three-state switch. [/i]
>
> I cannot disagree more. How can you tell there is
> something like three-state switch based on any
> performance benchmark?

No, not based on performance, based on syntax. Will a case statement with something other than a constant compile? On Object switches that would truely be an artificial pointless limitation. But that is the current limitation with both primatives and enums.

> The point is that you can always have the fastest
> code available without changing syntax.
> Another point is that you should never assume
> performance from syntax.

I think that the limitations of what can come after a case is syntax related. The limitation exists for performance reasons, but it expresses itself in syntax.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

> Sure, but switches (even enum switches) work on
> primatives, not objects (mutable or otherwise), so
> the usage of a constant only ensures the compiler can
> inline an int (or long, or whatever it uses).

That's why this proposal exists, dude. To eliminate this unnecessary limitation.

>
> I think that alot of the justification of a switch
> statement from the days of C is performance. It would
> never have been thought of otherwise. There would
> only be if/else. Java carries on that legacy.

You're mistaken. Case/switch has fall-through which cannot be nicely done with if/else.
Besides this, why should we limit ourselves to C legacy?

> No, not based on performance, based on syntax. Will a
> case statement with something other than a constant
> compile? On Object switches that would truely be an
> artificial pointless limitation. But that is the
> current limitation with both primatives and enums.

It will compile, it is possible, and that's why this proposal exists.
Switch/case is just different if/else.

> I think that the limitations of what can come after a
> case is syntax related. The limitation exists for
> performance reasons, but it expresses itself in
> syntax.

Again, even if this is true, which I doubt, why should wew stick ourselves to C legacy?

yishai
Offline
Joined: 2003-11-16
Points: 0

> > Sure, but switches (even enum switches) work on
> > primatives, not objects (mutable or otherwise), so
> > the usage of a constant only ensures the compiler
> can
> > inline an int (or long, or whatever it uses).
>
> That's why this proposal exists, dude. To eliminate
> this unnecessary limitation.

That's fine. I understand that. What I am saying is you are proposing to change the Enum switch syntax and implementation, which will reduce its performance. That won't go down easy with every Java user. If you don't change the enum syntax (which is what I think would end up happening) then we have 3 types of switches. And 3 types is 1 type too many for me.

> >
> > I think that alot of the justification of a switch
> > statement from the days of C is performance. It
> would
> > never have been thought of otherwise. There would
> > only be if/else. Java carries on that legacy.
>
> You're mistaken. Case/switch has fall-through which
> cannot be nicely done with if/else.
> Besides this, why should we limit ourselves to C
> legacy?

I think a lot of the success of Java had to do with its imitation of C syntax. I am not arguing though that it has to be ints so it can be a jump table, so that it works like C. I am just saying that the usage of switch over if/else is about performance for a lot of people. Complex fallthrough scenarios are rare, and hard to read in switch statements. And easy fallthrough stuff is just as easy in an if/else using || in the if clause. In and of itself it wouldn't make a language designer design a statement just to accomidate it. C was designed as high-level assembler, and assembler had jump tables, so C got a switch/case. I could be wrong about all of that, but that is my understanding. Researching the history of switch is a little too much work for a forum post.

> > No, not based on performance, based on syntax. Will
> a
> > case statement with something other than a
> constant
> > compile? On Object switches that would truely be
> an
> > artificial pointless limitation. But that is the
> > current limitation with both primatives and enums.
>
> It will compile, it is possible, and that's why this
> proposal exists.
> Switch/case is just different if/else.

If it would compile, then you are loosing the special nature of the enum case. I'm fine with that. But I don't think that is a realistic language change, any more than dropping all deprecated methods would be. It would also be hard to retrofit to enums because a switch requires an unqualified enum name in the case statement (with the qualification determined by the clause of the switch statement), so we would be looking at a backwards incompatable change unless there were special handling. Which puts us back to the 3 type switch.

> > I think that the limitations of what can come after
> a
> > case is syntax related. The limitation exists for
> > performance reasons, but it expresses itself in
> > syntax.
>
> Again, even if this is true, which I doubt, why
> should wew stick ourselves to C legacy?

If we were at Java 0.9, I would agree completely. But we aren't. At 5.0, you have to respect what people thought they were getting out of switch/case when they started using enums with them.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

let me say that once more. Switch can be rewritten as if/else statement. Provided the rules for rewriting are intuitive, logical and transparent, you will be able to use switch efficiently and without any mystery behind the scenes.

Semantics remains unchanged. Condition matches, action is performed. No miracle.

yishai
Offline
Joined: 2003-11-16
Points: 0

It would seem that the fact that enum switches work would undermine the ability to add Object switches (something I always wanted as well). The enum switches behave with == but Object switches would not, they would use .equals(). That would be very confusing, as enums are Objects too.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

Enum switches do not behave with == (Well, technically, this may be true, but we should not care.)
Truth is that
1) Enums are Objects,
2) They are used in switch/case
3) Their equals() method is final and implemented using ==
operator

How can you tell enums use == in switch/case? On high level, you can still think of it as if equals() was used. The fact that equals() uses == does not make any difference.

There is nothing confusing about this.
Logically, switch() evaluates expression, and this expression is checked for match in 'case' statement.
For primitives, == is used as they do not have any equals() method.
For objects, equals() is used as this is how object equality (not identity) is defined

No magic, no miracle, no confusion at all. Simple as that

swpalmer
Offline
Joined: 2003-06-10
Points: 0

There is a huge difference here.

Objects in general are not CONSTANTS.. switch/case requires constants! To change that would be too great a change.. switch/case becomes something entirely different.

Enums are constants, they are basically treated as literal values, so it made sense to allow them. Perhaps it would make sense to allow literal strings.

Other languages with switch/case (e.g. C++) do not allow this either.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

Please understand that this proposal DOES change what data types switch/case operates on. I agree, I don't doubt this.

But it does not change semantics at all. And that't the whole point.

What does it matter if objects being compared are final/constant or not? switch/case is about comparison and decision.

Immutability is an implementation requirement.
And I hope you will agree that it is very unlucky that such a requirement is in laguage specification. At least in this case.

ulfzibis
Offline
Joined: 2005-02-18
Points: 0

[b]@ yod[/b]

I agree with all what you say. For me it's the best conclusion in this thread.

[b]case-statements should test for identity as "==" by default, also for objects.[/b]

For more flexibility I propose an additional syntax like:
[code]
switch( myObject) {
case equals( CONSTANT1) : doSomething(); break;
case equals( CONSTANT2) : doSomethingElse(); break;
default : doNothing();
}
[/code]
Example for Strings:
[code]
switch( myString) {
case equals("black") : doSomething(); break;
case equals("white") : doSomethingElse(); break;
default : doNothing();
}
[/code]
More additional syntax:
[code]
switch( myString) {
case startsWith("b") : doSomething(); break;
case startsWith("w") : doSomethingElse(); break;
default : doNothing();
}
[/code]
[code]
switch( myPrimitiveInt) {
case < 7 : doSomething(); break;
case < 10 : doSomethingElse(); break;
default : doNothing();
}
[/code]

Message was edited by: UlfZibis

Message was edited by: UlfZibis

monika_krug
Offline
Joined: 2004-10-14
Points: 0

> I would restrict
> case values to compile-time constants that would be
> compared by reference (ie, with == and not with
> equals) with mutually incompatible cases (otherwise,
> a compiler error should raise).

Your objections to general switching on objects are right, there are more problems than one might think.

But switching on String literals and String constants known at compile time should be possible and included in Mustang. They can be compared with == and the result is known at compile time, so identical cases could be identified and an exception be raised. E.g. "abc" == "ab" + "c" even compiles to true (tested with javac 1.4).

Or does this vary by implementation? Maybe the specification does not require this behavior, so maybe with some compilers or VMs even "xyz" == "xyz" could return false.

Monika.

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

String literals are constants and even "ab"+"c" is constant because it can be evaluated at compile time.
"ab" constant from class A and "ab" constant from class B will point to the same constant at runtime.
This is given by JLS (or even VM spec, not sure).