In Java, I check my preconditions using Google Guava:
public Port getPublishedPort(Port port) {
checkArgument(port.isPublishedPort(), "Given port %s is not a published port.", port);
Is there an equivalent to this in JavaScript?
The method checkArgument of the Preconditions class ensures the truthfulness of the parameters passed to the calling method. This method accepts a boolean condition and throws an IllegalArgumentException when the condition is false.
A precondition is a condition that must be true for your method code to work, for example the assumption that the parameters have values and are not null. The methods could check for these preconditions, but they do not have to. The precondition is what the method expects in order to do its job properly.
The Node.js Preconditions Library is billed as having a Guava-like API for precondition checks.
Support for Guava like Precondition error checking in Node.js
new InstanceValidator(port).checkArgument(
"publishedPort", "Given port %s is not a published port.", [port]);
I authored Requirements.js. Usage looks like this:
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);
}
}
The primary focus is on the readability. Here is what the output looks like:
RangeError: age must be in range [18, 30).
Actual: 15
I welcome your feedback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With