Originally published at: http://www.sitepoint.com/functional-wrappers-sass/
I am not a big fan of having global variables all over the place, no matter the language. In Sass, as in CSS, we have nothing but a global namespace (although latest Sass versions progressively provide more scoping features). It’s like a house with a single room: no matter how hard you try to organize your furniturs, at the end of the day there is still only a single room in the house.
What’s the problem with this? When it comes to Sass, the problem is that variables can overlap. What if you have a variable called
$baseline, and a Sass grid framework you use have a
$baseline variable as well? Or worst, what if a Sass library you included uses a
$_ variable to hold private content required for it to work and you happen to override it yourself with your own stuff? Simple: it breaks.
Coming back to my initial point: I am not a big fan of having variables to configure a Sass system. I shall be more precise and say “having only variables” because, of course, variables are the key when it comes to store data. Meanwhile, it has occurred to me that functional wrappers help a lot.
You could think of function wrappers as getters and setters in a way that they are functions wrapping a variable declaration or retrieving to add some extra features on top of it: validation, error handling, default values, warnings, and so on.
Isn’t it a pain to do this?, you say. It depends. There is something beautiful in a variable: its simplicity. A variable is obvious: it is a value mapped to a storage key. How could it get any simpler than this? Yet, I think raw variables are not best suited to handle things like library configurations and such.
Actually the choice is yours: either you have a function wrapper that handles everything from the very start (errors, parameter validation, default values…), or you make all of this in every functions and mixins you’ve got. I’ll play clear: I’d rather go the former.