iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 14
1
Software Development

為什麼世界需要Typescript系列 第 14

消滅多個if 的方法 - 14

  • 分享至 

  • twitterImage
  •  

提前return

下面是一個if else 的範例

function checkBalance(customer: Customer, amount: number): boolean {
   let account = customer.getAccount();
   if( account != null ) {
      if( account.balance >= amount ) {
         return true;
      } else {
         return false;
      }
   }
   return false;
}

上面程式碼可以透過 提前return 方法來避免 巢狀if 的問題

function checkBalance(customer: Customer, amount: number): boolean {
   let account = customer.getAccount();
   if( account == null ) {
      return false;
   }
   
   if( account.balance >= amount ) {
      return true;
   } else {
      return false;
   }
   return false;
}

接著再用 boolean 表達式消滅下面的 if else

function checkBalance(customer: Customer, amount: number): boolean {
   let account = customer.getAccount();
   if( account == null ) {
      return false;
   }
   return (account.balance >= amount);
}

用Dictionary 替代 if else

之前的書店折扣實作程式碼原本如下

class Bookstore {
   getPrice(books: number): number {
      if( books == 2 ) {
         return 190;
      }
      if( books == 3 ) {
         return 270;
      }
      if( books == 4 ) {
         return 320;
      }
      if( books == 5 ) {
         return 375;
      }
      if( books >= 6 ) {
         return books * 100 * 0.75;
      }
      return 100;
   }
}

需求是買 N 本書, 有相對應的折扣(%), 所以我們可以把 books 數量當作key, 把折扣(%)當作 value. 首先建立一個字典.

discountDict: {[books: number]: number} = {
   1: 1,
   2: 0.95,
   3: 0.9,
   4: 0.8,
   5: 0.75,
};

如果要更清楚描述說明那個 "字典的value" 的意義, 我們可以在前面宣告 Percentage

type Percentage = number;
class Bookstore {
   private _discountDict: {[books: number]: Percentage} = {
      1: 1,
      2: 0.95,
      3: 0.9,
      4: 0.8,
      5: 0.75,
   };
}

然後在 getPrice 實作方法內容中, 內容會變成如下

getPrice(books: number): number {
   let discount = this._discountDict[books];
   if( books > 5 ) {
      return books * 100 * this._discountDict[5]; 
   }
   return books * 100 * discount;
}

甚麼!? 你看到重複的程式碼!?

books * 100

你會你來, 把它重構(Refactor)一下, 再跑測試吧!

物件多型 替代 if else

物件多型(polymorphism), 就是不同資料類型的實體提供統一的介面. 以上面的書店例子, 1本書的折扣是0, 2本書的折扣是5%, 3本書的折扣是10% , 我們把1本書, 2本書, 3本書... 當作物件, 這些物件有統一相同的行為, 就是 "打折扣" 的行為, 這就是多型.

所以我們要改成物件多型的話, 要準備一個統一相同的行為的動作, 想要統一相同物件的話, 我們可以用下面幾個方法解決

  • 抽象類別 abstract class
  • 介面 interface

用抽象類別(abstract class) 方法, 就得先寫一個基本抽象類別, 每一個新物件就繼承(inheritance) 這個基本抽象類別, 然後再覆寫(override) 基本抽象類別中的方法(function).

用介面方法(interface) 方法, 就得先寫一個介面(interface), 每一個新物件就實作(implements) 這個介面, 然後再實作(implements) 介面中的方法(function).


上一篇
參數化測試 - 13
下一篇
利用抽象類別取代if else - 15
系列文
為什麼世界需要Typescript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言