Skip to content

Commit

Permalink
Add more to docs on prefer-some-in-iteration
Browse files Browse the repository at this point in the history
This is one of the most visited docs pages, so filling in some blanks
and adding some links to relevant content.

Signed-off-by: Anders Eknert <anders@styra.com>
  • Loading branch information
anderseknert committed Jun 18, 2024
1 parent 1191c41 commit 6e69043
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions docs/rules/style/prefer-some-in-iteration.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,30 @@ Or is `other_rule` a map-generating rule, and we're checking for the existence o
elsewhere in the code. Using `some .. in` removes this ambiguity, and makes the intent clear without having to jump
around in the policy.

Improved readability is not the only benefit of using `some .. in`. The `some` keyword ensures that the bindings
following the keyword are bound to the local scope, and modifications outside of e.g. a rule body won't affect how the
variables are evaluated. Consider the following simplified example to iterate over the keys of a map:

```rego
package policy
key_traversal if {
map[key]
# do something with key
}
key_traversal if {
some key in object.keys(map)
# do something with key
}
```

The two rules above are equivalent in that they both bind the variable `key` to the keys of `map`. The first
example would however change behavior entirely if a rule named `key` was introduced in the package, as the expression
would then mean "does map have key `key`?". While this isn't common, using `some .. in` means one less thing to worry
about.

## Exceptions

Deeply nested iteration is often easier to read using the more compact form.
Expand Down Expand Up @@ -116,6 +140,8 @@ rules:
- Rego Style Guide: [Prefer some .. in for iteration](https://github.com/StyraInc/rego-style-guide#prefer-some--in-for-iteration)
- Regal Docs: [Use `some` to declare output variables](https://docs.styra.com/regal/rules/idiomatic/use-some-for-output-vars)
- OPA Docs: [Membership and Iteration: `in`](https://www.openpolicyagent.org/docs/latest/policy-language/#membership-and-iteration-in)
- OPA Docs: [Some Keyword](https://www.openpolicyagent.org/docs/latest/policy-language/#some-keyword)

## Community

Expand Down

0 comments on commit 6e69043

Please sign in to comment.