Skip to content

Brute-force idioms: == True, an if/else that returns a boolean, index loops that only read xs[i], .filter(...).length > 0, indexOf(x) !== -1, x ? true : false, x ? x : y, .map().flat(), strings.Index(...) != -1, .len() == 0 ​

Code longer than it needs to be: one of the ways AI coding agents bloat software, from lessloc's pattern catalog. lessloc catches it as simpler, built in for Python, JS/TS, Go, Rust, Java and C#. ruff (in every hook) and clippy (in ci) go deeper.

What makes brute-force idioms a bad practice? ​

The standards that call it a bad practice: Sonar S1125, S1126, S1066, S1155; ESLint no-unneeded-ternary, no-lonely-if; typescript-eslint prefer-for-of, prefer-optional-chain; unicorn prefer-array-some, prefer-array-find, prefer-includes; PEP 8; ruff E712, SIM103; staticcheck S1002, S1003, S1008; clippy needless_bool, len_zero.

What does lessloc do about brute-force idioms? ​

lessloc catches it as simpler, built in for Python, JS/TS, Go, Rust, Java and C#. ruff (in every hook) and clippy (in ci) go deeper.

  • simpler (tier 2): Brute-force code with a shorter idiom: == True, an if/else that returns the condition, an index loop that only reads xs[i], .filter(...).length > 0, a catch that only rethrows, a flag loop that is any(), a hand-built counter, an __init__ that @dataclass writes, a React Effect that only sets state. ruff and clippy add more.

Examples ​

Caught as simpler:

ts
export const has = (xs: number[]) => xs.filter(x => x > 2).length > 0;
export const at = (xs: string[], x: string) => xs.indexOf(x) !== -1;
export const flag = (v: boolean) => (v ? true : false);

Written well:

ts
export const has = (xs: number[]) => xs.some(x => x > 2);
export const at = (xs: string[], x: string) => xs.includes(x);
export const flag = (v: boolean) => v;

Caught as simpler:

js
export function sum(xs) {
  let s = 0;
  for (let i = 0; i < xs.length; i++) {
    s += xs[i];
  }
  return s;
}

Written well:

js
export function sum(xs) {
  let s = 0;
  for (const x of xs) {
    s += x;
  }
  return s;
}

Caught as simpler:

js
export function isAdmin(u) {
  if (u.role === "admin") {
    return true;
  }
  return false;
}

Written well:

js
export function isAdmin(u) {
  return u.role === "admin";
}

Caught as simpler:

python
def names(users):
    out = []
    for i in range(len(users)):
        out.append(users[i].name)
    return out

Written well:

python
def names(users):
    return [u.name for u in users]

Caught as simpler:

go
package y

import "strings"

func Has(s, x string) bool {
	if strings.Index(s, x) != -1 {
		return true
	}
	return false
}

Written well:

go
package y

import "strings"

func Has(s, x string) bool {
	return strings.Contains(s, x)
}

The other patterns in Code longer than it needs to be:

Released under the Apache-2.0 license. · llms.txt