(Updated: 1999.07.11 10:01:43 AM)
| |
You can measure the complexity of a function or method in the following way.
Start with 1 point for the existence of the function/method
Add 1 for every time a new variable is used.
Add 1 for every decision point like IF, CASE, OR, AND, IIF, FOR, WHILE, SCAN, INLIST etc.
The sum is the complexity of the function or method.
To calculate the complexity of classes add the scores for each method and add 1 for every property.
Routines with a complexity of less than 25 are unlikely to contain bugs and if they do they are typically easy to fix. This is in part because less complex routines are easy to understand, easy to prove correct or test and easy to debug.
Routines with a complexity level greater than 100 are much more likely to contain bugs. This is because they are harder to understand, test and debug.
Example:
PROCEDURE DisplayMessage && Score 1
LPARAMETERS tuName, tcMessage && Score 2
LOCAL lcName, lcMessage && Score 2
IF VARTYPE(tcMessage) = 'C' && Score 1
lcMessage = tcMessage
ELSE && Score 1
lcMessage = 'Hi there:'
ENDIF
DO CASE
CASE VARTYPE(tuName) = 'N' && Score 1
lcName = LookUpName(tuName)
CASE VARTYPE(tuName) = 'C' && Score 1
lcName = tuName
OTHERWISE && Score 1
lcName = 'Stranger'
ENDCASE
WAIT WINDOW lcMessage + ' ' + lcName
RETURN
So this procedure would score a total of 10
For more information about measuring complexity search the web on the following two systems:
- McCabe's Cyclomatic number
This is the system Andrew is using and is descibed in Code Complete.
- Halstead's Software Science
Counts using the number of operands and operators, both the total count and the unique count.
One thing I want to include in my measuments are the number of comments per lines of code. However I am not sure yet how to count this, proberbally lines of code / number of comments.
Maurice De Beijer
This concept of measuring complexity is valuable but the final "measurement" is one that grows with time. To this end, you might want to download this snippet of code (
CNTCODE.PRG) Pass it a piece of code to read (I routinely pass it _CLIPTEXT!) and it will tell you how complex your code is. The first lines of code allow you to define how your "complexity" measurement are (defined as EXCELLENT_SCORE and GOOD_SCORE).
I first ran into this in Chapter 16 of
Code Complete by
Steve McConnell.
Andrew MacNeill
CNTCODE.PRG - FWIW, has a readability index of 7, Consider Simpilfying. :-)
That's why I like Maurice's scale of 25 or less being good!
Score 18, pretty good. I never give excellent on an automated score, not very often in any other case either for that matter :-)
Category Testing