HN2new | past | comments | ask | show | jobs | submitlogin

I think shortcuts like the following are fundamentally flawed, at least when dealing with user input.

  If (user && user.name) { ...
While it sucks to have to even check for user etc, not checking that it’s truthy, then an object, then checking that the name is the correct type also during runtime, will cause bugs over time.

This type of developer provided shorthand validation is pretty much the cause of all hacks/data breaches currently. It’s more of an attitude or how a developer prioritizes their own wants/needs over maybe a client/end user. Like I mentioned in another comment, checking for more advanced, abusive behavior will make issues with type checking seem basic in comparison.



Yes. That's why a good language makes this explicit in the type.

For example in Scala, this example would be that user is of type Option[User] and the name property would also be Option[String] for example.

Then to safely get the name would be:

user.flatMap(_.name)

and the resulting type would be Option[String]

Which would then carry on the info that you don't know for certain that you know the name.


Will be nice when JS gets the Elvis operator and you’ll be able to do ‘if (typeof user?.name === “string”)’ which will have the added value of type narrowing/interaction with ‘never’ if name is expected to be something else.


I'd say the elvis operator would make things worse, especially wrt the parent post.

The problem isn't that `user && user.username` style validation is verbose, but that it's very error-prone. Making it less verbose just means you'll more likely use it before you reach for a better validation strategy, like a declarative validation library.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: