-
Notifications
You must be signed in to change notification settings - Fork 30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Create rule S7172 Named methods should be used to avoid confusion between testing an optional or an expected and testing the wrapped value CPP-5929 #4545
Open
github-actions
wants to merge
8
commits into
master
Choose a base branch
from
rule/add-RSPEC-S7172
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e597990
Create rule S7172
AlexandreMessmer 152b649
First draft of the rule description
loic-joly-sonarsource bcf51a8
Merge branch 'master' into rule/add-RSPEC-S7172
loic-joly-sonarsource be4040e
Better asciidoc syntax
loic-joly-sonarsource 1180856
Add link to S6023
loic-joly-sonarsource fa77788
Apply review suggestions
loic-joly-sonarsource 3e8152b
Mark quickfix as infeasible. A basic fix would be possible, but a cle…
loic-joly-sonarsource f376942
Add introduction
loic-joly-sonarsource File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
{ | ||
"title": "Named methods should be used to avoid confusion between testing an optional or an expected and testing the wrapped value", | ||
"type": "CODE_SMELL", | ||
"status": "ready", | ||
"remediation": { | ||
"func": "Constant\/Issue", | ||
"constantCost": "10min" | ||
}, | ||
"tags": ["confusing" | ||
], | ||
"defaultSeverity": "Major", | ||
"ruleSpecification": "RSPEC-7172", | ||
"sqKey": "S7172", | ||
"scope": "All", | ||
"defaultQualityProfiles": ["Sonar way"], | ||
"quickfix": "infeasible", | ||
"code": { | ||
"impacts": { | ||
"MAINTAINABILITY": "HIGH" | ||
}, | ||
"attribute": "CLEAR" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
|
||
== Why is this an issue? | ||
|
||
`std::optional`, `boost::optional`, and `std::expected` are types that allow to represent a contained value of a certain type, and additional data that denote the absence of a value (`nullopt` for `optional`, and error values for `expected`). To check if the wrapper contains a value, it is possible to call its member function `has_value()`. Alternatively, it can also be converted to `bool`, which is more concise, especially when used in a place that allows _contextual conversion to bool_ (for instance, the condition of an `if`). It means that the following syntax is valid: | ||
|
||
[source,cpp] | ||
---- | ||
std::optional<bool> flag; | ||
if(flag) { ... } | ||
// Equivalent to | ||
if(flag.has_value()) { ... } | ||
---- | ||
|
||
When the contained type is also convertible to `bool`, using this concise syntax can be confusing. What is tested: The wrapper, or the contained value? | ||
|
||
This rule raises an issue when `std::optional`, `boost::optional`, or `std::expected` wrap a basic type, and the conversion to `bool` is used to test presence of the value. | ||
|
||
=== What is the potential impact? | ||
|
||
There are two possibilities, depending on the initial intent of the autor of the code: | ||
|
||
- If the intent was actually to test the presence of the value, the code is correct, but it is not clear. When reading it, people might think that the contained value is tested, and not the presence of the value. | ||
|
||
- If the intent was to test the contained value, the code is incorrect. This situation can especially happen when evolving code that worked directly with values to work with optional or expected values, and forgetting to update the test. This will lead to code that does not behave in the intended way, but still works in a plausible way, and the lack of clear clue on what is tested makes finding the issue difficult. | ||
|
||
=== Exceptions | ||
|
||
If, in a single expression, the presence of the value is tested and the value is accessed, the risk of confusion is reduced, and no violation is raised. | ||
|
||
[source,cpp] | ||
---- | ||
std::optional<bool> flag; | ||
if(flag && *flag) { ... } // Compliant | ||
---- | ||
|
||
== How to fix it | ||
|
||
The most direct way to fix this issue is to replace the concise syntax with a more verbose call to `has_value()`. However, both syntaxes leads to a code that is full of `if`/`else` and becomes difficult to read, especially if the program works with many `optional` or `expected` values. | ||
|
||
In many circumstances, it is possible to write code in a more direct way, using member functions such as `value_or()` or, starting with {cpp}23, the monadic interface of `optional` and `expected` (`and_then()`, `transform()` and `or_else()`), which are especially convenient when chaining operations on those types. | ||
|
||
|
||
//== How to fix it in FRAMEWORK NAME | ||
|
||
=== Code examples | ||
|
||
[source,cpp,diff-id=2,diff-type=compliant] | ||
|
||
==== Noncompliant code example | ||
|
||
[source,cpp] | ||
---- | ||
void perform(Node node, optional<bool> recursive, Action action) { | ||
action(node); | ||
bool recurse; | ||
if (recursive) { | ||
recurse = *recursive; | ||
} else { | ||
recurse = getDefaultRecurseMode(); | ||
} | ||
if (recurse) { | ||
// perform recursion... | ||
} | ||
} | ||
---- | ||
|
||
==== Compliant solution | ||
|
||
The most direct solution is to replace the concise syntax by the more explicit one. | ||
|
||
[source,cpp] | ||
---- | ||
void perform(Node node, optional<bool> recursive, Action action) { | ||
action(node); | ||
bool recurse; | ||
if (recursive.has_value()) { | ||
recurse = recursive.value(); | ||
} else { | ||
recurse = getDefaultRecurseMode(); | ||
} | ||
if (recurse) { | ||
// perform recursion... | ||
} | ||
} | ||
---- | ||
|
||
Since the rule will not trigger if the value is accessed in the same expression where its presence is tested, another possibility if the following: | ||
|
||
[source,cpp] | ||
---- | ||
void perform(Node node, optional<bool> recursive, Action action) { | ||
action(node); | ||
bool recurse = recursive ? *recursive : getDefaultRecurseMode(); | ||
if (recurse) { | ||
// perform recursion... | ||
} | ||
} | ||
---- | ||
|
||
In this simple case, the use of both `recursive` and `++*recursive++` hints that recursive is more than a simple `bool`. However, it is possible to write the code with a higher level semantic (see S6023): | ||
|
||
[source,cpp] | ||
---- | ||
void perform(Node node, optional<bool> recursive, Action action) { | ||
action(node); | ||
bool recurse = recursive.value_or(getDefaultRecurseMode()); | ||
if (recurse) { | ||
// perform recursion... | ||
} | ||
} | ||
---- | ||
The downside of this version is that `getDefaultRecurseMode()` is called even if `recursive` contains a value. If `getDefaultRecurseMode()` is a complex function, it can be a performance issue. In this case, it is possible to use the monadic interface of `optional`, at the cost of a more complex syntax: | ||
|
||
[source,cpp] | ||
---- | ||
void perform(optional<bool> recursive) { | ||
bool recurse = recursive.or_else([]() { return optional {getDefaultRecurseMode()};}).value(); | ||
if (recurse) { | ||
// perform recursion... | ||
} | ||
} | ||
---- | ||
|
||
This syntax is more complex, but it is also more flexible, especially when chaining operations on `optional` or `expected` values. | ||
|
||
== Resources | ||
|
||
=== Related rules | ||
|
||
* S6023 - "std::optional" member function "value_or" should be used | ||
|
||
=== Documentation | ||
|
||
* {cpp} reference - https://en.cppreference.com/w/cpp/utility/optional[`std::optional`] | ||
* {cpp} reference - https://en.cppreference.com/w/cpp/utility/expected[`std::expected`] | ||
* {cpp} reference - https://en.cppreference.com/w/cpp/utility/optional[`std::optional`] | ||
|
||
=== Articles & blog posts | ||
|
||
* Microsoft Developper Blog - * https://devblogs.microsoft.com/oldnewthing/20211004-00/?p=105754[Some lesser-known powers of std::optional] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
{ | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would add a line here:
In SonarLint it is just displayed below the title and before the tabs, saying while this is an issue. So it is good place, to give tldr of the rule
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
See for example here: https://rules.sonarsource.com/cpp/RSPEC-7127/?search=array