Should we validate function parameters?


In languages like Java, the method parameters are "validated" in the compilation (at least the type):

public void facaAlgo(String str) {
  // ...

// em algum outro lugar:
int i = 2;
this.facaAlgo(i); // erro de compilação!

In dynamic typing languages such as Javascript, is it recommended to validate input to avoid problems?

function facaAlgoComString(str) {
  if (typeof str !== 'string') {
    throw 'Está função só aceita string!';
  // restante da função

This gets more complex when working with objects and arrays:

function facaAlgo(aluno) {
  if(typeof aluno !== 'object' || typeof aluno.nome !== 'string' || !Array.isArray(aluno.notas)) {
    throw 'Parâmetro incorreto!';
  // ...

facaAlgo({nome: 'Fulano', notas: [10]}); // ok!

Among the problems of so many validations is:

  • Polluted code
  • Impaired application performance

However, this can avoid some problems.

How far do you go with this input validation story? Is there a more interesting alternative?

asked by anonymous 02.12.2014 / 12:46

3 answers


It depends on what you want. Want to have an organized code or just "work"? You can let the error happen at your end point. Or you can show before where the error actually occurred.


Polluted code

I would not call pollution something that is useful. Pollution is unnecessary. If you choose to make it easier for you to maintain the code, use it for others, or use it for yourself in the future. If you want to give better information to debug, the information in the correct place is fundamental.

Actually this code is very simple, if it is not, you are doing something wrong. It is very quick to code this. This meager time-out will compensate the first time you debug.


I do not know if the solution is to use throw . But some treatment may be interesting. Exceptions are not part of the JavaScript culture. It is usually used in more obvious situations where there is a gain doing this way. I do not know if this is changing or will change with increasingly complex applications but the fact is that this feature is not used as it is used in other languages.

And maybe it's a good thing since most programmers use it the wrong way. In this case I do not know if it is for an exception since we are talking about a programming error. The ideal thing is to do something that helps the programmer find and understand the error more easily. Exception is not the best mechanism for this. I even understand this confusion since exception in other languages is used to solve any kind of problem, so the programmers do not really understand the various types of problems.

On the other hand if you do not know what to do, if you treat the problem in the wrong way, do not add relevant information, it will add useless code anyway.


Impaired Application Performance

First, this will make very little difference. We're talking about JavaScript, a language that was not meant to have the best performance possible.

And second, we go back to the previous item, what is best for your code? What will make your life easier? Even in other languages performance should only be a concern when you measured and saw that there are problems, that something is running slower than is acceptable.

This is not a reason to avoid this kind of verification.

Alternative view

But that depends a lot on how you and your team usually work. If you have an adequate workflow and tools, this may not be so necessary. Most of the time what you will lose is a better location of the problem. You may have to check the entire call stack to understand where the problem originated.

Some people prefer to do this in "library" functions rather than in application functions.

The smaller the team and the application you are doing, the smaller the need for these checks (which I would not call validation since this is a programming problem and not an input problem).

Alternative forms

Unit tests

Other people will say that it is critical to do unit tests that do these checks for you. That is, verification is done but out of code.

Alternative language

You can use some other language that compiles for JavaScript and has compile-time type checking. An example is TypeScript .

In fact a language like TypeScript will bring many other advantages, especially if you use the tools available to encode it. Unlike other languages that try to run on top of JS, it behaves almost autonomously. I've never liked layers on top of JS but this case seems to me to be an exception. The advantages brought and the almost absence of disadvantages make them think about its use.

It would look something like this:

function facaAlgo(str : string) {
  // ...

// em algum outro lugar:
var i = 2; // tipo de i inferido como numérico
facaAlgo(i); // erro de compilação!


Anyway, it's more a matter of taste and adaptation to the working method. Test each form for a while and try to find the best alternative for you. I always prefer the language to do this for me. Then I look for tools outside of the code to help and only if none of that is good and is available I will see if I will put this type of verification in the code when the application is a bit more complex (which is not usually the case for JS applications for sites ).

Recommend my other response on the subject in this answer .

02.12.2014 / 13:04

My answer starts with a question: What benefits do you see in this practice?

You listed two negative points and did not list any benefits.

In JavaScript, throwing an exception by the type of the parameter is not as expected is no different than letting the code pop if you can not handle this difference. The Google Chrome dev tools, for example, are great and solve all the debugging and troubleshooting challenges in JavaScript code - you will not depend on these additional validations.

In addition, will the parameter type actually be incompatible with the method code? JavaScript does a series of implicit conversions .

TypeScript offers a slightly different programming paradigm and compiles your code written in this other paradigm to JavaScript. The difference between this framework and the validation you suggested is that in this framework the typing is explicit, instead of being laboriously validated by the programmer and hiding in the body of the method.

My suggestion: embrace the culture of the language you are using. You may find that your style is more appropriate to solve what is proposed and is not limited but, on the contrary, having less restrictions, is very powerful.

02.12.2014 / 13:39

In fact, what we should or should not do, it is up to us, programmers, but common sense tells us to make validations that we are sometimes not used to knowing Javascript is a weakly typed language.

So there are some tools to help data validation staff like TypeScript for example.

However, you can implement a validation by yourself, just as you did in your question, it's okay, it might give you some work in the beginning, but once all your functions are validated correctly, implementing new functions and validating the parameters will not be a problem.

As I said that javascript is a weak typed language, it's pretty free for you to work the way you please, many things you can not do in various languages in javascript you can (not that so depending on how you write the code you might end up getting lost in the middle of that freedom and everything will literally become a zone and this is the most well known disadvantage of javascript.

Well, knowing all this, it's up to you to make a decision:


Should I validate the function parameters that I create in javascript?

It's about you, but adding my opinion , I would say that yes is worth validating for who has the time and availability for it, after all the big problem is always him , the time .

02.12.2014 / 13:04