5 tips to make your PHP code beautiful (3)
Avoid unnecessary control structures.
Brackets everywhere. Try to get rid of those as much as you can. Unnecessary brackets add visual complexity and make your code much longer. In real world situation, when you need to quickly browse through your code, they just add clutter
//prints out the structure of a table
function describe( $table )
{
$query = "SHOW COLUMNS FROM `$table `";
$result =mysql_query( $query );
if ( ! $result )
{
return $result;
} else {
$data = array();
while ( $record = mysql_fetch_assoc( $result ) )
{
$data[] = $record;
}
return $data;
}
}
In the function above the if-else structure is not needed, just because when $result is false I can just return it, breaking the flow. Also while ( $record = ..) uses brackets for looping over just one statement.
We can make describe() look much more tidy:
function describe( $table )
{
$query = "SHOW COLUMNS FROM `$table `";
$result =mysql_query( $query );
if ( ! $result ) return $result;
$data = array();
while ( $record = mysql_fetch_assoc( $result ) ) $data[] = $record;
return $data;
}
Seems nicer, uh ? While one could think that’s just a detail, when code complexity grows, this kind of tricks can help you cutting it down.
