ShtukbaseStandard
包文件→ .shtukbase/packages/code-refactoring/checks/feature_envy.ts

checks/feature_envy.ts

36 行, 1.8 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // RF-R06 (Fowler, Feature Envy). A method that reaches into one parameter more than into its own object:
  2. // `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
  3. // (TypeScript methods of a class, Python and Rust methods with self).
  4. import { type CheckDef, num, runCheck } from '../../code-lib/checks/lib/run.ts';
  5. import { body, functions } from '../../code-lib/checks/lib/units.ts';
  6. const count = (text: string, re: RegExp) => (text.match(re) ?? []).length;
  7. export const CHECK: CheckDef = {
  8. pkg: 'code-refactoring',
  9. rule: 'RF-R06',
  10. name: 'feature-envy',
  11. defaults: { envyMin: 8, distinctMin: 4 },
  12. scan(srcs, set) {
  13. const min = num(set.envyMin, 8);
  14. const out = [];
  15. for (const s of srcs)
  16. for (const f of functions(s)) {
  17. if (!f.hasSelf) continue;
  18. const b = body(s, f);
  19. const own = count(b, s.lang === 'ts' ? /\bthis\.[A-Za-z_$]/g : /\bself\.[A-Za-z_]/g);
  20. let top = { p: '', n: 0, kinds: 0 };
  21. for (const p of f.params) {
  22. if (!p) continue;
  23. const hits = b.match(new RegExp(`(?<![\\w$.])${p.replace(/\$/g, '\\$')}\\.[A-Za-z_$][\\w$]*`, 'g')) ?? [];
  24. if (hits.length > top.n) top = { p, n: hits.length, kinds: new Set(hits).size };
  25. }
  26. // a value used through two or three members (a range, a point) is not envy: it takes `distinctMin` members
  27. if (top.n >= min && top.n > 2 * own && top.kinds >= num(set.distinctMin, 4))
  28. 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` });
  29. }
  30. return out;
  31. },
  32. };
  33. if (import.meta.main) runCheck(CHECK);