A safer switch?

bearophile bearophileHUGS at lycos.com
Mon Oct 12 01:03:13 PDT 2009


This is a pruned method from a command-line Java program:

private static void parseCmdLine(String args[]) {
  int i = 0;
  String arg;
  while (i < args.length && args[i].startsWith("-")) {
    arg = args[i++];
    if (arg.equals("-s")) {
      if (i < args.length)
        size = new Integer(args[i++]).intValue();
      else
        throw new Error("-l ...");
    } else if (arg.equals("-m")) {
      printMsgs = true;
    } else if (arg.equals("-p")) {
      printResults = true;
    } else if (arg.equals("-h")) {
      usage();
    }
  }
  if (size == 0) usage();
}


I may translate part of that to D like this:

switch (arg) {
    case "-s":
        if (idx < args.length)
            size = toInt(args[idx++]);
        else
            throw new Exception("...");
        break;
    case "-m":
        printMessages = true;
        break;
    case "-p":
        printResults = true;
        break;
    case "-h":
        showUsage();
    default:
        showUsage();
        throw new Exception("...");
}

But the "-h" case misses a break. Languages like C# have found a way to avoid (in most cases) that common bug. D may use some like this:

switch (arg) {
    case("-s") {
        try {
          next_arg = iargs.next();
          size = toInt(args[idx++]);
        } catch (...) {
            throw new Exception("...");
        }
    }
    case("-m") {
        printMessages = true;
    }
    case("-p") // just 1 istruction, no {} needed
        printResults = true;
    case("-h"); // semicolon isn't allowed here
        showUsage();
    default { // default case may need some care
        throw new Exception("...");
    }
}

Mixing "case:" and "case()" in the same switch is not allowed, to keep things tidy.

"break" is implicit. You can add "continue" if you want to step to the following case. If you put the switch inside a loop, the continue is relative to the switch and not the loop. So if you want to continue the loop you need a "continue LABEL;" where the LABEL if before the loop.

Bye,
bearophile



More information about the Digitalmars-d mailing list