Replace Magic Number with Symbolic Constant

From CSSEMediaWiki
Jump to: navigation, search

Any time that a number is hard coded into the text, it should be replaced by a constant value for that class.

Example

public int power10(int num) {
 int result = 1;
 for(int i = 0; i < 10; i++) {
  result *= num;
 }
 return result;
}

Refactors into:

private static final int powerNum = 10;
 ...
public int power10(int num) {
 int result = 1;
 for(int i = 0; i < powerNum; i++) {
  result *= num;
 }
 return result;
}

Arguably the 0 and 1 magic numbers should also be refactored.

See Also:


Refactoring

Composing Methods: Extract Method | Inline Method | Inline Temp | Replace Temp with Query | Introduce Explaining Variable | Split Temporary Variable | Remove assignments to Parameters | Replace Method with Method Object | Substitute Algorithm
Moving Features Between Objects: Move Method | Move Field | Extract Class | Inline Class | Hide Delegate | Remove Middle Man | Introduce Foreign Method | Introduce Local Extension
Organising Data: Self Encapsulate Field | Replace Data Value with Object | Change Value to Reference | Change Reference to Value | Replace Array with Object | Duplicate Observed Data | Change Unidirectional Association to Bidirectional | Change Bidirectional Association to Unidirectional | Replace Magic Number with Symbolic Constant | Encapsulate Field | Encapsulate Collection | Replace Type Code with Class | Replace Type Code with Subclass | Replace Type Code with State/Strategy
Simplifying Conditional Expressions: Decompose Conditional | Consolidate Conditional Expression | Consolidate Duplicate Conditional Fragments | Remove Control Flag | Replace Nested Conditional with Guard Clauses | Replace Conditional with Polymorphism | Introduce Null Object | Introduce Assertion
Making Method Calls Simpler: Rename Method | Add Parameter | Remove Parameter | Separate Query from Modifier | Parameterise Method | Replace Parameter with Explicit Methods | Preserve Whole Object | Replace Parameter with Method | Introduce Parameter Object | Replace Parameter Object | Remove Setting Method | Hide Method | Replace Constructor with Factory Method | Encapsulate Downcast | Replace Error Code with Exception | Replace Exception with test
Dealing with Generalisation: Pull Up Field | Pull Up Method | Pull Up Constructor Body | Push Down Field | Push Down Method | Extract Subclass | Extract Superclass | Extract Interface | Collapse Hierarchy | Form Template Method | Replace Inheritance with Delegation
Big Refactorings: Tease Apart Inheritance | Convert Procedural Design to Objects | Separate Domain from Presentation | Extract Hierarchy

Personal tools