Created
June 28, 2016 15:22
-
-
Save jacopotarantino/d5c51e9cfa3a16d7613b1a6a0d9184a1 to your computer and use it in GitHub Desktop.
Example of reducing cyclomatic complexity for more maintainable code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this function is highly complex. it has a cyclomatic complexity rating of 7. | |
// it's performance is fine but it's very difficult to read and maintain. | |
// rating generated by this quick tool: http://jshint.com/ | |
function do_something (config) { | |
if (config.prop1) { | |
if (config.prop2) { | |
if (foo === bar) { | |
blah() | |
} | |
} | |
} else { | |
if (config.prop3) { | |
if (config.prop4) { | |
if (foo === bar) { | |
blah() | |
} | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this function is not very complex. it has a complexity rating of 4. | |
// moving if statements into null-checks where possible reduces both the complexity and the number of nested blocks. | |
// i prefer to write null-checks with a comment describing what they do because negating a value tends to make it less easy to interpret. | |
function do_something_better (config) { | |
// don't do this if this prop isn't passed in correctly. | |
if (typeof config.prop1 === 'string') { return; } | |
// don't do this if this prop isn't passed in correctly. | |
if (!config.prop2) { return; } | |
// don't do this if this prop isn't passed in correctly. | |
if (foo !== bar) { return; } | |
blah() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment