I have the a function that loads a list of things from a database and put them into a select list. The function is as follows : (pseudocode)
protected function Foo()
{
try {
get pdo instance
prepare statement
if (pdo query executes)
{
while (row = fetched rows)
{
do stuff with row
}
}
}
catch (PDOException $ex)
{
do error stuff here
}
}
NetBeans gives a code hint that it is too many lines and too many nested blocks. I personally feel that the function should be acceptable. I also feel that to break the logic up into smaller functions is bit looney, but why would netbeans lie to me:) ?
so my questions are as follows:
Is this bad logic or am I good to go ahead? I would welcome any suggestions on how I might redesign the function to fit within the NetBean constraints.
edit:
I won't answer my own question but in this case there was one nested block that was not needed. The pdo is retrieved from a singleton class that has the try/catch block. I dont need to repeat it again in this function because the exception would of already been caught.
edit 2:
Removing the try catch block was just like robbing Peter to pay Paul. So if the exception is thrown in the creation of the pdo instance it does not stop execution. Thus, we try call the prepare statement on a PDO object that was not initialized correctly. This forces us to put in another test before the prepare call, thus just returning to a rework of the original function.
In my experience, this means somewhere along the line my logic is floored. I am going to go over my design and holla back if i have anything worthy to say.
Thanks again to all
Your code is good. What NetBeans suggests is not necessarily a rule you should follow and you wouldn't even have worried if you used some other editor like PHPStorm (In PHPStorm, you can set coding style to follow PSR 1/2).
You could at least do away with one nesting by using something called guard clause:
protected function Foo()
{
try {
get pdo instance
prepare statement
if (! pdo query executes) return;
while (row = fetched rows)
{
do stuff with row
}
}
catch (PDOException $ex)
{
do error stuff here
}
}
I have seen people having different preferences since there is no hard and fast rule. For example Anthony Ferrara personally thinks he should not go beyond four nested levels where I personally think four levels are too much.
Point is you should minimize nesting and number of lines as much as you can. When your method is too big (sometimes called god method), it means you are doing it wrong.
You may also want to look at this nice article by William Durand on the subject where he discuss few (actually 9) proposals suggested by Jeff Bay in his book ThoughtWorks Anthology
Also PHP Coding Standards Fixer is your friend.
So: