60 lines
2.2 KiB
Markdown
60 lines
2.2 KiB
Markdown
# Extending PMD
|
|
|
|
Use XPath to define a new rule for PMD to prevent complex code. The rule should detect the use of three or more nested `if` statements in Java programs so it can detect patterns like the following:
|
|
|
|
```Java
|
|
if (...) {
|
|
...
|
|
if (...) {
|
|
...
|
|
if (...) {
|
|
....
|
|
}
|
|
}
|
|
|
|
}
|
|
```
|
|
Notice that the nested `if`s may not be direct children of the outer `if`s. They may be written, for example, inside a `for` loop or any other statement.
|
|
Write below the XML definition of your rule.
|
|
|
|
You can find more information on extending PMD in the following link: https://pmd.github.io/latest/pmd_userdocs_extending_writing_rules_intro.html, as well as help for using `pmd-designer` [here](https://gitlab2.istic.univ-rennes1.fr/VV-2025-2026/VV-ISTIC-TP2/-/blob/main/exercises/designer-help.md).
|
|
|
|
Use your rule with different projects and describe you findings below. See the [instructions](../sujet.md) for suggestions on the projects to use.
|
|
|
|
## Answer
|
|
|
|
|
|
|
|
```xml
|
|
<?xml version="1.0" encoding="UTF-8"?>
|
|
<ruleset name="Nested If Ruleset"
|
|
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
|
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
|
<description>
|
|
Ruleset pour détecter 3 niveaux (ou plus) de if imbriqués.
|
|
</description>
|
|
<rule name="nestedIfRule"
|
|
language="java"
|
|
message="nested If"
|
|
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
|
|
<description>
|
|
Three or more nested `if` !
|
|
</description>
|
|
<priority>3</priority>
|
|
<properties>
|
|
<property
|
|
name="xpath"
|
|
value =" //IfStatement[
|
|
descendant::IfStatement[
|
|
descendant::IfStatement
|
|
]
|
|
]"
|
|
/>
|
|
</properties>
|
|
</rule>
|
|
</ruleset>
|
|
```
|
|
|
|
en testant un programme Java, il détecte bien les imbrications de 'if' même s'ils ne sont pas directement imbriqués, séparés par un while par exemple
|