Code-Refactor-Part1

anonymous·2021년 12월 3일
0

Bad Code Labels

Bloaters

Long Method

  • If you feel the need to comment on something inside the method, you probably should take this code and put it into a new method.

Problem

  • Long method
void printOwing() {
  printBanner();

  // Print details.
  System.out.println("name: " + name);
  System.out.println("amount: " + getOutstanding());
}

Solution

  • Extract Method
// Replace oldcode with a call to the method
void printOwing() {
  printBanner();
  printDetails(getOutstanding());
}

void printDetails(double outstanding) {
  System.out.println("name: " + name);
  System.out.println("amount: " + outstanding);
}

Problem

  • Long method
double calculateTotal() {
  double basePrice = quantity * itemPrice;
  if (basePrice > 1000) {
    return basePrice * 0.95;
  }
  else {
    return basePrice * 0.98;
  }
}

Solution

  • Replace Temp with Query
double calculateTotal() {
  if (basePrice() > 1000) {
    return basePrice() * 0.95;
  }
  else {
    return basePrice() * 0.98;
  }
}
double basePrice() {
  return quantity * itemPrice;
}

Problem

  • Complex Conditional
if (date.before(SUMMER_START) || date.after(SUMMER_END)) {
  charge = quantity * winterRate + winterServiceCharge;
}
else {
  charge = quantity * summerRate;
}

Solution

  • Decompose Conditional (into
if (isSummer(date)) {
  charge = summerCharge(quantity);
}
else {
  charge = winterCharge(quantity);
}

Large Class

  • Bloated class

Problem

  • one class two functions

Solution

  • Extract Class : (Be Situational about this)

Problem

  • Class has features used only in certain cases

Solution

  • Extract Subclass :Create subclass and use it in different cases

Problem

  • Multiple clients are using same part of class interface. Part of interface in two classes is the same.

Solution

  • Extract Interface : Move the identitcal portion to its own interface

REF

https://refactoring.guru/smells

profile
기술블로거입니다

0개의 댓글