Skip to content

Commit 0e1a5d3

Browse files
committed
More improvements to anti-pattern
1 parent 1b1bbf1 commit 0e1a5d3

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

lib/elixir/pages/anti-patterns/code-anti-patterns.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,9 @@ There are few known exceptions to this anti-pattern:
375375

376376
#### Problem
377377

378-
In Elixir, it is possible to access values from `Map`s, which are key-value data structures, either statically or dynamically. When a key is expected to exist in the map, it must be accessed using the `map.key` notation, which asserts the key exists. If `map[:key]` is used and the informed key does not exist, `nil` is returned. This return can be confusing and does not allow developers to conclude whether the key is non-existent in the map or just has a bound `nil` value. In this way, this anti-pattern may cause bugs in the code.
378+
In Elixir, it is possible to access values from `Map`s, which are key-value data structures, either statically or dynamically. When a key is expected to exist in the map, it must be accessed using the `map.key` notation, which asserts the key exists. If the key does not exist, an exception is raised (and in some situations also compiler warnings), allowing developers to catch bugs early on.
379+
380+
`map[:key]` must be used with optional keys. This way, if the informed key does not exist, `nil` is returned. When used with required keys, this return can be confusing and allow `nil` values to pass through the system, while `map.key` would raise upfront. In this way, this anti-pattern may cause bugs in the code.
379381

380382
#### Example
381383

@@ -432,7 +434,9 @@ iex> Graphics.plot(point_3d)
432434
{5, 6, nil}
433435
```
434436

435-
As shown below, another alternative to refactor this anti-pattern is to use pattern matching:
437+
Overall, the usage of `map.key` and `map[:key]` encode important information about your data structure, allowing developers to be clear about their intent. See both `Map` and `Access` module documentation for more information and examples.
438+
439+
Another alternative to refactor this anti-pattern is to use pattern matching:
436440

437441
```elixir
438442
defmodule Graphics do

0 commit comments

Comments
 (0)