I’m just wondering – is it bad programming style to create functions (decomposition) for relatively simple task?
For example, in PHP I find it annoying to have the ‘$_’ and then capital letters for session, post, get, and cookies. So if I made a function called setSesVar(‘key’, ‘value’) that would create a session variable for me, is that bad? And is the overhead of calling a function for it each time worth it? Or is it irrelevant/own preference?
Some other examples:
- printLn function in c++ (and java)
- shorthand form of getElementBydId in Javascript (assuming I don’t use jQuery or another library)
- redirect in place of header(‘Location: ‘ . url) in PHP
And a slightly off topic question – I’m use to languages with more ‘strict’ arrays; in PHP you can add an element to the end buy just saying myArray[] = ‘newElement’. I feel like I should do myArray[sizeof(myArray)] but I bet it’s probably bad style to add unessesary code.
Depends on what the functions do, and how much you’re doing this. If you take everything and make a one-line function out of it, then you haven’t really gotten rid of any complexity. In fact, you’ve added complexity, in two ways:
First, anything that’s not built into PHP is something someone new to your code has to figure out. If i see
$_SESSION['stuff'] = "some value";, i know what it’s doing — as does anyone who’s spent more than an hour with PHP. On the other hand, if i seesetSessionVar('stuff', 'some value');, i have to go and make sure of whatsetSessionVardoes. I mean, it’s got to be doing something more than just setting something in$_SESSION; otherwise, why not just do that?Second, if these functions end up calling each other, you end up with a rats’ nest of function calls. It’s easier to follow a 10- (or even a 30-) line function than to trace through a 2-line function that calls this other 2-line function that calls this whole other 2-line function that might or might not call another 2-line function. You’d have to yoyo through the file (or worse, tab between a bunch of different files) in order to trace your way through the code.
In my opinion, anything that’s built into PHP — and can be expressed in one simple line of code — does not deserve its own function. I’d suggest limiting functions to at least 3 lines, with one exception: methods that require access to an object’s internals, like getters or setters for example, can be smaller. But most functions should do something that PHP doesn’t already trivially do; if they don’t, then you’re defeating the purpose of functions and adding complexity for no good reason.