Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function trim (str) {
if (typeof str !== 'string') { throw new Error('Invalid argument type'); }
// do trimming
return str;
}
@millermedeiros

This comment has been minimized.

Copy link

millermedeiros commented Aug 5, 2014

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

This comment has been minimized.

Copy link

millermedeiros commented Aug 5, 2014

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

This comment has been minimized.

Copy link

millermedeiros commented Aug 5, 2014

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
You can’t perform that action at this time.