简体   繁体   English

手动键入检查和测试函数参数的好习惯?

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

I'm applying TDD while creating my project, and I'm implementing a lot of tests and checks for my functions to ensure their arguments are correctly input.我在创建项目时应用了 TDD,并且我正在对我的函数进行大量测试和检查,以确保正确输入它们的参数。

I have no issue with this, but my code is starting to look congested with all the argument checks.我对此没有任何问题,但是我的代码开始因所有参数检查而显得拥挤。 Is this proper practice or is argument checking not generally implemented like this?这是正确的做法还是通常没有像这样实施参数检查?

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]);
  })
});

You should do runtime validation of user supplied values .您应该对用户提供的值进行运行时验证。 Because those only appear at runtime and errors in them must be handled at runtime.因为这些只出现在运行时,并且它们中的错误必须在运行时处理。 Doing this for values which are passed internally in your code is usually overkill.对在代码内部传递的值执行此操作通常是多余的。 Because while those errors will surface at runtime, you cannot do anything about them at runtime;因为虽然这些错误会在运行时出现,但您无法在运行时对它们做任何事情; you need to fix them by fixing your code.您需要通过修复代码来修复它们。 So runtime checks for those values might help you discover bugs in your code, but at the cost of very convoluted code;因此,运行时检查这些值可能会帮助您发现代码中的错误,但代价是代码非常复杂; and it's not even guaranteed to easily help you discover those bugs, if your code doesn't happen to take that particular path.如果您的代码没有碰巧采用该特定路径,甚至不能保证轻松帮助您发现这些错误。

What does help unearth these types of bugs at development time is a static type checker like TypeScript .有助于在开发时发现这些类型的错误的是像TypeScript这样的静态类型检查器。 Using it often makes more sense than these runtime type checks.使用它通常比这些运行时类型检查更有意义。

You can use a library that helps with this, for example is.js :您可以使用有助于解决此问题的库,例如is.js

is.number(value:any) is.number(值:任意)

is.number(42);
=> true

is.alphanumeric(value:any) is.alphanumeric(值:任意)

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

etc.. ETC..

Don't look at whether the code is overwhelmed is a good practice if it leads to safe code running without errors only不要看代码是否不堪重负是一个好习惯,如果它只导致安全的代码运行而没有错误

edit: sure, and you could use some kind of library, but this way you have access to what you check and how you check it, which makes it easier to modify later if necessary.编辑:当然,您可以使用某种库,但是这样您就可以访问您检查的内容以及检查方式,这使得以后在必要时更容易修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 好的做法是在箭头函数中使用name = arguments作为函数参数? - It is good practice to use name=arguments as function arguments in arrow functions? 从 javascript 中的参考文献中定义具有不同 arguments 列表的 function 是一种好习惯吗? - Is it good practice to define a function with different arguments list from reference in javascript? 如果函数始终具有相同的输入,将函数参数保留为空是一种好习惯吗? - Is it a good practice to leave function arguments empty, if the function always has the same input? 这种类型的 promise 嵌套是好习惯吗? - Is this type of promise nesting good practice? 使用this.argu存储参数是一个好习惯吗? - use this.argu to store arguments a good practice? .unbind().click(function() {...}) 是一个好习惯吗? - Is .unbind().click(function() {…}) a good practice? 如何确保类型检查 function 返回相同 arguments 的相同引用 - How to ensure type check a function returns the same reference for same arguments 覆盖函数参数值是一种好习惯吗? - Is it good practice to override function parameter value? 是在JS函数的“良好”实践中使用多次替换吗? - Is using multiple replaces in a JS function 'good' practice? CommonJS函数声明范围的良好实践 - CommonJS function declaration scope good practice
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM