Skip to content

Instantly share code, notes, and snippets.

@Couto
Created August 5, 2014 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Couto/0ec37ef6eda55dd8bf71 to your computer and use it in GitHub Desktop.
Save Couto/0ec37ef6eda55dd8bf71 to your computer and use it in GitHub Desktop.
function trim (str) {
if (typeof str !== 'string') { throw new Error('Invalid argument type'); }
// do trimming
return str;
}
@millermedeiros
Copy link

you don't need to fail early in most cases. in fact for trimming (and all string methods) on MOUT I used a toString function to make sure it doesn't throw errors:

var trim = require('mout/string/trim');
console.log( trim({}) ); // "[object Object]"
console.log( trim(null) ); // ""

that allows us to pass any object that implements a toString method and avoids naive mistakes like passing null or undefined (and always expecting a string back).

I even implemented a safe upperCase and lowerCase methods just to avoid bureaucracy: http://moutjs.com/docs/latest/string.html#upperCase

nowadays when I need to make sure I have a string I just call toString.. if I need an array I call toArray, that simplified my code A LOT. I usually only throw errors for cases where there is really no easy way to recover.

PS: the likelihood of passing an object to trim is not so high, but the likelihood of passing a number or null or undefined is pretty high when data is coming from external sources.

@millermedeiros
Copy link

PS: notice that toNumber and toArray needs a lot of type checks.. the thing is, that by abstracting the checks into a few helper functions I avoid littering my code with type checks, I can simply use it as if data was always the way I want to. IMO the minority of the functions should have type checks, not saying that they aren't useful.

@millermedeiros
Copy link

PPS: my application code rarely have toNumber, toArray and toString calls, these are more useful for helpers/libraries since you never know how they will be called. For most cases you can just assume the proper data will be passed and if you receive the wrong kind of data it will throw errors automatically (undefined is not a function).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment