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.