Welcome to WebmasterWorld Guest from 35.171.45.91

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

What coding style do you use and why?

     
2:38 am on Nov 13, 2009 (gmt 0)

Full Member

10+ Year Member

joined:June 1, 2007
posts:201
votes: 0


I just thought I would ask a simple question about your coding style. Why you use it? What made you pick it? and do you use other styles for other languages.

When I first started messing with PHP and hacking other scripts. I didn't even realize there was a style, let alone multiple styles to choose from when coding. I know choosing a style preference is up to the coder but knowing the different styles can help a person get around in another developers codebase more quickly.

I am relatively knew to PHP and programming in general and since I have no formal training, I had no idea about a lot of the basics. I still don't claim to know a lot but I have found that once I realized formating your code a certain way can help productivity and bug fixing I ended up choosing a style that worked for me.

I picked the PEAR coding style [pear.php.net...] I will admit I don't stick to it as strictly as it is written but pretty closely.

Another wikipedia article [en.wikipedia.org...]

5:00 pm on Nov 13, 2009 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:June 10, 2008
posts: 1130
votes: 0


You're bound to get reamed with this question. Your going to get hit with the OOP guys who think you need to objectify everything and the opposite "cowboy coders" who never use OOP. You need to know how to do both. There are times when OOP just makes sense and there are times when it just ends up creating more work. As far as formatting I can give you a few pointers.
1. documentation
It's a coders worst nightmare and no one likes to do it but get into the habit of doing it and you will save yourself in the long run. It never seems necessary when your coding because you know what every variable is for and what every method/object does. However, step away, even for a few months, and come back and you will wish you would have documented. Even simple things help. I know it seems like extra work but saying

//if we have an id then they
//are logged in otherwise
//they are not
if($id != null){

}
else{

}

Also, properly tab your code

if(condition 1){

if(condition 2){

if(condition 3){

}
else{

}
}

else{

}

}
else{

}

Lastly notice that if you put some code in that last section it may be hard to tell what brace is supposed to go where. If you have a lot of things like this and miss one brace, it could be a huge headache trying to figure it out. I found a good way around this get into the habit of commenting behind close braces. Even if its a single if statement, DO IT! Once you get into the habit you will thank yourself

Let's say you start with
if(condition 1){

}

and you don't comment it. Then later on you come in and add more ifs like my earlier example, it will be confusing if you miss a brace. However, if you do it from the get go

this
if(condition 1){

}//if condition 1

Turns into this
if(condition 1){

if(condition 2){

if(condition 3){

}//if condition 3
else{

}//else condition 3
}//if condition 2

else{

}//else condition 2

}//if condition 1
else{

}//else condition 1

It makes debugging much easier. Just my thoughts though. You have to program to a style that YOU are comfortable with.

9:12 pm on Nov 13, 2009 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
posts:7999
votes: 0


**Personally** there are several directives in programming style I adhere to, some I do not. The finer points - how you format the code


function foo () {
// code
}
function foo()
{
// code
}

Are just that, finer points and nowhere near as important as the one's I'll mention.

Chef Boyardee

One of the things I truly detest about PHP is that much of the code I find, and review, and try to untangle, is spaghetti code, a tangled mass of html mixed with dashes of PHP here and there throughout. The nature of PHP lends itself to this, and newcomers or lazy coders make it's ugly side shine brightest.

It's not so easy to do this in Perl - but it can be done, and is just as miserable.

<html><head><title><php?$title?></title></head><body>
<!-- block of 300 lines of HTML -->
include("some-file.php");
<!-- another block of 500 lines, with at least 50 instances of <php?$some_var?> peppered throughout -->
include("some-other-file.php");
</body>
</html>

It makes perfect sense to use an include for, say, a header and a footer. But scattered over 500 pages, this is more of a nightmare than updating 500 headers in static pages. The best solution in most cases is to review your code for redundant processes and functions, and compartmentalize them.

This does not always mean OOP. It just means if you build a screwdriver, don't build a new one to turn in a new screw. Use the one you already built. The above scenario is easy to resolve. One oversimplified example,

$my_page = get_flippin_template($page_title,$content);
echo $my_page;

'S OK M Nut Bzy M JS Drvn

Legibility and logic is paramount. In an effort to make clients come back to them, or prevent others from understanding (W.T.H.) they are thinking, or even just that they presume no one else will see it so it doesn't matter, coders often do this

$dfg = 'some value';
$abs = 1234;
$q = bl_func($abs);
echo "$dfg $q";

It's okay, we can figure it out. But it would be a lot easier if you did this.

$product_category = 'some value';
$prod_id = 1234;
$product_display = get_product_display($prod_id);
echo "$product_category $product_display";

Code here, output there.

One of the things you learn from Perl or many other languages is that a program's function and it's output are two separate things. In PHP, the exact opposite is true, it allows you to HTML and insert PHP willy nilly, any time you like, making for a mess of a source code. While I'm having fun describing this, this is perfectly fine because it's what PHP does - but in large programs, or even with output that is large, it's to your advantage to separate the two.

How many of you have seen a PHP page start to load, shoot half of it to the browser, think about it a bit while it performs some PHP function, then finally finish?

There are two camps on this:
- Outputting as you run frees up memory (true)
- Outputting all in one place may use a little more memory, but it prevents the output and wait hiccup (also true)

My opinion, if you' are storing a page output in memory that will choke your server, you need to figure out what you're doing wrong - even the most limp-along servers can handle storing a page output in memory. Ive cornered myself in page errors where the page output was so huge (1000 links with looooong query strings - oops) that it choked the browser. But it never choked the server.

Separating the output from the programming will do everything I've talked about, and it will make the page dump to the browser all at once, making for a smoother experience for your users.

cleanse_input();
do_your_functions();
output_the_response();

Compartmentalize, compress, simplify, recycle.

Related to spaghetti code, it's important to form an overall logical structure for the entire set of programs - the includes, the file naming, the specific scripts, all of it. When you recognize a function that could be redundantly used, do just that - recognize it and re-use it. A few changes to a simple function can make life so much easier. Here's an example, a state list.

function state_list ($obj_name) {
// select id,abbrev from us_states order by state asc;
// compile the list, set "selected" if $_POST is present and matches
return $list;
}

But wait a sec. This function
- accepts parameter of name
- selects from a table
- returns a select list

So why can't we make this object create a select list from any table?

We can.


function select_list ($obj_name,$targ_table,$id_fld,$value_fld,$order,$dir,$post_value) {
if (
(! $obj_name) or (! $targ_table) or
(! $id_fld) or (! $value_fld)
) { error("required parameters missing for select list"); }

$list = '<select name="' . $obj_name . '" id="' . $obj_name . '">';
$query = "select $id_fld, $value_fld from $targ_table";
if ($order) { $query .= " order by $order $dir"; }
$result=@mysql_query($query);
if (!$result) { error("can't get select list: " . mysql_error()); }
while ($row=mysql_fetch_array($result)) {
$list .= '<option value="' . $row[0] . '"';
if ($post_value == $row[0]) { $list .= ' selected'; }
$list .= '>' . $row[1] . '</option>';
}
$list .= '</select>';
return $list;
}

You now have a neat little function that will generate 95% of the select lists you will ever use. The bolded portions lead me to my next pet peeve, error checking.

If it works, it works.

If it doesn't, you get white pages, 500 errors (even with PHP,) blank values when you expect results, and the problem is likely buried deeply in 20K lines of code spread across sometimes hundreds of files. I attribute a good portion of programming problems to insufficient or lazy error checking.

True, if it works, you will never make use of your error check. But when things go sideways, you will wish you had. It only takes a few seconds to add the two lines shown above, or anywhere else in your program. Any time you expect a value, CHECK for it. This becomes extremely valuable when you have to move to a different environment - or when someone like me comes in to fix your problem. :-)

The code posted above should never ever ever be used in a public script:

error("can't get select list: " . mysql_error());

mysql_error can reveal table and field names. Use these approaches only in development, remove them after debugging.

error("can't get select list");

Sometimes rebuilding the wheel is better.

This one will probably draw flames. In all the languages I work with - Perl, PHP, Javascript, Flash, others - I am often told not to do what I'm doing, that it's already been done, use *this library* for that like everyone else.

If I have a function that will cost me 20 lines and half an hour to code, why on Earth would I include a 1500+ line library that will likely have dependencies on other libraries just for the same result? Does this make the application more robust if all but one of the features of said library are never used? Often I encounter this, and it's neither efficient or good coding practice, IMO. Many will disagree, as it sets a standard for your programming.

I do use libraries when appropriate, it boils down to what is most efficient, easiest to maintain, and will make the most sense to anyone seeing it.

In some cases, this is also true of OOP programming. I've encountered many cases where an OOP approach was used to standardize the way it's been coded. Many of them didn't really need it, and the classes required for a simple function increased the files by thousands of lines of code, and overcomplicated the comprehension of a simple task.

Just because you can, doesn't mean you should.

Time and time again I see suggestions like "Simple. You can do this or that." When this becomes an ingrained philosophy of your coding, it shows in your programming and overall quality of your programs. Sometimes, it will even trap you, using that method and bending it to your will. A perfect example is redirects. I always see PHP coders posting to a script, then redirecting to a static "thank you" page.

WHY? Why can't you take a moment to use the posted-to page to respond with a useful response page, that makes use of the variables posted?

Another is (ab)use of Javascript. Just because you can use jQuery to do a thing, that doesn't make it better (sometimes,) because you are ignoring the fact that any time you use Javascript for anything accessibility takes a huge hit.

I use the jQuery as an example because it's most obvious, but there are many decisions you will make in coding out an app. With each of those decisions, stop, think, am I doing this because it's an easy no brainer or because it's the best solution to the problem?

Comments are good. Usually.
I frequently see RFP's for "all code must be commented so we know exactly what does what." Okay. No problem, but if you follow the above style, commenting is only mildly necessary. Truth be told, I just add comments so I can easily find them in scripts. :-)

## Function for creating select lists from database
## table values. Required parameters are form object
## name, table name, record ID, record value. Order, direction,
## and post/get/request value are optional.

function select_list ($obj_name,$targ_table,$id_fld,$value_fld,$order,$dir,$post_value) {

Per the above, you shouldn't need to comment every single line, the variables should define their meaning.

Coding style is not always about how you tab your code, or where you make line breaks, or how you format the code itself, it's about how easy it is to maintain and understand without reading War and Peace to figure out what's going on. IMO anything beyond that is just a matter of preference.