Can't add a method to a class you don't own? Use a Foreign Method!
- Create the method in YOUR code
- Pass the utility object as parameter
Example (JS):
function formatWithTimezone(date) {
return StringUtils.format(date) " UTC";
}
#ProgrammingTips#CodeRefactoring
Remove Middle Man:
When a class just delegates calls (adding no value):
- Delete the delegating methods
- Make clients call directly
Before:
manager.getEmployee().getName()
After:
employee.getName()
Cut the pointless proxy!
#CleanCode#Refactoring
Hide Delegate:
If clients access object B through object A, make A handle the call instead.
Before:
a.getB().doSomething()
After:
a.doSomething()
Reduces coupling! #CleanCode#OOP
Example:
user.getAddress().format() → user.formatAddress()
Extract Class:
When one class tries to do two jobs:
- Split into two classes
- Connect via reference
Before:
class User { saveToDB() {...} sendEmail() {...} }
After:
class User {} class EmailService {}
#SOLID#Refactoring
Move Field Refactoring:
- Add field to new class
- Redirect all old field access
- Delete old field
Keeps data where it’s used most! #CleanCode#Refactoring
Example:
user.address → profile.address
Move Method:
When a method is used more by another class than its own:
- Cut from source class
- Paste into target class
- Update references
Keeps behavior near its data! #OOP#Refactoring
Example:
user.getAddress() → address.format()
Never reassign parameters!
Use a local var instead.
Before:
function foo(x) { x = 2; }
After:
function foo(x) { const y = 2; }
#JavaScript#CodeSmells
Inline Temp Refactoring:
Replace a variable with its expression.
Before:
const discount = basePrice * 0.1;
return total - discount;
After:
return total - (basePrice * 0.1);
Make simple code!!
#CleanCode#Refactoring