0

I want to fix This function's cyclomatic complexity is too high messages and stumble on a simple function which contains only a switch statement. The function's cyclomatic complexity was calculated to (5) (W074).

Configuration.prototype.loadAndParseDataFromStorageFilename = function(cmd) {
    var jsonData;

    var ext = path.extname(cmd.argumentDatasource.filename).toLowerCase();
    var rawData  = fs.readFileSync(cmd.argumentDatasource.filename).toString().replace(/\n/g, "").replace(/\r/g, "");
    switch(ext) {
        case ".config":
            jsonData = xml.parseString(rawData);
            break;
        case ".xml":
            jsonData = xml.parseString(rawData);
            break;
        case ".json":
            jsonData = JSON.parse(cmd.argumentDatasource.filename);
            break;
        case ".js":
            jsonData = require(cmd.argumentDatasource.filename);
            break;
        default:
            var msg = colors.bgRed.white(cmd.argumentDatasource.filename + " not supported as data storage");
            console.log(msg);
    }
    return jsonData;
};

How is the cyclomatic complexity computed to 5 in this simple case? So far if have not idea to reduce complexity for a switch. For my understanding I would calculate the complexity to max. 3 or 4 :). What is the best practice to code a method with contains only a switch statement? It seems like codacy.com sets maxcomplexity to 4 or 3.

Stephan Ahlf
  • 3,310
  • 5
  • 39
  • 68

2 Answers2

1

There are 5 paths that the function can take and therefore has a cyclomatic complexity of 5

0

Just rewrote my code. So as far I can see we should avoid switch commands to code in best practice?

Configuration.prototype.loadAndParseDataFromStorageFilename = function(cmd) {
    var jsonData;

    var ext = path.extname(cmd.argumentDatasource.filename).toLowerCase().replace(/\./g,"");
    var parserFunction = {
        config : xml.parseString,
        xml : xml.parseString,
        json : JSON.parse,
        js : require
    };

    if (parserFunction[ext]){
        var rawData  = fs.readFileSync(cmd.argumentDatasource.filename).toString().replace(/\n/g, "").replace(/\r/g, "");
        jsonData = parserFunction[ext](rawData);
    } else {
        var msg = colors.bgRed.white(cmd.argumentDatasource.filename + " not supported as data storage");
        console.log(msg);
    }

    return jsonData;
};
Stephan Ahlf
  • 3,310
  • 5
  • 39
  • 68