Skip to content

Commit

Permalink
Add more to docs on prefer-some-in-iteration (#851)
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 <[email protected]>
  • Loading branch information
anderseknert committed Jun 19, 2024
1 parent 7bf1c93 commit e9a2ab6
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]

This comment has been minimized.

Copy link
@srenatus

srenatus Jun 19, 2024

Member
some key
map[key]

would do the same, right? should we mention that?

This comment has been minimized.

Copy link
@anderseknert

anderseknert Jun 19, 2024

Author Member

Yeah, I intended to keep this isolated from https://docs.styra.com/regal/rules/idiomatic/use-some-for-output-vars
But it's perhaps better to show all three alternatives. Will follow up with a fix.

# 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 e9a2ab6

Please sign in to comment.