gotta have style, baby

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

Post by BDKR »

llimllib wrote: Sorry, BD, I really wasn't trying to troll at all :)
Don't apologize. It's not needed. It actually was meant more as a joke. 8)
llimllib wrote: However, I believe we have gotten a couple things out in this thread that are important. First, the importance of seperating things out into functions even when they seem simple. It appears that mcgruff has seen the light.
That's good. It's also good to see the Crime Dog writing code. :D
llimllib wrote: Second, I think this comments discussion is an important one, and perfect for the advanced forum. Perhaps it should be seperated into a seperate thread, because it's a little different from what it started out to be.
Have at it.
llimllib wrote: I think all Jason is trying to say is to comment wisely.


I can believe that, but this is the kind of thing we have to be careful about. There are some points, or should I say situations where everyone must tow a line and code in accordance to a standard, or else the team or project is going to go bust.

BUT, in most other situations there should be as much room as possible allowed for an individual to simply create. A new up and coming should be made aware of standards and methodologies, but free to break those when the only person harmed is he or she. If nobody is encouraged to think outside of the box, we're heading into a dead end! Perhaps a person should comment as much or little as helps them, then think about going back and refactoring the comments! I do it all the time.

Also, I've used comments while helping others get the hang of coding. I encourage the person to write a comment that represents what they want to do, whether or not they know how to do it. Whatever helps a persons mind set.

For me, I love comments and code that has lots of comments. Based on who the progger is, it can be a picture of that persons creative process at the time. That's a picture that should be prized! It's of utmost value when studying the code. One of my favorite coders is John Carmak (Doom, Quake). I have the source for QII and QIII and frankly wish there was more in the way of ramble in the comments to give me a picture of what his thinking was at the time.

Anyway, absolutes, when it comes to comments, shouldn't exist outside of the team or
project domain.

Oh, and er..., sorry for going off... :oops:

Cheers,
BDKR

P.S. It's good to see that you (limlib) are still alive. Now Blog! Also, I couldn't get fluxbox to work from GDM in RH9 either! Hmmm.....
evilcoder
Forum Contributor
Posts: 345
Joined: Tue Dec 17, 2002 5:37 am
Location: Sydney, Australia

Post by evilcoder »

I cant remember who said it, but i'm a big fan of self-commented code. much easier to read, easy to write and allows you to write faster as you dont have to stop to write comments:

Code: Select all

<?php

$Database_Connect = mysql_pconnect( "" , "" , "" );
$Database_Select = mysql_select_db( "" , $DB_Connect );

$Query = "SELECT * FROM table";
$Query_Return = mysql_query( $Query );

?>
Theres no need to comment anywhere in there.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

I've had an interesting couple of days now that I've stopped trying to be "efficient". Code can really flow if, as llmllib said, you start looking at it as a high level language.

I would never have done this before:

Code: Select all

<?php
function stripper(&$array) {

    foreach ($array as $key=>$value) {

        $array[$key] = stripslashes($value);

    }

}
........
.........
$result = mysql_fetch_blah...;
stripper($result);
?>
A little thing but saves time and cleans up a lot of stripslash mess.

I even wrote a class to write some simple html - options list for a select form field, with a preselected value passed to the class by the calling script. Now THAT is going to be useful... Next time I need a select field two lines of code and <snap!> it's done.
Last edited by McGruff on Thu Aug 11, 2005 8:16 am, edited 1 time in total.
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post by jason »

BDKR wrote:
I have to say that some of this is just downright arbitrary! But here goes....
Commening Rule #1: Comments that require maintenance are bad comments.
No, comments require maintenance because at times while creating and finding a better way during the coding process, the code changes. Therefore the comments should be changed. What if the function needs a rewrite in response to a boneheaded client that doesn't
seem to know what he wants?
Nope, your taking the rule out of context. The original response was in regards to bad commenting styles.

Example of a comment that requires maintenance. If you change the comment, you have to work to make it conform to the commenting standards again.

Code: Select all

<?php
/**************************************
* This commenting style is bad	*
* It requires a lot of work to keep	*
* up and is a pain to change things	*
* so people will not want to change*
* it or use it					*
**************************************/
?>

Code: Select all

<?php
/*
This comment is better.  It's easy to type, easy to use, 
and if you need to make a change later on, you just
make the change will minimal fuss.
*/
?>
Maybe the use of the word "maintenance" was a poor choice. But these rules were stated within the context of this thread, and was explained (I believe) when I original stated them.
BDKR wrote:
Commening Rule #2: More comments means your code is less readable.
This is simply a matter of personal taste. It's also an echo of old time dinosaurs from the days when memory was extremely expensize and hard to come by. Back then, code had to be as tight and small as possible. For the most part, it's not true in general. What if the code is doing something interesting. That's the kind of stuff that should be commented. Besides, I don't want to have to read the code to see what it's doing if a comment will tell me. Even better, it may help put me in the mindset of the original coder to help better understand his logical process.

One of the single most difficult things any progger ever has to do is read someone else's code!.
It's rather simple with a clear example:

Code: Select all

<?php
// This block of code does this
if ( $some == $thing ) {
// This part does this
	$does = $this;
// and this part does this
	$does = $this_some_more;
// and this part of the code is included
// because this and that need to be equalized
// when underwater
	$this_that = equalized($this_that);
}
?>
or this:

Code: Select all

<?php
/*
This block of code does this as well as this
and some of this and this part of the code is included
because this and that need to be equalized
when underwater
*/
if ( $some == $thing ) {
	$does = $this;
	$does = $this_some_more;
	$this_that = equalized($this_that);
}
?>
Now, assuming these comments aren't just repeating the code, which is easier to read? For the majority even?
BDKR wrote:
Commening Rule #3: Comments are written in another language from the code. When reading through code littered with comments, it's like reading through a book in two languages.
As an extreme example, I removed all the comments from a tool that I wrote to help with emergency situations should they arise (and have done so by the way). Can anyone tell me what it does with a casual glance?
I'll take the blame for this confusion. After rereading the second rule, and the third, I realize they are basically the same thing, and indeed, were intended to solve the same problem.
BDKR wrote: I'll take the comments!
As will I.

First, as to what the code does...hrm.. I would have to say it does this: "This code is for splitting binlogs up into their respective parts. To put it more plainly, to seperate the queries for various databases on a particular MySQL server. In the version 4 series (someone correct me if I'm wrong) one may specify which db they want the information for making this script useless. However, with 3.23.xx, this script should come in handy."

/me snickers

Okay, seriously, first, to everyone reading this, I did not figure this out from the code. Rather, I read BDKR's most excellent weblog[1] regularly (as so should you, mostly so he posts more), and this is some recent code he posted [2],

BDKR: As much as you think you have proved your point with this example, it would only be true if I said comments are bad, and should never be used. My arguments are against the "Comments are always good" and the "More comments == More goodness" beliefs.

Placing comments willy nilly in your code will NOT help. However, comments which are used properly are good, and helpful.

Proof of point in reading through your code:

Code: Select all

<?php

# Now open the sql file into an array
$queries=file($args['file']);

?>
Here is an example of a comment that is completely useless. file() is a function that returns a file as an array. The only potential value the comment adds is that it defines the file as the SQL file. However, you could have done this

Code: Select all

<?php

$queries=file($args['sql_file']);

?>
And the code is just as clear. to understand.

However, on the flip side, let's look at this:

Code: Select all

<?php

# Parse the 'use db' string
function parse_use($str)
	{
	$new=str_replace("use", "", $str);
	$new=str_replace(";", "", $new);
	$new=str_replace(" ", "", $new);
	$new=trim($new);
	return $new;
	}

?>
The comment for this function is clear and succint. It defines exactly what the code is used form It's a good comment.

Code: Select all

<?php

# This function will check the arguments 
function check_args()
	{
	# Create the array that will be returned
	$data_arr=array("file"=>'', "db"=>'');
	
	# Let's first check the number of args
	if($_SERVER['argc']!=3)
		{ 
		echo "Incorrect argument count! Use -h for usage.\n";
		exit;
		}
	
	# Assign data to the array
	$data_arr['file']=&$_SERVER['argv'][1];
	$data_arr['db']=&$_SERVER['argv'][2];

	# Return the information
	return $data_arr;
	}

?>
In the above function, the first comment about the function is good, as is the second function (it let's whoever works with this function later know what that variable is). However, the 3rd, 4th, and 5th comments, are they really needed? Of course return resturns the information.

Your header comment, detailing what the software does, is fine (except, I would eliminate all the extra asteriks, they are annoying to work with). It's important, it details what the software does.

Your code isn't bad. Your comments aren't evil. These are however, ways to improve your code.

Of all things concerning comments I have ever said, however, I have preached consistancy above all. Being consistant is more important than anything. At least if the code and comments are consistant, we have a starting point.
BDKR wrote: For the most part, this topic has led to holy wars and flame wars for as long as proggers have been progging! I really should have a talk with limlib about this. He should know better! He's prolly giggling his tail off over this one.

Anyways, like crack and tailgating, I usually don't indulge, but on this topic we have to remember that far fewer things then we like to think are concrete. Whatever an individual does that works for him or her isn't bad because it's gibberish to another. Yes, on one level, we must be concerned when we are part of a team or project, but if one is in 'lone-coder' mode, and it's his or her project, more power to 'em! These are more often than not the nuts and weirdos coding or tinkering away in a basement somewhere, clothes dirty and face unwashed, that comes up with the next big thing! We should be careful that we don't stifle or hinder with standards.

Cheers,
BDKR

p.s. ternary operators rule!
As with all standards, they are great because their are so many to choose from. =)

They way I look at comments is pretty simple. I may be wrong, I'll admit it. However, I doubt it. I honestly think that I am not saying anything that isn't the norm. As I mentioned before, I am not against comments. I use them myself. I am again against the "Comments are always good" and the "More comments == More goodness" beliefs. These, I believe, are wrong.

But of course, that's my belief. Take it for what it is.

Yes, this is an [un]holy war. Just be careful, I am not on the side of "no comments at", but neither am I on the "all comments all the time" side. I am Switzerland.

PS: I don't want to suggest BDKR's examples are examples of poor code. Merely, it was code that was handy at the time. BDKR is a strong coder, and has my respect. Don't take my ripping on his commenting style as a reflection of my belief of his ability. I could have just as easily taken code from my own stuff and used it here, because, unfortunately, I sometimes stray from my own rules.

PSS: Yes, ternary operators are coolness.

[1] http://mgaps.highsidecafe.com/
[2] http://mgaps.highsidecafe.com/tools/bl_split
User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

RRrrrrrrggghhhh......

Post by BDKR »

I have to say that the thing I like about Jason is that he'll take a shot and get right back up swinging. :D I can certainly see his points here and they are good ones. But some of the things that he mentioned are examples of my coding practice. How I think through the code first, place comments in key places, then come back and write actual code.

Oh and BTW, you're a cheater Jason! LOL!

Anyways, in this code example:

Code: Select all

# This function will check the arguments 
function check_args() 
   { 
   # Create the array that will be returned 
   $data_arr=array("file"=>'', "db"=>''); 
    
   # Let's first check the number of args 
   if($_SERVER['argc']!=3) 
      { 
      echo "Incorrect argument count! Use -h for usage.\n"; 
      exit; 
      } 
    
   # Assign data to the array 
   $data_arr['file']=&$_SERVER['argv'][1]; 
   $data_arr['db']=&$_SERVER['argv'][2]; 

   # Return the information 
   return $data_arr; 
   }
Now Jason's points about the above code are well recieved, and is correct. What else is "return $data_arr;" going to do? But in light of how I approach a problem, the comments are sometimes just 'artifacts' or the original mindset. Here is what I said in an earlier post.
Also, I've used comments while helping others get the hang of coding. I encourage the person to write a comment that represents what they want to do, whether or not they know how to do it. Whatever helps a persons mind set.
Now this is what that function looked like when I first started writing it.

Code: Select all

# This function will check the arguments 
function check_args() 
   { 
   # Create the array that will be returned 
    
   # Let's first check the number of args 
    
   # Assign data to the array 

   # Return the information 
   }
In other words, I placed the comments first to act as a rough outline or representation of what was going on in my head. I feel this is a good way to get down the road and will most likely continue to use it. As for wether or not all of it needs to remain, that I feel depends on what the code is doing. For example. I would keep the comment for the file() function (from a different example) as it's a function that I don't see many people using. Most people tend approach this issue from the fopen() / fread() school of file i/o.

Perhaps this is just like what I said in an earlier comment.
Perhaps a person should comment as much or little as helps them, then think about going back and refactoring the comments! I do it all the time.
I didn't do this time though. :oops:

Anyway,
Your header comment, detailing what the software does, is fine (except, I would eliminate all the extra asteriks, they are annoying to work with). It's important, it details what the software does.

Your code isn't bad. Your comments aren't evil. These are however, ways to improve your code
Honestly, I don't how or why the asteriks are annoying. But once again, this is a matter of personal tastes and therefore this is where conversations along these lines should be aborted.

However, I will add that I like this approach as those sections with all the astericks as they act as easily identifiable seperators of sorts. Notice near the bottom where the functions start. It's clearly commented and a more-than-easy way to see. There are two things I did here.

1) Put the logic first and the functions second.
2) Clearly seperated the logic from the function list.

If any of you have ever read C code of moderate to large size, it's often difficult to figure out what's going on as many times you need to scroll down through function after function after function before you get to main() and can see the overall logic of the program. I reject this in PHP because I can. With C, there is not much room for flexibility (in other words, there is way to get around this) without having the compiler screamin' at you. That said, with me and PHP, the logic comes first, then the functions list with that huge asterik-full-of seperator. Now a person can see exacty where the logic starts and ends as opposed to having to look at function names in particular or spend extra mental energy to get a grip on what the code is doing.

Now do the asteriks work with any of those documentation tools? No. Do I care? No.

However, if I was part of a developement team and my livelyhood depended on choking down it's standards, you can bet I will do some caring.

Anyway, as much as this post was mainly from a defensize posture, I still have the taste of boot in my mouth from letting Jason's comments (no pun intended) step on my toes. Evenstill, I feel that some of what Jason stated could (and may still be) limiting. Why? Becuase they are stated as absolutes.

However, it should also be stated that this is clearly an issue of scope. Before talking about whether or not a comment or comment style is bad, perhaps we should first figure out if the code is part of a collaborative project or not. Another thing we can ask is if there are plans to use a documentation tool. If the above is not the case, we are into the realms on an individual approach and style. And in support of that, I'm going to keep swinging!

Perhaps I've read too much Ayn Rand :?:

Lastly, Jason and I have discussed other things at other times. There is a mutual respect. I hold guys like Jason, Volka, Harry Fueks, and limlib in high regards. I look at these guys and see in each one of them a strong point that I personally need to work on. But we are all different and it should'nt be too suprising that eventhough we are talking about the same cherished interest, we bare our teeth from time to time.

Cheers,
BDKR
User avatar
xisle
Forum Contributor
Posts: 249
Joined: Wed Jun 25, 2003 1:53 pm

Post by xisle »

Code: Select all

<?php
# Now open the sql file into an array
$queries=file($args['file']);
?>
Here is an example of a comment that is completely useless. file() is a function that returns a file as an array.
First time post here, 4 year php programmer.
From an outsider's perspective on the thread:
This type of comment may be useful to the entry level programmer
who does not have all php functions under their belts.
I specifically recall ( in the beginning of time)
finding the file() function in a manual and being
psyched because I had been using feof unnecessarily.
Is it possible that commenting level should be fluid and
contingent upon the audience? Are there juniors in your group
that may need this level of commenting help?

just a thought..
xisle
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post by jason »

I don't think that should influence your commenting level. If someone is unaware of what a function does, they have the manual handy. That's what it's there for.

The little benefit it provides to a newbie programmer does not overweigh the disadvantage it would give to a more advanced programmer.
User avatar
Heavy
Forum Contributor
Posts: 478
Joined: Sun Sep 22, 2002 7:36 am
Location: Viksjöfors, Hälsingland, Sweden
Contact:

Post by Heavy »

Guys...
Let me tell you that reading this thread is really good and healthy.
Reading jasons post quoted below teached me one thing about one feature I created for a system running in a sharp environment.
jason wrote: There is also the case of the highly complex code that needs a paragraph to describe what it does. This is usually a sign the programmer has to do some refactoring.
You got me.
Iv'e done that really baaad. It is a collection procedure for queued outgoing email. It works, but it is hardly understandable. I bet I would get tired of just looking at it now that it is "finished". It isn't even anything special to think about. Some users, some email, some email addresses. I MADE IT complex, but it didn't have to be complex in the first place.
I don't deserve more than to rewrite it better.Do it once more. Do it right.
If I as a programmer go down to crawling in front of the screen as I try to get it right, there must be something wrong in the idea that formed the code.
Hopefully I won't do that again.
Big thanks to a great community. :wink:
User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

Post by BDKR »

xisle wrote:

Code: Select all

<?php
# Now open the sql file into an array
$queries=file($args['file']);
?>
Here is an example of a comment that is completely useless. file() is a function that returns a file as an array.
First time post here, 4 year php programmer.
From an outsider's perspective on the thread:
This type of comment may be useful to the entry level programmer
who does not have all php functions under their belts.
I specifically recall ( in the beginning of time)
finding the file() function in a manual and being
psyched because I had been using feof unnecessarily.
Is it possible that commenting level should be fluid and
contingent upon the audience? Are there juniors in your group
that may need this level of commenting help?

just a thought..
xisle
There are others that certainly disagree, and that's OK by the way, but when I don't know what a function does, and after 4 years with PHP myself, that's still possible, it's nice to have a comment right there to tell you! A trip to the manual is not allways needed!

Rock hard, ride free!
BDKR
Post Reply