-
Notifications
You must be signed in to change notification settings - Fork 414
/
negated_is_nil.ex
67 lines (52 loc) · 1.76 KB
/
negated_is_nil.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
defmodule Credo.Check.Refactor.NegatedIsNil do
use Credo.Check,
base_priority: :low,
tags: [:controversial],
explanations: [
check: """
We should avoid negating the `is_nil` predicate function.
For example, the code here ...
def fun(%{external_id: external_id, id: id}) when not is_nil(external_id) do
# ...
end
... can be refactored to look like this:
def fun(%{external_id: nil, id: id}) do
# ...
end
def fun(%{external_id: external_id, id: id}) do
# ...
end
... or even better, can match on what you were expecting on the first place:
def fun(%{external_id: external_id, id: id}) when is_binary(external_id) do
# ...
end
def fun(%{external_id: nil, id: id}) do
# ...
end
def fun(%{external_id: external_id, id: id}) do
# ...
end
Similar to negating `unless` blocks, the reason for this check is not
technical, but a human one. If we can use the positive, more direct and human
friendly case, we should.
"""
]
@doc false
@impl true
def run(%SourceFile{} = source_file, params \\ []) do
issue_meta = IssueMeta.for(source_file, params)
Credo.Code.prewalk(source_file, &traverse(&1, &2, issue_meta))
end
defp traverse({:when, meta, [_, {negation, _, [{:is_nil, _, _}]}]} = ast, issues, issue_meta)
when negation in [:!, :not] do
issue =
format_issue(
issue_meta,
message: "Negated is_nil in guard clause found",
trigger: "when !/not is_nil",
line_no: meta[:line]
)
{ast, [issue | issues]}
end
defp traverse(ast, issues, _), do: {ast, issues}
end