Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metrics & Object-oriented programming

Tags:

oop

metrics

I would like to know if somebody often uses metrics to validate its code/design. As example, I think I will use:

  • number of lines per method (< 20)
  • number of variables per method (< 7)
  • number of paremeters per method (< 8)
  • number of methods per class (< 20)
  • number of field per class (< 20)
  • inheritance tree depth (< 6).
  • Lack of Cohesion in Methods

Most of these metrics are very simple.

What is your policy about this kind of mesure ? Do you use a tool to check their (e.g. NDepend) ?

like image 616
user12703 Avatar asked Dec 23 '22 14:12

user12703


2 Answers

Imposing numerical limits on those values (as you seem to imply with the numbers) is, in my opinion, not very good idea. The number of lines in a method could be very large if there is a significant switch statement, and yet the method is still simple and proper. The number of fields in a class can be appropriately very large if the fields are simple. And five levels of inheritance could be way too many, sometimes.

I think it is better to analyze the class cohesion (more is better) and coupling (less is better), but even then I am doubtful of the utility of such metrics. Experience is usually a better guide (though that is, admittedly, expensive).

like image 109
Jeffrey L Whitledge Avatar answered Jan 14 '23 17:01

Jeffrey L Whitledge


A metric I didn't see in your list is McCabe's Cyclomatic Complexity. It measures the complexity of a given function, and has a correlation with bugginess. E.g. high complexity scores for a function indicate: 1) It is likely to be a buggy function and 2) It is likely to be hard to fix properly (e.g. fixes will introduce their own bugs).

Ultimately, metrics are best used at a gross level -- like control charts. You look for points above and below the control limits to identify likely special cases, then you look at the details. For example a function with a high cyclomatic complexity may cause you to look at it, only to discover that it is appropriate because it a dispatcher method with a number of cases.

like image 24
torial Avatar answered Jan 14 '23 18:01

torial