Why is it a good idea to avoid nested blocks in a function? (PHP) -


i installed netbeans 7.4 beta, , there's new hint says "too many nested blocks in function declaration - it's practice introduce new function...".

i try avoid nested blocks within function better readability, there other reason why better "idea," php, if matters.

the formal name cyclomatic complexity.

this measure of how complex function is, based on number of 'decision points' in function. higher number, more complex function.

complexity determined number of decision points in method plus 1 method entry. decision points 'if', 'while', 'for', , 'case labels'. generally, 1-4 low complexity, 5-7 indicates moderate complexity, 8-10 high complexity, , 11+ high complexity.

(taken http://phpmd.org/rules/codesize.html)

the reason considered bad have complexity values high because makes function difficult test.

in order test function full potential, need have separate test each possible code path. number of code paths increases exponentially every new decision point, means time you've got more handful of decisions in single function, start needing hundreds of tests in order sure you've covered whole range of functionality might perform.

hundreds of tests single function many, better option reduce number of decision points per function splitting several smaller functions fewer decisions each.

you need make functions discrete don't rely on each other run. allows them tested in isolation each other. (otherwise still have original problem of many decisions in single call)

you can test each of functions handful of number of tests have required.

the process of testing functions in isolation of each other called unit testing. large topic in itself, worth researching if want know more software development practices.

since you've tagged question php, point in direction of few tools mgiht you:

  • php unit - de-facto standard unit testing package php.
  • phpmd - "php mess detector"; tool analysing code things excessive complexity.
  • pdepend - similar tool.

there bunch of other tools available, that's enough started; know ones first. you'll come across others naturally research topic.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -