TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 01-05-2008, 06:38 PM   #1 (permalink)
Wizard
Top Contributor 
 
Village Idiot's Avatar
 
Join Date: Sep 2007
Posts: 1,299
Thanks: 17
Village Idiot is on a distinguished road
Default Writing Clean Code

Its been a while since I've written an article, lack of inspiration. If you have any ireas on a subject, please do contact me.

Lately, other people’s code has been getting on my nerves. It is so messy it takes me an hour to just decrypt it. Don’t get me wrong, I can work with other people’s styles if they are clean. This inspired me to make this article on writing clean code. This is not a sure fire guide to clean code, but they are good guidelines.

1. Indentation

What style you use doesn’t really matter, just stick to it. I find the allman indent style the easiest, but it is fully up to you. Just stick with it in the entire application. If you have a team, make sure they all use the same style. The only style you should never use is none.
If you want a list of indent styles, go to Indent style - Wikipedia, the free encyclopedia


2. Brackets
PHP lets you have a single line under an if, while, or for statement without using brackets. Don’t use it. It makes things harder to read and leaves an open door for a bug should you accidentally add second line. Reason being it wont create an error, it will execute the command as normal outside of that condition or loop.


3. Comment your code
Even good code can be complicated. Comment everything you do. This does not mean every line, but every basic function. If you have a complicated process (well, hard to read) comment every step so the next programmer knows what is going on. And remember Eagleson’s law
“Any code of your own that you haven’t looked at for six or more months might as well have been written by someone else.”


4. Make everything as simple as possible, but not simpler.
This Albert Einstein quote sums up how your coding should be. Simple as possible. Some things simply take complicated, hard to read code. Don’t be afraid to use complicated code where needed, just comment them. But when possible, make it simple. One reason is as Brian W. Kernighan said
“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. “

Other reason is because adding things to applications may make it more complicated. Why not start from easy and work your way up as slow as possible opposed to start at the top and have no room to move.



5. Use descriptive variable names
With good indentation, comments and simple code, bad variable names can still make an application near impossible to modify. In no more then three words (there is a good reason they are not called novels), describe what it does and what it is. Lets say we have a mysql query getting all the post to the forum, a good name would be $posts_query. $query would not be good for the task, all it tells you is what it is, it could be any query. The same goes for functions.


6. Good looking variables
Descriptive naming is essential, but it serves almost no point if your variable name is $postsquery. It makes it harder to read because the next programmer has to separate the words themselves. It is better to either capitalize the first letter of each word ($PostsQuery) or use an underscore ($posts_query).




7. If you don’t use a templating system, embed PHP in HTML, not HTML in PHP
PHP gives you the ability to end the PHP and start html, if its within an if statement it will honor it. It is easier to read HTML with embedded PHP then echo’d HTML with all the quotes escaped. For example

PHP Code:
if($condition = “value)
 {
             ?>
             <input type=”text” name=”<?php echo $name?>” />
             <?php
 
}
Opposed to

PHP Code:
If($condition = &#8220;value)
 
{
             echo &
#8220;<input type=\”text\” name=\”$name\” />”;
 

It doesn’t make a huge difference in that instance. But when outputting large blocks of HTML, it is far easier to read if you are putting the PHP in the HTML.


You can find this and other articles like it at my Programming Tips blog
__________________

Village Idiot is offline  
Reply With Quote
The Following 3 Users Say Thank You to Village Idiot For This Useful Post:
Alan @ CIT (01-06-2008), Karl (01-06-2008), Wildhoney (01-05-2008)
Old 01-06-2008, 01:22 PM   #2 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 437
Thanks: 22
Karl is on a distinguished road
Default

Great article, one note though, there's a better, cleaner (in my opinion) way to embed PHP into HTML, and that is using keywords in replace of brackets, such as:

PHP Code:

<?php if ($condition == 'value') : ?>

    <input type=”text” name=”<?php echo $name?>” />

<?php endif; ?>
Each to their own, I just prefer this way and thought it deserved a mention.

Finally, I have one more suggestion :)

1) Keep functions short and concise, with descriptive function names. This improves code clarity (cohesiveness), there's nothing worse than looking at a function that is responsible for 10 different little tasks, break that function up into smaller, more understandable functions.

Of course we're treading onto refactoring here, but imo that's an important part of clean code.
__________________
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Last edited by Salathe : 01-06-2008 at 11:06 PM. Reason: I'm fairly sure you wanted a comparison operator (==) and a closing quote after 'value'... :)
Karl is offline  
Reply With Quote
Old 01-07-2008, 04:52 PM   #3 (permalink)
Wizard
Top Contributor 
 
Village Idiot's Avatar
 
Join Date: Sep 2007
Posts: 1,299
Thanks: 17
Village Idiot is on a distinguished road
Default

I have a bias against the endif way due to the fact is what basic uses. That and notepad++ highlights the starting or ending bracket to the one you have highlighted.
__________________

Village Idiot is offline  
Reply With Quote
Old 01-08-2008, 01:01 PM   #4 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

It does aggravate me personally how people claim that because users cannot see code that it doesn't matter. I think it very much does matter. For the very fact that managing bad code is an utter nightmare, and any subsequent additions to the system would merely be patching up the code to take it another mile before it again falls apart, is dead wrong.

If everybody in this world had that frame of mind, such as a car manufacturer, say Lotus, built cars that lasted for a year before I install some fluffy dice in my car and the carburettor decided enough was enough and keeled over. You take it back to the garage where the mechanic informs you that this will soon become common because Lotus only manufacture cars to get them out of the showroom, and to do a few errands before it decided it could not carry in - you wouldn't be best pleased to say the least!

The bottom line is, things are supposed to be built to last, and if they don't last then that's bad workmanship. Whether I can see the carburettor or not is immaterial. I'm not a mechanic and so constantly checking it is of no concern to me, I paid good money for my Lotus and I expect it to function for a damn sight longer than a year.

Coding is no different.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 01-08-2008, 04:09 PM   #5 (permalink)
Wizard
Top Contributor 
 
Village Idiot's Avatar
 
Join Date: Sep 2007
Posts: 1,299
Thanks: 17
Village Idiot is on a distinguished road
Default

Well said *claps*
__________________

Village Idiot is offline  
Reply With Quote
Old 01-09-2008, 05:37 PM   #6 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

To be honest on point #6, if I ever do inline MySQL, which I do from time-to-time, even still, then I do use $szQuery merely because it describes what it is, it just doesn't describe the finer details of its content. And I think that's very important.

I could name my query string variables $szLoginQuery but I feel variables shouldn't be so descriptive. When you start having to add many inline queries concurrently - to which would require differently named variables, then I don't think the problem is necessarily the variable naming scheme, but rather the fact that such concurrent queries should be moved off into classes and thus the query variable name can remain nondescript and vague.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 11-21-2011, 09:27 AM   #7 (permalink)
The Visitor
 
Nicklaus's Avatar
 
Join Date: Nov 2011
Posts: 3
Thanks: 0
Nicklaus is on a distinguished road
Default

You must ensure that your code is very readable, clean and maintainable. That's what all programmers must do.
But you are talking about over styling (like that term better that girl-code) which serves nothing but the ego of its author.
I've seen many developers in the past so proud of their creation (you know, like in the restrooms ;)), they spent hours cleaning and polishing their code. Some of them were so meticulous than they ensured that the correct white spaces between members were respected.
It's too much.
I fight that kind of behavior counterproductive. In a professional context, you must be professional. You can get your satisfaction by writing clean, very readable and maintainable code and talking with happy users or colleagues.
Nicklaus is offline  
Reply With Quote
Old 11-30-2011, 08:38 AM   #8 (permalink)
The Visitor
 
Francis's Avatar
 
Join Date: Nov 2011
Posts: 3
Thanks: 0
Francis is on a distinguished road
Default

This is a question I've been asking myself for a long time. Thought of throwing out it to you.
From my experience of working on several Java based projects, I've seen tons of codes which we call 'dirty'. The unconventional class/method/field naming, wrong way of handling of exceptions, unnecessarily heavy loops and recursion etc. But the code gives the intended results.
Though I hate to see dirty code, it's time taking to clean them up and eventually comes the question of "is it worth? it's giving the desired results so what's the point of cleaning?"
In team projects, should there be someone specifically to refactor and check for clean code? Or are there situations where the 'dirty' codes fail to give intended results or make the customers unhappy?
Do feel free to comment and reply. And tell me if I'm missing something here.
Francis is offline  
Reply With Quote
Old 01-14-2012, 05:29 PM   #9 (permalink)
The Wanderer
 
Germanium's Avatar
 
Join Date: Nov 2007
Posts: 9
Thanks: 0
Germanium is on a distinguished road
Default

Variable naming is often broken - I once worked on some code where the programmer had defined naming conventions like:
* varTime
* varSpeed
* varPointsTotal
Send a message via ICQ to Germanium Send a message via MSN to Germanium Send a message via Yahoo to Germanium
Germanium is offline  
Reply With Quote
Old 05-17-2012, 10:51 AM   #10 (permalink)
Ivan Ivković, Croatia
 
ivanivkovich's Avatar
 
Join Date: May 2012
Posts: 7
Thanks: 0
ivanivkovich is on a distinguished road
Default

Quote:
Originally Posted by Karl View Post

PHP Code:

<?php if ($condition == 'value') : ?>

    <input type=”text” name=”<?php echo $name?>” />

<?php endif; ?>
This is what I was searching for! Thanks!
Send a message via Skype™ to ivanivkovich
ivanivkovich is offline  
Reply With Quote
Old 06-25-2012, 12:35 PM   #11 (permalink)
The Wanderer
 
Join Date: May 2012
Location: usa
Posts: 6
Thanks: 0
cheapcnjerseys is on a distinguished road
Default

Nike NFL Jerseys from china, Nike NFL Jerseys online,cheap Nike NFL Jerseys,2012 nike nfl jerseys, nike nfl women jerseys,buy jerseys online, soccer jerseys shop online, nfl jerseys store online
cheapcnjerseys is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 03:00 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design