繁体   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