Why use named groups only to never use any of them later on in the code?
This rule raises issues every time named groups are:
- defined but never called anywhere in the code through their name;
- defined but called elsewhere in the code by their number instead;
- referenced while not defined.
Noncompliant Code Example
const date = "01/02";
const datePattern = /(?<month>\d{2})\/(?<year>\d{2})/;
const dateMatched = date.match(datePattern);
if (dateMatched !== null) {
checkValidity(dateMatched[1], dateMatched[2]); // Noncompliant - numbers instead of names of groups are used
checkValidity(dateMatched.groups.day); // Noncompliant - there is no group called "day"
}
// ...
const score = "14:1";
const scorePattern = /(?<player1>\d+):(?<player2>\d+)/; // Noncompliant - named groups are never used
const scoreMatched = score.match(scorePattern);
if (scoreMatched !== null) {
checkScore(score);
}
Compliant Solution
const date = "01/02";
const datePattern = /(?<month>\d{2})\/(?<year>\d{2})/;
const dateMatched = date.match(datePattern);
if (dateMatched !== null) {
checkValidity(dateMatched.groups.month, dateMatched.groups.year);
}
// ...
const score = "14:1";
const scorePattern = /(?<player1>\d+):(?<player2>\d+)/;
const scoreMatched = score.match(scorePattern);
if (scoreMatched !== null) {
checkScore(scoreMatched.groups.player1);
checkScore(scoreMatched.groups.player2);
}