DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. JavaScript
  4. Validating Arguments in JavaScript Like a Boss

Validating Arguments in JavaScript Like a Boss

In this post, a senior dev shows how to use an open source library he created to simplify argument validation in JavaScript.

Dmitry Sheiko user avatar by
Dmitry Sheiko
·
May. 28, 19 · Tutorial
Like (2)
Save
Tweet
Share
17.46K Views

Join the DZone community and get the full member experience.

Join For Free

In software engineering, we try to discover and eliminate bugs as soon as possible. One of most important heuristics here is validation of input/output on functions and methods. If you are going with TypeScript or Flow, you are fine. But if not? Then we have to manually validate at least the input (arguments). But what would be the best way of doing this?

The first thing that comes to mind is the aproba library. It's "ridiculously" light-weight and equally popular:

import validate from "aproba";
function click( selector, x, y ) {
  validate( "SNN", arguments );
}

Simple, isn't it? For constraints we give a string where each character stands for a corresponding argument. So here we require the  selector to be a string ("S") and both coordinates to be numbers ("N").

But when it comes to optional arguments it gets quite obscure. For example, the Node.js function fs.createWriteStream(path[, options]) maintainers of aproba recommend describing this as SO|SS|OO|OS|S|O

First, it's not that easy to read and second we do not validate the structure of options, any object is considered valid.

Such limitations made me to come up with an alternative — byContract. It is based on a similar principle, but instead of single-character signature it expects JSDoc expressions.

So the function from above can validated like this:

import { validate, typedef } from "bycontract";

function createWriteStream( path, options ) {
  validate( arguments, ["string|Buffer", "string|WriteStreamOptions#" ]);
}

Meaning, we state that  path can be a string or an instance of Buffer and options can be a string or an object of the WriteStreamOptions type or missing (note the # at the end of the signature). Here WriteStreamOptions is a custom type representing write stream options. We can define it as follows:

typedef( "WriteStreamOptions", {
  flags: "string#",
  encoding: "string#",
  fd: "number#",
  mode: "number#",
  autoClose: "boolean#",
  start: "number#"
});

I find it quite neat already, but can we do better? As a diligent developer you probably provide your functions with JSDoc. Why not to simply reuse it? Examine how you can do it with byContract:

import { validateJsdoc, typedef } from "bycontract";

class Fs {
  @validateJsdoc(`
  /**
   * @param {string|Buffer} path
   * @param {string|WriteStreamOptions} options
   * @returns {<WriteStream>}
   */
  `)
  createWriteStream() {

  }
}

With validate in byContract you can validate either a list of arguments against a list of constraints or a single value against a single constraint. The function always returns the incoming value(s). That can be used, for example, for exit point validation:

function pdf() {
//...
return validate( returnValue, "Promise" );
}

What if a function accepts different combinations of argument types? Let's say we have a  compare function that takes either two strings or two arrays of strings. We just need to use validateCombo:

import { validateCombo } from "bycontract";
function compare( a, b ) {
  const CASE1 = [ "string", "string" ],
        CASE1 = [ "string[]", "string[]" ];
  validateCombo( arguments, [ CASE1, CASE2 ] );
}

But personally I like taking advantage of it when validting React.js action creators. Let's say we define constraints in a separate module:

/interface/index.js

export const GROUP_REF = { 
  id: "string" 
};
export const ENTITY = {
 editing: "boolean=", 
 disabled: "boolean="
};
export const GROUP = {
 title: "string=",
 tests: "*[]",
 ...GROUP_REF
};

Now we can reuse them in actions:

import { validate } from "bycontract";
import * as I from "interface";
 export const addGroup = ( data, ref = null ) => ({
  type: constants.ADD_GROUP,
  payload: {
    data: validate( data, { ...I.ENTITY, ...I.GROUP } ),
    ref: validate( ref, I.GROUP_REF )
  }
});

As you can see, I combined the abstract entity and group constraints { ...I.ENTITY, ...I.GROUP }. Thus, when I need to validate another entity subclass I can do this { ...I.ENTITY, ...I.TEST } or this { ...I.ENTITY, ...I.COMMAND }.

Recap

byContract covers literally all of my needs for argument validation. It's not that concise as aproba, but much more flexible and powerful.

One doesn't need to learn a new constraint syntax given you know already JSDoc. It's fast enough, but still can be turned off for production builds.

The library can be used as ES module, with Node.js, and as none-module in a browser.

Strings JavaScript IT Data Types Node.js Library entity Object (computer science) Creator (software)

Published at DZone with permission of Dmitry Sheiko, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Important Takeaways for PostgreSQL Indexes
  • Use AWS Controllers for Kubernetes To Deploy a Serverless Data Processing Solution With SQS, Lambda, and DynamoDB
  • ClickHouse: A Blazingly Fast DBMS With Full SQL Join Support
  • Introduction to NoSQL Database

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: