Page 1 of 1

Coding styles

Posted: Fri Jun 10, 2005 6:25 am
by Chris Corbyn
In a community like we have here we see lots of different coding styles. Some to me, look very unreadable and unorgainised, but to the author I guess my code may appear the same to them.

How many people follow a strict style, whether it be taught or personal preference?

What do you find help make code as readable as possible?

Who swaps and changes their coding style with the weather?

I'm just curious because I always use the EXACT same style, with everything from placing brackets and parentheses in the same place to adding comments in a particular fashion.

For me I like plenty of whitespace, nesting is always done like this (for all classes, functions and conditions)

Code: Select all

if () {

    //this

} else {

   //that

}
I always add little

Code: Select all

//end if
//end function_name()
//end while
after closing brackets etc.

Posted: Fri Jun 10, 2005 6:38 am
by Bennettman
My style tends to involve lots of whitespace in nesting like yours, d11wtq. I also like to split arguments (especially in str_replace) up, and put SQL commands on more than one line. However, I don't use comments a lot. I usually use them to explain sections of code, or explain what functions do.

Code: Select all

<?php

// strip_slashes(STRING text) - returns text with escaping slashes removed (and yes, I know this is useless ;p)
function strip_slashes($text) {
     return preg_replace(
          "/\\\('\")/",
          "$1",
          $text
     );
}

// Get the data for #5
$data = mysql_query("SELECT *
                      FROM table
                      WHERE id=5
                      LIMIT 1");

?>

Posted: Fri Jun 10, 2005 6:49 am
by malcolmboston
example of parathesis

Code: Select all

function dosomething ($number)
{
   // comment regarding what the function does here
   $number = ($number + 1);
   return $number;
}
example of vars in strings

Code: Select all

print "Something is equal to {$something}";
the whole way i code is based on readability, i fully know that my code can be shortened but i add stuff in for readability
for example

Code: Select all

if (isset($something))
{
   // do nothing
}
else
{
   // call function
   DoSomething();
}
// this could be rewritten to the shorter...
if (!isset($something))
{
   // call function
   DoSomething ();
}
imo, readability is just as important as the code

Re: Coding styles

Posted: Fri Jun 10, 2005 7:48 am
by Roja
d11wtq wrote: How many people follow a strict style, whether it be taught or personal preference?

What do you find help make code as readable as possible?
I follow a fairly strict style. After seeing the phpbb coding guidelines, I grabbed a copy, modified it to match my preferences, and posted my version for my projects (http://www.kabal-invasion.com/guidelines.html)

I've generally followed those guidelines for the last 18 months or so in most of my projects. For me, the critical top three:

- Works with reg_globals off, and notices on
- Brackets line up
- NO TABS

Almost all of it is related to my coding preferences. I end up going back and forth between webcvs views and putty w/ nano all the time. As a result, tabs aren't pasted correctly, and I end up with massive diffs for no changes. I hate tabs as a result. :)

Not to mention, using nano as my editor, having the brackets line up really makes it simple to scroll to the spot I need to.

Of course, most of my projects start with "someone else"'s code, and then i spend years modifying it to match my preferences. That means I end up with plenty of procedural code where I would normally use OOP, and plenty of code that breaks my guidelines.

All told, it definitely helps (me) to document the style, so I can refer to it, and so that other developers on the project can too.

Posted: Fri Jun 10, 2005 8:30 am
by patrikG
I'm fairly happy as long as there is a consistent coding style. What is much more important to me is at least a simple seperation of logic and view. Unfortunately, PHP doesn't force you to have a clear code structure unlike Python where indentation is part of the code can change pretty much everything.

Personally, I tend to use what is, I believe, more or less the accepted C-coding style.

A code snippet from a user-class of mine

Code: Select all

/**
    * fetches all data of a user from database
    * and assigns it to $this->user
    * @param int $id user-id
    * @access private
    **/
function get_details($id=""){
	if ($id=$this->id($id)){
		$query="SELECT * FROM members
				LEFT JOIN memaddress ON members.mem_contactID=memaddress.mem_contactID
				WHERE members.mem_contactID=".$this->id;
		$record =&	new QueryIterator($this->db->query($query));
		if($data=$record->getCurrent()){
			foreach($data as $key=>$value){
				(is_string($key)) ? $this->details{$key}=filter::sanitize_sql_string($value) : '';
			}
		}
		$this->get_membership();
		subscription::get_subscription($this->id);
	}
}

Posted: Fri Jun 10, 2005 2:58 pm
by onion2k
Comments that don't actually say anything that you can't get from the code really annoy me. Something like "//Call function" would get removed immediately. If should be "//Call function stored in functions.inc.php to generate user id" or something. Clear, verbose, and useful. Bad comments are worse than no comments.

Posted: Fri Jun 10, 2005 6:51 pm
by Skara
I can't stand extra whitespace. Useless. :P //End whatever comments bug the hell out of me too. I code something like this:

Code: Select all

$valid = array('about','guestbook');
if (isset($_GET['page']) && in_array($_GET['page'],$valid)) require $_GET['page'].'.php';
else {
  require 'news.php';
  print('<h2>News</h2>');
  for ($i = count($news) - 1; $i >= 0; $i--) {
    $date = str_replace(' ','&nbsp;',$news[$i]['date']);
    print("<table cellspacing='0' cellpadding='0' class='news'>
           <tr><td class='ntitle'>{$news[$i]['name']}</td><td class='ndate'>{$date}</td></tr>
           <tr><td class='nnews' colspan='2'>{$news[$i]['news']}</td></tr></table>");
    if ($i) print('<br />');
  }
}
I never have a { on a line by itself. Can't stand that either. Oh, and tabs for me are always two soft spaces.

Posted: Fri Jun 10, 2005 8:01 pm
by Roja
Skara wrote:I can't stand extra whitespace. Useless.
Ah, but for you, and your tools, its "extra". For me, its critically needed.

To each their own. :)

Coding styles are definitely extremely different from one programmer to another.

Posted: Fri Jun 10, 2005 11:06 pm
by McGruff
I used to go mad with whitespace but I recently changed to something more condensed. Function braces line up, but not loops and conditionals. I hardly ever put comments in code apart from parameter/return types (and then only on public methods). I see comments as something of a smell: good naming, lean methods that don't try to do too much, and unit tests can virtually eliminate the need for comments.

Posted: Fri Jun 10, 2005 11:45 pm
by webjoe
I just generally follow PEAR's coding standards:

http://pear.php.net/manual/en/standards.php

Posted: Mon Jun 13, 2005 11:51 am
by m3mn0n
I'll show you my style based upon the good example by malcolmboston.

example of parathesis

Code: Select all

// comment regarding what the function does here
function Foo ($number) // int
{
   // comment describing the current code block
   $number = ($number + 1);

   return $number; // int
}
example of vars in strings

Code: Select all

echo "Something is equal to ". $something;
I like taking the variable out of the quotes so it's more easily identifiable (thanks to syntax highlighting) when scanning source code quickly.

Also, I tend to add a lot of comments and a lot of spacing between things so it's easier to read on the fly and so it makes the source code easier to read for people I work with, and of course myself after a few months of not seeing that particular snippet/funciton/class.

Code: Select all

// comment regarding what's going on
if ( !isset ($something) )
{
   // error handling

} else {

   // call function
   Foo ();
}

Posted: Tue Jun 14, 2005 3:10 am
by CoderGoblin
Skara wrote://End whatever comments bug the hell out of me too.
I too dislike //End comments however sometimes I find they are useful. If a complex nesting is taking place and the code stretches past a "page" it is often useful as a sanity check if I ever have to edit using a simple text editor and mismatch brackets.

I do agree with the post that bad comments are worse than no comments but comments in general tend to be based on the communication skills of the programmer. If the programmer is programming on the "fly" without proper design documentation additional comments are required. If design documentation exists less comments should be required.

Posted: Tue Jun 14, 2005 5:27 am
by timvw
I remember in that a couple of years ago i saw a tool "indent" which could indent/format/beatify code to the style you liked (I don't mean a code2html generator) I wonder if there is such a tool for PHP too, anyone? :)

Posted: Tue Jun 14, 2005 6:42 am
by Weirdan
There's a vim php indent script... but it won't suit you unless you're comfortable with vim.