What is Halstead Metric
Halstead Metric is a Complexity measure that introduced by Maurice Howard Halstead. The goal of this metric is to quantify and identify measurable properties of software, and relation between them. This metrics determine quantitative measure of complexity directly from it’s operators and operands.
How to Calculate Halstead Metric
Halstead metric is based on interpreting the source code as a sequence of tokens and classifying each token to be an operator or an operand. These are the following measure that can be collected :
n1 = Number of distinct operators.
n2 = Number of distinct operands.
N1 = Number of total operator instances
N2 = Number of total operand instances.
After collecting those measures it can be used to calculate :
Program Length (N) - Sum of the total number of operator and operands.
Halstead Vocabulary (n) - Total number of unique operator and unique operand occurrences.
Program Volume (V) - Describe the size of implementation of an algorithm. This computed by the number of operations performed and operands handled in the algorithm. Measured in mathematical bits.
Difficulty (D) - The difficulty or error proneness of a program is proportional to the number of unique operators in the program. D is also proportional to the ration between the number of operands and the number of unique operands (if a same operands are used many times, the program might more prone to errors)
Level (L) - Inverse of the error proneness of the program. a low level program is more prone to errors than a high level program.
Effort (E) - The effort to implement (E) or understand a program is proportional to the volume and to the difficulty level of the program.
Time to Program (T) - Time to implement or understand a program, is proportional to the effort.
Where
S = 18
Estimated Bugs (B)
The number of estimated bugs (B) this correlates with overall complexity of the software, and is an estimate for the number of errors in the implementation.
Example
PHP
public function destroy() {
$session = array('user_id', 'user_login', 'user');
$this->session->unset_userdata($session);
$this->session->set_flashdata('warning','Anda berhasil logout!');
redirect(site_url('indonesia'));
}
Operators | Occurrences | Operands | Occurrences |
---|---|---|---|
public | 1 | destroy | 1 |
function | 1 | $session | 2 |
() | 6 | string constants | 6 |
array | 1 | unset_userdata | 1 |
$this | 2 | set_flashdata | 1 |
{} | 1 | redirect | 1 |
= | 1 | site_url | 1 |
, | 3 | session | 2 |
-> | 4 | - | - |
; | 4 | - | - |