Software Engineering

Code Smells

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Code Smell

  • Code smells [Fowler, Beck]
  • Actual term used
  • Indicates the need for a refactoring
  • Typically based on developer intuition
  • We will look at a few examples

Primitive Obsession

Primitive Obsession

Use of primitive types when an object is needed, e.g., array, Money, Data, etc.

  • Hinders: comprehension, reuse
  • Main Refactoring: Replace Data Value with Object, Replace Type Code with {Class, Subclasses, State/Strategy}
  • For many fields: Extract Class
  • For many parameters: Introduce Parameter Object
  • For arrays: Replace Array with Object

Primitive Obsession

Long Parameter Lists

  • Difficult to use a call or get parameters in the correct order
  • Difficult to read and interpret what the call does
  • Has boolean parameters
  • Has optional, null parameters

Long Parameter Lists

Too many parameters

  • Functionality is wrong, or not enough use of fields
  • Hinders: comprehension, use, adding parameters
  • Main Refactoring: Replace Parameter with Method, Preserve Whole Object, Introduce Parameter Object

Data Clumps

Data Clumps

Bunches of data that always hang around together

  • Hinders: comprehension, reuse
  • For fields: Extract Class
  • For method signatures: Introduce Parameter Object, Preserve Whole Object


Switch Statements

Most switch statements should be replaced by polymorphism

  • Hinders: comprehension, reuse
  • Secondary Refactorings: Extract Method, Move Method
  • Main Refactorings: Replace Type Code with {Subclasses, State/Strategy}, Replace Conditional with Polymorphism
  • When polymorphism is overkill: Replace Parameter with Explicit Methods
  • Case is Null: Introduce Null Object

Ref: Replace Type Code with Subclasses