String-based Switch Request...

  • Follow


[] A string-based switch would have the following benefits for JAVA,

   1) Increase maintainability of code (especially GUI code)
   2) Facilitate good callback programming design and modularization
within GUI code


[] A string-based switch would have the following drawbacks for JAVA,

   Umm,...actually there are none.  C, Fortran lovers can still do
their integer-based switch.  If overcoming inertia it's such a big
concern, why not just call it sswitch (string-switch) or wswitch
(word-switch) or something else.

The best alternative I have used to date (although ugly)
is for a String S:

while (true) //String-based switch mimic...
{
    if (S.equalsIgnoreCase("run"))
    {
        System.out.println("Do one thing");
        break;
    }

    if (S.equalsIgnoreCase("jump"))
    {
        System.out.println("Do another thing");
        break;
    }

    //etc...

    System.out.println("Otherwise do something here.");
    break;

}

0
Reply dpdoughe9579 (9) 4/13/2005 6:35:54 PM


Dan wrote:
> [] A string-based switch would have the following benefits for JAVA,
> 
>    1) Increase maintainability of code (especially GUI code)
>    2) Facilitate good callback programming design and modularization
> within GUI code

    Not everyone agrees that (2) is a good idea -- that
is, everyone agrees that "good" is good, but not everyone
buys the idea that Strings are good enumerators.  See,
for example, Bloch in "Effective Java."

    Even (1) is subject to a few questions.  Using Strings
for case labels (or even for `if' ladders) whose main task
is to identify particular objects is error-prone (did the
user click the "Go" button or the "GO" button?), and seems
to contravene the O-O mantra that behavior should reside in
the objects rather than in their clients.  It might be better
to attach a behavior-defining object to the JButton (perhaps
by extending JButton); that way you won't be surprised when
somebody internationalizes your code and the button name
changes to "Allez."

    I'm not claiming that arguments like these will or should
carry the day, but it would be premature to rush a feel-good
feature into the language until such arguments are resolved.

-- 
Eric.Sosman@sun.com

0
Reply Eric.Sosman (4228) 4/13/2005 7:01:13 PM


The text label one sees when the GUI is rendered certainly does not
need to be the same String used in the callback.  In general I think
code written by a French speaker is going to be pretty unreadable by an
English speaking programmer.  In otherwords when talking of
internationalization we need to separate internationalization of the
code from internationalization of the application.  So I don't find the
"Go" versus the "Allez" argument all too convincing.  But perhaps you
meant something more general there I just didn't get it.

Also, the simple convention that case-insensitive switches be used (as
shown in my "while" kludge) would certainly be a "good programming
practice" but not a requirement.

The main issues with GUI and other potentially interactive modules are
design and maintainability (which are related) not so much the
internationalization.   The goal is not to "enumerate" the possible
events as such but to communicate in as central a location as possible
so that future developers don't need to fish around reading through
layers upon layers of OO heirarchy.

For example if I know that either "Go" was pressed or "GO" was pressed,
I'm a lot closer to understanding what's maybe just happened than if I
know "56" was triggered by something, somewhere, somehow...

0
Reply dpdoughe9579 (9) 4/13/2005 7:38:03 PM

Dan wrote:
> [] A string-based switch would have the following benefits for JAVA,
> 
>    1) Increase maintainability of code (especially GUI code)
>    2) Facilitate good callback programming design and modularization
> within GUI code
> 

I think you'll find that it would do neither of those two things. If we 
had String based switches, why stop there?  why not Enums, User defined 
types, etc.?  Because ...

1) When ever switch statements are used, they are typically over used 
being favour over polymorphism, which leads to brittle shoddy design. 
Switch statements are best used in isolated cases (no pun intended) like 
Abstract Factories. These use the switch to decide which object to 
create, and then we can take advantage of polymorphism.

As for GUI code explicitly, Java actually moved away from Conditional 
logic to polymorphism because of these problems.

2) Switch statements have nothing to do with callbacks. Sure we CAN use 
them for that purpose, but then we can use any of the languages 
constructs for the same purpose (arrays, If/else, Collections, etc.).

> 
> [] A string-based switch would have the following drawbacks for JAVA,
> 
>    Umm,...actually there are none.  C, Fortran lovers can still do
> their integer-based switch.  If overcoming inertia it's such a big
> concern, why not just call it sswitch (string-switch) or wswitch
> (word-switch) or something else.
> 

Umm, actually loads, at best they would give another procedural 
programming construct to an OO language. At worst see above.

> The best alternative I have used to date (although ugly)
> is for a String S:
> 
> while (true) //String-based switch mimic...
> {
>     if (S.equalsIgnoreCase("run"))
>     {
>         System.out.println("Do one thing");
>         break;
>     }
> 
>     if (S.equalsIgnoreCase("jump"))
>     {
>         System.out.println("Do another thing");
>         break;
>     }
> 
>     //etc...
> 
>     System.out.println("Otherwise do something here.");
>     break;
> 
> }
> 

I take it your application has 'type codes' that are string based and 
this is why you are posting this 'idea'.  If it does then one approach 
would be to use a HashMap.  Use the string type-code as the Key and a 
Command or Strategy Object as the Value.

e.g using inheritance and polymorphism...

interface Command {
    void execute();
}

class abstract AbstractPrintlnCommand implements Command {
    public void execute() {
       String msg = getMessage();
       System.out.println("Do one thing");
    }

    protected String getMessage();
}

class RunCommand extends AbstractPrintlnCommand {
    protected String getMessage() {
       return "Do one thing";
    }
}


class JumpCommand extends AbstractPrintlnCommand {
    protected String getMessage() {
       return "Do another thing";
    }
}


class LetsUseOO {

    public LetsUseOO() {
        commands.put("Run", new RunCommand());
        commands.put("Jump", new JumpCommand());
    }

    public void printMessage(String typeCode) {
       Command command = commands.get(typeCode);
       command.execute();
    }

    private Map commands = new HashMap();
}

Now that we have this simply pattern, we can populate the hashmap in 
numerous ways.

As above it could be hard coded - exactly like the switch is hardcoded.

Or better yet we could populate at runtime by using a config file which 
specified the typeCode and name of the Command implementing class, then 
with reflection to instantiate the command and populate the hashmap.

And many many more ways of changing the program dynamically - which is 
much more maintainable that hard coded switch statements. We could ship 
and deploy a system and then later on ship a new or modified Jar which 
just contains new Commands and these would be able to be used without us 
having to ship and deploy a whole  new system.

Trying to use C constructs in Java is the problem - don't do it, it will 
make your job more difficult and the maintainers job a nightmare.


0
Reply news248 (613) 4/13/2005 9:39:48 PM

"Andrew McDonagh" <news@andrewcdonagh.f2s.com> wrote in message
news:d3k3je$ods$1@news.freedom2surf.net...
> Dan wrote:
> > [] A string-based switch would have the following benefits for JAVA,
> >
> >    1) Increase maintainability of code (especially GUI code)
> >    2) Facilitate good callback programming design and modularization
> > within GUI code
> >
>
> I think you'll find that it would do neither of those two things. If we
> had String based switches, why stop there?  why not Enums, User defined
> types, etc.?  Because ...
<snip>

Maybe I am wrong, but:
I thought 1.5 has enums ;-)
I thought a user defined type is a 'class' ;-)


0
Reply lisa8584 (112) 4/13/2005 9:55:07 PM

Betty wrote:
> "Andrew McDonagh" <news@andrewcdonagh.f2s.com> wrote in message
> news:d3k3je$ods$1@news.freedom2surf.net...
> 
>>Dan wrote:
>>
>>>[] A string-based switch would have the following benefits for JAVA,
>>>
>>>   1) Increase maintainability of code (especially GUI code)
>>>   2) Facilitate good callback programming design and modularization
>>>within GUI code
>>>
>>
>>I think you'll find that it would do neither of those two things. If we
>>had String based switches, why stop there?  why not Enums, User defined
>>types, etc.?  Because ...
> 
> <snip>
> 
> Maybe I am wrong, but:
> I thought 1.5 has enums ;-)
True...

> I thought a user defined type is a 'class' ;-)
you aren't wrong...but the OP is suggesting using the java.lang.String 
where as I'm talking classes that I create, not those provided by Sun, 
e.g. com.myDomain.MyWizzyClass




0
Reply news248 (613) 4/13/2005 10:09:06 PM

I don't have a problem with your suggested implementation per se.  I
think the design structure I am thinking of may be different than what
you think I have in mind.

 Let's say my client wants a GUI with some number N panes organized in
a JTabbedPane.  We'll assume that we've programmed things nicely (as
much as possible anyway) so that each Pane can function independently.
However, there may be some button in one Pane that should effect what
goes on in another pane.  One solution is to have a central listener
that is added to each pane upon their construction.  Each pane may have
their own private listeners but they should each accept at
instantiation an outside listener which the Pane may allow to listen to
a subset or all of its actions.  The idea is then that the Panes do
what they do best and the central listener can coordinate their
(public??)  behaviours.  If we want to change the coordination between
Panes then we just need to ship a new central listener.  If we want the
behavior or appearance within a Pane to be modified then we ship
something that fixes that component.  We can add more Panes and modify
central coordination just the same.  As a developer I really only need
to look at the code of the central listener to see what is going on.
It is in the central listener that I argue it would be nice to have a
String-based switch.  No big woop.

I do have an issue with maintainability and readability (which are
related) to this snipit from your code...

public void printMessage(String typeCode) {
       Command command = commands.get(typeCode);
       command.execute();
    }

This is all the developer will have to go on in your design.  Then what
she has to do next is go read that Config file (hopefully the right
one), then go find which class goes with which command then go read
that classe's execute() method or documentation to see what is being
done there.   For even a small number of such commands this does not
bode well for maintainability.

Having a switch statement is no more procedural  than a for-loop
statement is.  It's just a way of organizing what should happen and
when.  There is a difference between classes doing "something"  under a
OOP paradigm and then actually getting around to doing "the something".
 String-based switch helps a class that coordinates to do its job and
do it well.  Not having a String-based switch makes using switch-yard
programming untenable (unless you use something like the "while"
kludge).  Therefore users get tempted into adding all sorts of action
listeners here and there and sewing up the whole bloody mess.  I agree
your implementation will work nicely in many contexts, but it can just
as easily be over used.  FYI, I rarely use switch yard programming
except in GUI programming coordinating between modular classes.

Personally, I think future JAVA versions should either allow
String-based switch or just eliminate the switch statement altogether
(you can add enums in there too).  I agree that integer-based switch
will more than likely lead to crappy procedural-like programming if be
productive at all.  This has been the experience even in procedural
languages such as C.

0
Reply dpdoughe9579 (9) 4/14/2005 12:16:05 AM

Dan wrote:
> [] A string-based switch would have the following benefits for JAVA,
>
>    1) Increase maintainability of code (especially GUI code)
>    2) Facilitate good callback programming design and modularization
> within GUI code
>
>
> [] A string-based switch would have the following drawbacks for JAVA,
>
>    Umm,...actually there are none.  C, Fortran lovers can still do
> their integer-based switch.  If overcoming inertia it's such a big
> concern, why not just call it sswitch (string-switch) or wswitch
> (word-switch) or something else.

>From Fortran 90 onwards there has been a SELECT CASE construct that can
use strings, integers, and integer ranges as switches, as demonstrated
in the following code.

program xselect
implicit none
integer           :: i
character (len=3) :: month
month = "feb"
select case (month)
   case ("jan"); print*,"january"
   case ("feb"); print*,"february"
end select
i = 22
select case (i)
	case (20:29); print*,"twenties"
	case (30:39); print*,"thirties"
end select
end program xselect

0
Reply beliavsky (2207) 4/14/2005 1:05:03 AM

"Dan" <dpdoughe@mbi.osu.edu> wrote in message
news:1113417354.017553.182770@z14g2000cwz.googlegroups.com...
>
> [] A string-based switch would have the following benefits for JAVA,
>
>    1) Increase maintainability of code (especially GUI code)
>    2) Facilitate good callback programming design and modularization
> within GUI code
>
>
> [] A string-based switch would have the following drawbacks for JAVA,
>
>    Umm,...actually there are none.  C, Fortran lovers can still do
> their integer-based switch.  If overcoming inertia it's such a big
> concern, why not just call it sswitch (string-switch) or wswitch
> (word-switch) or something else.
>
> The best alternative I have used to date (although ugly)
> is for a String S:
>
> while (true) //String-based switch mimic...
> {
>     if (S.equalsIgnoreCase("run"))
>     {
>         System.out.println("Do one thing");
>         break;
>     }
>
>     if (S.equalsIgnoreCase("jump"))
>     {
>         System.out.println("Do another thing");
>         break;
>     }
>
>     //etc...
>
>     System.out.println("Otherwise do something here.");
>     break;
>
> }
>

We were just discussing this on the 'stupid question' thread.
A string-based switch is nasty. In fact, a switch is nasty.
Excessive if/else (~4 or more) is nasty.
Always use a strategy instead of a switch or excessive if/else.
Ignore suggestions that you can switch on a String hash code - collisions
are imminent (which is beside the point that it's just nasty anyway).
http://www.google.com/search?q=strategy+design+pattern&hl=en

-- 
Tony Morris

JTiger Unit Test Framework for J2SE 1.5
http://www.jtiger.org/
Java Q&A (FAQ, Trivia)
http://qa.jtiger.org/
http://xdweb.net/~dibblego/


0
Reply not147 (444) 4/14/2005 1:07:00 AM

"Tony Morris" <not@telling.you> writes:

> A string-based switch is nasty. In fact, a switch is nasty.

Yes: The only two reasons for Java to have switch is that 1) C-family
languages have it and 2) primitives aren't objects which makes it
somewhat harder to implement the Strategy pattern for them.
0
Reply tor.iver.wilhelmsen (759) 4/14/2005 6:38:54 AM

"Tor Iver Wilhelmsen" <tor.iver.wilhelmsen@broadpark.no> wrote in message
news:umzs1yi9t.fsf@broadpark.no...
> "Tony Morris" <not@telling.you> writes:
>
> > A string-based switch is nasty. In fact, a switch is nasty.
>
> Yes: The only two reasons for Java to have switch is that 1) C-family
> languages have it and 2) primitives aren't objects which makes it
> somewhat harder to implement the Strategy pattern for them.

I'm glad someone agrees with me :)
I hate pointing out the obvious only to find that years of misguidance prove
to take precedence over common sense.

Now... if only I can make it obvious that non-final classes are also evil.

-- 
Tony Morris

JTiger Unit Test Framework for J2SE 1.5
http://www.jtiger.org/
Java Q&A (FAQ, Trivia)
http://qa.jtiger.org/
http://xdweb.net/~dibblego/


0
Reply not147 (444) 4/14/2005 6:49:01 AM

Tony Morris wrote:
> "Tor Iver Wilhelmsen" <tor.iver.wilhelmsen@broadpark.no> wrote in message
> news:umzs1yi9t.fsf@broadpark.no...
> 
>>"Tony Morris" <not@telling.you> writes:
>>
>>
>>>A string-based switch is nasty. In fact, a switch is nasty.
>>
>>Yes: The only two reasons for Java to have switch is that 1) C-family
>>languages have it and 2) primitives aren't objects which makes it
>>somewhat harder to implement the Strategy pattern for them.
> 
> 
> I'm glad someone agrees with me :)
> I hate pointing out the obvious only to find that years of misguidance prove
> to take precedence over common sense.
> 
> Now... if only I can make it obvious that non-final classes are also evil.
> 

There's a lot us who agree - some like us are vocal - most are not.... 
Unfortunately there's a lot more that do not agree with us and prefer to 
pic-and-mix the programming paradigms. Mind you, keeps them in a job ;-)
0
Reply news248 (613) 4/14/2005 7:18:11 AM

Tor Iver Wilhelmsen wrote:
> "Tony Morris" <not@telling.you> writes:
> 
> 
>>A string-based switch is nasty. In fact, a switch is nasty.
> 
> 
> Yes: The only two reasons for Java to have switch is that 1) C-family
> languages have it and 2) primitives aren't objects which makes it
> somewhat harder to implement the Strategy pattern for them.

Nicely stated!
0
Reply news248 (613) 4/14/2005 7:18:30 AM

Dan wrote:
>    2) Facilitate good callback programming design and modularization
> within GUI code

No, I don't think so. I consider the usual attempts to handle all kinds 
of callbacks/events through one event listener, and then trying to 
fiddle out what event it really was in the event listener a serious 
design error. There is no good excuse (ok, I know one exception) for 
this kind of design.

/Thomas

-- 
The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
0
Reply nobody89 (1419) 4/14/2005 8:08:42 AM

On Thu, 14 Apr 2005 16:49:01 +1000, Tony Morris wrote:

> "Tor Iver Wilhelmsen" <tor.iver.wilhelmsen@broadpark.no> wrote in message
> news:umzs1yi9t.fsf@broadpark.no...
>> "Tony Morris" <not@telling.you> writes:
>>
>> > A string-based switch is nasty. In fact, a switch is nasty.
>>
>> Yes: The only two reasons for Java to have switch is that 1) C-family
>> languages have it and 2) primitives aren't objects which makes it
>> somewhat harder to implement the Strategy pattern for them.
> 
> I'm glad someone agrees with me :)
> I hate pointing out the obvious only to find that years of misguidance
> prove to take precedence over common sense.
> 
> Now... if only I can make it obvious that non-final classes are also evil.

I might agree with the sentiment that non-final, non-abstract classes are
evil.  However, abstract classes provide an extremely convenient way of
sharing truly common functionality across several implementations of an
interface.  Something like:

abstract class A {
  public boolean someBoolMethod () {
    ...
  }
}

/* vv   note what's missing in the above class */
public interface Foo {
  public int interfaceMethod ();
}

public class AFoo extends A implements Foo {
  public int interfaceMethod () {
    if (someBoolMethod ())
      return 1;
    else
      return 0;
  }
}

Obviously this is an extremely contrived example, but the pattern is one
I've found useful for implementing network protocols, among other things.
0
Reply ojacobson (54) 4/21/2005 4:41:34 AM

14 Replies
17 Views

(page loaded in 0.221 seconds)


Reply: