簡體   English   中英

手動鍵入檢查和測試函數參數的好習慣?

[英]Good practice to manually type check and test for function arguments?

我在創建項目時應用了 TDD,並且我正在對我的函數進行大量測試和檢查,以確保正確輸入它們的參數。

我對此沒有任何問題,但是我的代碼開始因所有參數檢查而顯得擁擠。 這是正確的做法還是通常沒有像這樣實施參數檢查?

export default class Ship {
  constructor(shipLength) {
    if (typeof shipLength !== 'number') throw new Error('Length must be a number');
    if (arguments.length !== 1) throw new Error('Must enter only 1 argument');
    if (shipLength < 1) throw new Error('Length must be greater than 0');
    if (shipLength % 1) throw new Error('Length must be an integer');
    
    this.length = shipLength;
    this.hits = Array(this.length).fill(false);
  }

  hit(location) {
    if (typeof location !== 'number') throw new Error('Must be a number');
    if (arguments.length !== 1) throw new Error('Can only accept one argument')
    if (location > this.length - 1) throw new Error('Must be within ship body');
    if (location < 0) throw new Error('Cant be negative');
    if (location % 1) throw new Error('Must be an integer');
  
    this.hits[location] = true;
  }
}
import Ship from "../src/ship";

describe('Test that the constructor', () => {
  it('accepts only one parameter of type number', () => {
    expect(() => new Ship(3)).not.toThrow();
    expect(() => new Ship(1,2,3)).toThrow();
    expect(() => new Ship([1,2,3])).toThrow();
    expect(() => new Ship('asd')).toThrow();
  });
  it('doesnt take < 1 as length', () => {
    expect(() => new Ship(0)).toThrow();
    expect(() => new Ship(-1)).toThrow();
  });
  it('only accepts integers', () => {
    expect(() => new Ship(1.1)).toThrow();
  });
  it('sets the passed ship length', () => {
    expect(new Ship(3).length).toBe(3);
  });
  it('creates a hit array', () => {
    expect(new Ship(3).hits).toEqual([false, false, false]);
  })
});

您應該對用戶提供的值進行運行時驗證。 因為這些只出現在運行時,並且它們中的錯誤必須在運行時處理。 對在代碼內部傳遞的值執行此操作通常是多余的。 因為雖然這些錯誤會在運行時出現,但您無法在運行時對它們做任何事情; 您需要通過修復代碼來修復它們。 因此,運行時檢查這些值可能會幫助您發現代碼中的錯誤,但代價是代碼非常復雜; 如果您的代碼沒有碰巧采用該特定路徑,甚至不能保證輕松幫助您發現這些錯誤。

有助於在開發時發現這些類型的錯誤的是像TypeScript這樣的靜態類型檢查器。 使用它通常比這些運行時類型檢查更有意義。

您可以使用有助於解決此問題的庫,例如is.js

is.number(值:任意)

is.number(42);
=> true

is.alphanumeric(值:任意)

is.all.alphaNumeric('alphaNu3er1k', '*?');
=> false

ETC..

不要看代碼是否不堪重負是一個好習慣,如果它只導致安全的代碼運行而沒有錯誤

編輯:當然,您可以使用某種庫,但是這樣您就可以訪問您檢查的內容以及檢查方式,這使得以后在必要時更容易修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM