21-22. Code Smells

Process

  1. Sniff
  2. Prioritise and evaluate
  3. Refactor:
    • Split
    • Join
    • Move
    • Extract
    • Rename
    • etc.

How large is large?

Morphology

Fan-out:

Fan-in:

Method Length

Metrics:

Long methods a problem because:

How long is too long? Use:

Object-Oriented Metrics

Chidamber & Kemerer suite commonly used:

Large Class Smell

Knows too much, does too much; violating single responsibility principle

i.e. a God class

Break into smaller cohesive classes: extract class, extract interface

Long Parameter Lists

Solutions:

Duplicated Code

Want a single place of truth.

Solution: extract it into a method

Message Chains

bla.getSubProperty().getSubProperty()...

Bad because:

Law of Demeter: only talk to immediate friends.

Method m() of object o should only invoke methods of:

Dead/Unreachable/Deactivated/Commented Code

Dead code:

Unreachable code:

Deactivated code:

Commented code:

Switch Statements

Large switch/if statements:

Solutions:

Can leave it alone if it just performs some simple actions

Comments

Solution:

Names

Type Embedded in Name

Found mostly in old code. e.g. strFirstName

What happens if type is changed? Decisions should be hidden.

Uncommunicative Names

Should be descriptive, succinct, and have consistent names.

Speculative Generality

When you make general solutions because you speculate/anticipate what you might need in the future: do not speculate about tomorrow’s problems.

YAGNI, so don’t over-engineer your solution.

But at the same time, need to balance this with planning or extensibility.

Solutions:

Inappropriate Intimacy

How much does a class need to know about another? Ideally little; low coupling is preferable.

Solutions:

Indecent Exposure

Feature Envy

Method making extensive use of another class (e.g. envious of their methods and which they had them).

Cohesive elements should be in the same module/class.

Shotgun Surgery

When making a change requires splattering lots of small changes across a large swath of the system; changes should be localized.

This probably means the single responsibility principal has been violated.

Solutions:

Test Smells

Hard to test code:

Obscure tests:

Production bugs:

High maintenance:

Fragile tests:

Erratic tests: