archivo del paquete→ .shtukbase/packages/code-refactoring/checks/feature_envy.ts
checks/feature_envy.ts
36 líneas, 1.8 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // RF-R06 (Fowler, Feature Envy). A method that reaches into one parameter more than into its own object:
- // `p.x` at least `envyMin` times through at least `distinctMin` different members, and more than twice as often as `this.x` / `self.x`. Only methods
- // (TypeScript methods of a class, Python and Rust methods with self).
- import { type CheckDef, num, runCheck } from '../../code-lib/checks/lib/run.ts';
- import { body, functions } from '../../code-lib/checks/lib/units.ts';
- const count = (text: string, re: RegExp) => (text.match(re) ?? []).length;
- export const CHECK: CheckDef = {
- pkg: 'code-refactoring',
- rule: 'RF-R06',
- name: 'feature-envy',
- defaults: { envyMin: 8, distinctMin: 4 },
- scan(srcs, set) {
- const min = num(set.envyMin, 8);
- const out = [];
- for (const s of srcs)
- for (const f of functions(s)) {
- if (!f.hasSelf) continue;
- const b = body(s, f);
- const own = count(b, s.lang === 'ts' ? /\bthis\.[A-Za-z_$]/g : /\bself\.[A-Za-z_]/g);
- let top = { p: '', n: 0, kinds: 0 };
- for (const p of f.params) {
- if (!p) continue;
- const hits = b.match(new RegExp(`(?<![\\w$.])${p.replace(/\$/g, '\\$')}\\.[A-Za-z_$][\\w$]*`, 'g')) ?? [];
- if (hits.length > top.n) top = { p, n: hits.length, kinds: new Set(hits).size };
- }
- // a value used through two or three members (a range, a point) is not envy: it takes `distinctMin` members
- if (top.n >= min && top.n > 2 * own && top.kinds >= num(set.distinctMin, 4))
- out.push({ rel: s.rel, line: f.line, msg: `the method ${f.name} reaches into ${top.p} ${top.n} times, into its own object ${own}: move the method (or a part of it) to where the data is` });
- }
- return out;
- },
- };
- if (import.meta.main) runCheck(CHECK);