PDA

View Full Version : How would or could I make this less?


student101
05-13-2008, 10:36 PM
How would or could I make this less code?
Is IF then ELSE maybe less?
It works out fine but interested to know if it's possible?
<?php
// get action based on query string...
//connect to the database ...
// validate1
switch ($action):
case 'validate1':
//database queries and checking
if ($num > 0) {
print "<font color=RED>bad</font>";
}else{
print "<font color=GREEN>good</font>";
}
}else{
print "<font color=RED>must be longer then x characters</font>";
}
break;

// validate2
switch ($action):
case 'validate2':
//database queries and checking
if ($num > 0) {
print "<font color=RED>bad</font>";
}else{
print "<font color=GREEN>good</font>";
}
}else{
print "<font color=RED>must be longer then x characters</font>";
}
break;

// this could go on and on
// validate3

default:
//I am the default switch, hi
endswitch;
?>

Cheers

pete
05-13-2008, 11:38 PM
It is difficult to say without knowing what you are trying to achieve, we need the bigger picture.

I see redundant code in the if/else statements, code blocks for validate 1 and validate 2 are identical so that would probably suggest you can create a function to handle the if/else, if you need 10 validate blocks you are just setting yourself up for a hard time when it comes to maintenance later down the line.

This is where experience comes in to play. The more real world sites you create the more experience you will have on how to manage your code and you begin to instinctively know where a class is needed, or a function or a design pattern. Many newbies also tend to make PHP do everything when it is often more sensible to use MySQL but that can be difficult when your MySQL knowledge is perhaps limited.

Also look at your output, please don't use <font color=RED> if you have to use inline styles then do <span style="color:#ff000"> but ideally you will use classes, the font tag is deprecated, read http://www.w3.org/TR/html401/present/graphics.html

You should also use single quotes around strings unless you require variable interpolation read http://hell.org.ua/Docs/oreilly/webprog/php/ch04_01.htm for a good summary of this.

student101
05-13-2008, 11:43 PM
Thanks I will look at those links, but I am so tired I can't think anymore.
Will have to resume this later, need sleep.

Cheers