Stubbornly Static Typed

Java.

As much as I like the language, it obviously has its moments.

I can't escape the boneheaded feeling I feel when I write

 public void doSomething(Object parameter){
        if(parameter instanceof SomeType)
                doSomething((SomeType) parameter);
        else if(parameter instanceof SomeOtherType)
                doSomething((SomeOtherType) parameter);
 }

I know, I know, this already has a real name, but just felt like making a CategoryRant :)

-- WilliamUnderwood (taking the blame for this mess)

Can you explain this program to non-Java speakers? Doesn't type coercion solve it?

Why are you using the same method name for two different operations? If you would rename one or both versions of "doSomething()" this problem would go away.


I seem to spend a lot of time doing similar things while talking to DOM stuff -- in that case, the switching is on the node types. Without messing about creating lots of wrapper classes I can't really think of sensible solutions.

-- KatieLucas


The classic refactoring advice, as in SwitchStatementsSmell, is to replace the switch with polymorphism, and as MartinFowler points out, the issue is where to put the polymorphism. There's not enough information in the example above to decide whether this would be a workable solution. -- TomRossen

It's a LanguageSmell. Get MultiMethods/GenericFunctions/MultipleDispatch. The GangOfFour workaround for C++ and Java is VisitorPattern.

Too true, and somewhere deep in the workaround, especially when you decide to add a `just a little' TemplateMetaprogramming `just to help sort out this mess a bit', it hits you: my ghod, Greenspun was right. (See GreenspunsTenthRuleOfProgramming)


See also: SmellsLikeJava

CategoryJava CategoryLanguageTyping


EditText of this page (last edited August 1, 2004) or FindPage with title or text search