mardi 18 janvier 2022

Better solutions to long pattern matching chains (for Dart)

I've often found myself having to use annoying patterns like:

ClassA extends BaseClass {
  static bool is(val) { ... }
}
ClassB extends BaseClass {
  static bool is(val) { ... }
}
...
ClassZ extends BaseClass {
  static bool is(val) { ... }
}

BaseClass parser(val) {
  if(ClassA.is(val)) {
    return ClassA(val);
  } else if(ClassB.is(val)) {
    return ClassB(val);
  ...
  } else if(ClassZ.is(val)) {
    return ClassB(val);
  }
}

This is very error prone and requires a lot of monotonous code. I was wondering if there was a way to expedite this process in a non-language specific (or in a language specific for Dart) way that doesn't involve listing all the pattern matchers after they've been defined. I would like to avoid this as I had too many bugs to count caused by forgetting to list one of the already defined class's pattern matcher.

Aucun commentaire:

Enregistrer un commentaire