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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Use State Inside of an Effect Component With ngrx
  • Generics in Java and Their Implementation
  • JavaScript Type Conversion and Coercion
  • JSON-Based Serialized LOB Pattern

Trending

  • Data Quality: A Novel Perspective for 2025
  • Unlocking AI Coding Assistants: Generate Unit Tests
  • Agile’s Quarter-Century Crisis
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  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.

By 
Dmitry Sheiko user avatar
Dmitry Sheiko
·
May. 28, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
19.2K 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.

Related

  • How to Use State Inside of an Effect Component With ngrx
  • Generics in Java and Their Implementation
  • JavaScript Type Conversion and Coercion
  • JSON-Based Serialized LOB Pattern

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: