在Java中,我使用Google Guava 检查我的前提条件:
public Port getPublishedPort(Port port) {
checkArgument(port.isPublishedPort(), "Given port %s is not a published port.", port);
Run Code Online (Sandbox Code Playgroud)
在JavaScript中是否有相同的功能?
我编写了Requirements.js。用法如下:
import {requireThat} from "@cowwoc/requirements/es6/node/DefaultRequirements.js"
class Player
{
constructor(name, age)
{
requireThat(name, "name").isNotNull().asString().length().isBetween(1, 30);
requireThat(age, "age").asNumber().isBetween(18, 30);
}
}
Run Code Online (Sandbox Code Playgroud)
主要关注点是可读性。输出如下所示:
RangeError: age must be in range [18, 30).
Actual: 15
Run Code Online (Sandbox Code Playgroud)
我欢迎您的反馈。
不,但你可以自己写:
var Preconditions = {
checkArgument: function(condition, message) {
if (!condition) {
throw Error('IllegalArgumentException: ' + (message || ''));
}
}
}
Run Code Online (Sandbox Code Playgroud)
并在你的业务逻辑中
function getPublishedPort(port) {
Preconditions.checkArgument(port.isPublishedPort(), 'Given port is not a published port.');
// ... Business logic ...
}
Run Code Online (Sandbox Code Playgroud)
虽然我猜它不能为你进行惰性评估的格式化。
| 归档时间: |
|
| 查看次数: |
1956 次 |
| 最近记录: |