2

I have this code:

entity.conditions().forEach(entityCondition - > {
    if (entityCondition instanceof LinkCondition) {
        LinkCondition condition = (LinkCondition) entityCondition;
    } else if (entityCondition instanceof OppositeLinkCondition) {
        //...
    } else if (entityCondition instanceof PropertyEqualCondition) {
        //...
    } else if (entityCondition instanceof PropertyLocalTimeRangeCondition) {
        //...      
    }
    // and 20 or so, more conditions...
});

In which I am looking for an alternative than IF-ELSE statement, a more elegant approach in dealing with dozens of instanceof conditions.

flaxel
  • 4,173
  • 4
  • 17
  • 30
Fireburn
  • 981
  • 6
  • 20
  • Interesting background reading: [when polymorphism fails](https://sites.google.com/site/steveyegge2/when-polymorphism-fails) – jarmod Oct 22 '20 at 19:07
  • 5
    What are you doing inside each block? Having to do `instanceof` checks at all is a code smell. There's probably a better way to do whatever it is you're doing, for example by calling overridden methods on each `Condition` subclass, but it depends on the specifics of your situation. – John Kugelman Oct 22 '20 at 19:07
  • Does this answer your question? [Switch type of Object in Java](https://stackoverflow.com/questions/52830106/switch-type-of-object-in-java) – Progman Oct 22 '20 at 19:07
  • 1
    Also check other questions like https://stackoverflow.com/questions/29570767/switch-over-type-in-java or https://stackoverflow.com/questions/5579309/is-it-possible-to-use-the-instanceof-operator-in-a-switch-statement – Progman Oct 22 '20 at 19:08
  • It may require a complete redesign. Start with generics. Then writing wrapper classes/and or interfaces to consolidate like functions. – WJS Oct 22 '20 at 19:13
  • @WJS can you put your idea into an answer if you may have time – Fireburn Oct 22 '20 at 19:20
  • `stmt?stmt:stmt` can it help? – A Farmanbar Oct 22 '20 at 19:23
  • @Fireburn it would be difficult to give a complete example without knowing more. How different is the processing to be done for each type of condition? – WJS Oct 22 '20 at 19:37

1 Answers1

0

Unfortunately, there is no such syntax in Java yet. You can try Kotlin which already supports this:

val b = when (a) {
    is String -> a.length
    is Int -> a
    is Long -> (a and 0xFFFFFFFF).toInt()
    else -> a.hashCode()
}    

As @Progman pointed out, this question is similar to other questions, you should check them out too.

sb27
  • 382
  • 4
  • 14