I’m a beginner but I’ve written my first little project and something about it doesn’t really feel right. I hope I can describe the problem clearly.
My whole program is basically a pile of little functions that call each other, and then one or two lines of code that call the initial function to start off the ‘chain reaction’ and return the desired result.
It looks kind of like this (I’m using PHP):
$result = func_A($args);
function func_A($arg1, $arg2){
$localvar1 = blah blah;
$value = func_B($localvar1, $arg2);
return $value;
}
function func_B($arg1, $arg2){
$localvar1 = blah;
$value = func_C($localvar1, $arg2);
$return value;
}
function func_C($args){
blah blah blah
}
So when I try to go through my code, I’m hopping around all over the place between functions like crazy.
Is there a better way to do this? Should I just be creating local functions within my other functions? This just doesn’t feel quite right.
Overall this is fine. We’d need to know more about specific goals and what the code is doing to get into more detail. In general, keeping the nuts and bolts in functions and calling them from a sort of main “command” center is a fine approach to procedural programming.
However, some general high level rules that work for me:
Don’t repeat yourself. If you find you’re doing the same things over
and over again, make a function of that. If you load a value from a
file, calculate something with it, and echo that, make a function for
it.
Don’t overspecialize too far. Lots of 2 line functions probably
isn’t a good thing.
If you can, be general. Don’t make 5 different functions to connect
to 5 different databases. Make one function and pass the name of the
database to connect to it. See the rule about not repeating
yourself.
If you have one function that calls another that calls another, and
they are always used that way, consider making a single function of
them.
Objects are great for dealing with a set of values and doing things with them. For a quick script, not so much, but if you’re going to do some substantial work like validating data, storing it, reading it in, making it into a single string, that’s a good opportunity to make a class. Classes will conveniently fit into a file which you can then use in other projects as well, and if you do maintenance to this class often, the scripts that use it may not need to be changed at all if your initial design was solid.