Skip to content
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

Add more to docs on prefer-some-in-iteration #851

Merged
merged 1 commit into from
Jun 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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