Almost seems like not talking could make you smarter.
Category: Uncategorized
How to make a single function call handle one or many
I was browsing through Ning’s codebase the other day. I work directly with the code since I’ve customized a Ning network for one of Cloudspace’s clients in some subtle ways, just because he wanted it that way.
I really like the work they’ve done. Their codebase clearly has a lot of best practices.
I found one neat trick that was used to make a function a bit more versatile, in that it can easily be passed a single object, or an array of objects, with no sweat. If you’re interested, you can find an example of this in /widgets/activity/models/ActivityLogItem.php, in beforeDelete()
This isn’t their code, but here’s an example of the trick.
function eatPie($pie_id) { foreach( (is_array($pie_id) ? $pie_id : array($pie_id)) as $current_id) { // codez } }
Really straightforward. If an array is passed in, each item in the array gets operated on. If a single item is passed in, it gets turned into an array, then each item in the array gets operated on. I also like how the tertiary statement gets used inline with the foreach. Of course, if you want a bit more code clarity, you can do it like this:
function eatPie($pie_id) { $pie_id = is_array($pie_id) ? $pie_id : array($pie_id); foreach($pie_id as $current_id) { // codez } }
Drawing diagrams
I sometimes forget just how useful drawing diagrams can be.
For example, working with a DB. Just a quick sketch of circles as tables, write the column titles inside the relevant circles, and then draw a few lines to represent joins.
It’d probably be useful to do this with large blocks of code too. Just draw parts of the code that matter, and abstract away the parts that don’t matter.