Should we validate function parameters?

Asked

Viewed 660 times

29

In languages like Java, method parameters are "validated" in the build (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, it is recommended to validate the entry to avoid problems?

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

This becomes 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
  • Performance of impaired application

Nevertheless this may avoid some problems.

How far to go with this input validation story? Is there any more interesting alternative?

  • I think you would like to meet http://www.typescriptlang.org/

  • @Pauloroberto I have heard but never used. Have you used? It is difficult to integrate with existing code?

  • 3

    Really??? Write code to validate types in a dynamic language??? I die and don’t see everything. Your question makes it seem that you have received or seen this kind of recommendation. Can you pass the source? I would like to understand the reasoning of this.

  • 5

    @Caffé I did not receive this recommendation from anyone, but me I constantly wonder whether it is good practice to make these validations or not. I would like to hear more about your opinion about validations not being required.

3 answers

19


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

Polluted code

I would not call pollution something that is useful. Pollution is unnecessary thing. Whether you choose to facilitate code maintenance, usage by others or by yourself in the future. If you want to give better information to debug, information in the right place is critical.

In fact this code is actually quite simple, if it’s not, it’s doing something wrong. It’s very fast to encode this. This tiny amount of time will be compensating the first time you debug.

Exception

I don’t know if the solution is to use one throw. But some treatment may be interesting. The use of exceptions is not part of the Javascript culture. It is usually used in more obvious situations where there is a gain doing so. I don’t 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 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 the exception in other languages is used to solve any kind of problem, so programmers don’t really understand the various types of problems.

On the other hand if you don’t know what to do, if you treat the problem wrong, don’t add relevant information, you will add useless code.

Performance of impaired application

First of all this will make very little difference. We’re talking about Javascript, a language that wasn’t meant to perform as well as possible.

And second, 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 have measured and seen that there are problems, that something is running slower than is acceptable.

This is not a reason to avoid such verification.

Alternative view

But that depends a lot on how you and your team work. If you have a proper 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 whole call stack to understand where the problem originated.

Some people prefer to do this in functions considered "library" and not in the application functions.

The smaller the team and the application you are running, the less the need for these checks (which I wouldn’t call validation since this is a programming problem and not data entry).

Alternative forms

Unit tests

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

Alternative language

You can use some other language that compiles for Javascript and has type checking at compile time. An example is Typescript.

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

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

Completion

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

Recommend my other answer on the subject in that reply.

  • 1

    I don’t really see people validating Javascript input, so I don’t know which would be the best practice or the most used. Initially throw it seemed to me the most natural, now I realized that it is even exaggeration.

10

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

You have listed two points that you consider negative and have listed no benefits.

In Javascript, throwing an exception for the type of parameter not expected is no different than letting the code pop if you can’t handle this difference. Google Chrome dev tools, for example, are great and solve all the debugging and problem identification challenges in Javascript code - you won’t depend on these additional validations.

Also, will the type of the parameter really be incompatible with the code of the method? Javascript makes a series of implicit conversions.

The Typescript offers a slightly different programming paradigm and compiles for Javascript your code written in this other paradigm. The difference between this framework and the validation you suggested is that in this framework typing becomes explicit, rather than 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 suitable to solve what you propose and that it is not limited but, on the contrary, by having fewer restrictions, it is very powerful.

  • Thanks for your opinion! I think I need to rethink this, maybe validate only in "extreme cases"

  • 3

    @user18612 Now you’ve reached the point I didn’t even write in my answer! Validate when you know why you’re doing this, in a specific method, by a clear need.

5

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

So there are some tools to help staff to validate data, such as the Typescript for example.

However, you can implement a validation by yourself, just as you did in your question, it is reasonable, can give work at first, but once all your functions are validated correctly, implement new functions and validate the parameters will not be a problem.

Since I had said that javascript is a weak typing language, it is very free so that you can work the way you want, many things that you can’t do in several languages in javascript you can (not that this is there those things) because depending on how you write the code may end up getting lost in the middle of this freedom and all become literally one zone and this is the most known disadvantage of javascript.

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

Should or should not validate the function parameters I create in javascript?

Will, but adding my opinion, I would say that yes it is worth validating for those who have time and availability for it, after all the big problem is always it, the time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.