473,320 Members | 2,083 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

do professional PHP programmers use error checking in their code?


I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?

Which of these two functions is better, the one with error checking or
the one without?

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
}
}

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
if ($result) {
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
if (is_array($row)) {
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
} else {
reportError("In getWeblogEntries, the function getRow
failed to return an array on the $i iteration.");
}
}
} else {
reportError("In getWeblogEntries, the query to the database
failed.");
}
}

My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere. I've taken over
PHP projects, started by other programmers, that had no error checking
and no comments, and such projects are always a big pain in the neck. I
lose time playing Sherlock Holmes, trying to track down where a
function's parameter first originates and why it's in use. I'd rather
have a comment on it, and error message for when the wrong thing is
passed in. Obviously this slows development. Is there any concensus
among developers about what is the best approach? I think whatever is
cheapest for the client should be considered the best approach, but it
seems to me cheapest-in-the-short-term is quite different from
cheapest-in-the-long-term.

Sep 2 '06 #1
16 2577
"lawrence k" <lk******@geocities.comwrites:
I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?

Which of these two functions is better, the one with error checking or
the one without?
The one with error checking.

/Always/ check for errors and print a meaningful message. The interpreter
can't do that for you, no matter how impressive it is.

/Always/ comment your code, and for large projects, keep your design
documents around (you do make design documents, right?). It'll save
time and money in the long run.

And by long run, I mean more than two weeks after the code is finished.

--
Andrew Poelstra <http://www.wpsoftware.net/projects>
To reach me by email, use `apoelstra' at the above domain.
"Do BOTH ends of the cable need to be plugged in?" -Anon.
Sep 2 '06 #2
On 2006-09-01 22:29:16 -0600, "lawrence k" <lk******@geocities.comsaid:
>
I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?

Which of these two functions is better, the one with error checking or
the one without?

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
}
}

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
if ($result) {
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
if (is_array($row)) {
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
} else {
reportError("In getWeblogEntries, the function getRow
failed to return an array on the $i iteration.");
}
}
} else {
reportError("In getWeblogEntries, the query to the database
failed.");
}
}

My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere. I've taken over
PHP projects, started by other programmers, that had no error checking
and no comments, and such projects are always a big pain in the neck. I
lose time playing Sherlock Holmes, trying to track down where a
function's parameter first originates and why it's in use. I'd rather
have a comment on it, and error message for when the wrong thing is
passed in. Obviously this slows development. Is there any concensus
among developers about what is the best approach? I think whatever is
cheapest for the client should be considered the best approach, but it
seems to me cheapest-in-the-short-term is quite different from
cheapest-in-the-long-term.
I agree with you, although I think the extent you take it to depends on
the needs project. Having quality error reporting is much different
than interpreter errors. An error like:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ') VALUES ( 1, 2, 'asdf', 'asdf',' at line 8"

doesn't tell you much other than there is problem. A function like:

function myFunction($sql) {
$result = @mysql_query($sql, $connection);
if (!is_resource($result) && $result !== true) {
die(mysql_error()." (Full query: ".$sql.") in function
myFunction');
}
return $result;
}

can save you lots of debugging, doesn't really take any extra time to
write and gives the added benefits of showing both the interpreter's
error, the full context of the error and the function used. But this
just describes an error that would kill the script anyway. What if, as
in your example, you needed program behavior to change based on
external influences (I.E. user input, database results, etc.)? In any
'real' language (PHP is just as real as Java) you would be foolish not
to have error checking and reporting. Why wouldn't that apply to an
interpreted language? In the end, what's the difference other than the
fact that it's not compiled into bytecode (you can compile PHP btw,
http://www.roadsend.com/home/index.p...eID=compiler)? Most
interpreter errors are comparable to compiler errors, and data checking
in otherwise 'compilable' code is a necessity in any language.

Granted, I think you should take advantage of PHP's abilities when you
can and when it makes sense (better not to re-invent the wheel, a tired
phrase I know) but that hardly covers everything.

Sep 2 '06 #3
On 1 Sep 2006 21:29:16 -0700, "lawrence k" <lk******@geocities.com>
wrote:
>
I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location.
[snip]

Personally, so far as MySQL stuff is concerned, I now use Adodb as
well as your method of if... else... echo... exit();

With Adodb you can easily turn on a higher level of Debug which
displays the SQL queries without you needing to do anything in the
code.
--
Locate your Mobile phone: <http://www.bizorg.co.uk/news.html>
Great gifts: <http://www.ThisBritain.com/ASOS_popup.html>
Sep 2 '06 #4
The error-checking policies also evolve during time. At first projects
at my current job, there was not much error checking. Now there's still
lot to improve, but things are better. There's sort of error-checking
framework in use, and it evolves.

if( !$dbresult ) {
HandleError("DatabaseError", "strErrorCode", "ELEVEL_CRITICAL", $sql,
mysql_error(), "Script location");
}

Well that's just from top of my head. But that's basically what happens
when there's an error. If error level is critical (or whatever), send
email to this address. Write all error to log.

So shortly my 5c is to always error check, and from project to project,
develop the error checking procedure according to needs and problems to
have a generic error checking process, which works for you and your
company policies.

t.j

Sep 2 '06 #5
It is definitely the better way to include error checking, but only for
fatal errors. When it comes to database errors it is FAR better to use the
error message which is generated by the DBMS engine and access it via a
customised error handler. So in your code you would have something like:

$result = mysql_query($this->query, $this->dbconnect) or
trigger_error($this, E_USER_ERROR);

For details on how to customise the error handler take a look at
http://www.tonymarston.co.uk/php-mys...orhandler.html

--
Tony Marston

http://www.tonymarston.net
http://www.radicore.org

"lawrence k" <lk******@geocities.comwrote in message
news:11**********************@e3g2000cwe.googlegro ups.com...
>
I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?

Which of these two functions is better, the one with error checking or
the one without?

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
}
}

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
if ($result) {
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
if (is_array($row)) {
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
} else {
reportError("In getWeblogEntries, the function getRow
failed to return an array on the $i iteration.");
}
}
} else {
reportError("In getWeblogEntries, the query to the database
failed.");
}
}

My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere. I've taken over
PHP projects, started by other programmers, that had no error checking
and no comments, and such projects are always a big pain in the neck. I
lose time playing Sherlock Holmes, trying to track down where a
function's parameter first originates and why it's in use. I'd rather
have a comment on it, and error message for when the wrong thing is
passed in. Obviously this slows development. Is there any concensus
among developers about what is the best approach? I think whatever is
cheapest for the client should be considered the best approach, but it
seems to me cheapest-in-the-short-term is quite different from
cheapest-in-the-long-term.

Sep 2 '06 #6
Would you call a PHP programmer that does not check for errors a
professional then?

Most web sites developed with PHP are a kind of "robot" that represent a
company or person. Think of any web shop, for example. People pay real
money when buying things through the internet.

Nobody is perfect, off course. So people do make mistakes. But when my
"robot" makes a mistake (better said: discovers a mistake that I have
made), I would like to know about it. So it saves any errors into a
table or file, or sends it to me by e-mail.
... I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself.
I am totally flabbergasted by this. First, these error messages are for
you, the programmer. They can contain sensitive data about table names,
file names, etc. You don't want to show the internal PHP message to a user.
Furthermore, because these messages are meant for you, you will miss
them if they are only shown to a user. Especially if they are hard to
reproduce.
I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development.
What a load of crap. On what planet his this person been for the last
decade? PHP is an object-oriented language that is still backwards
compatible with hacker-style or "blind panic" type of programming, but
has outgrown it since long.
To speed up development, I have written classes that I share between
projects (using SourceSafe or Subversion). So, database handling is
something I have written just once. Error logging is something I have
written just once. And so on. If you want to speed up development,
prepare your code for reuse.
Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?
I already answered that one, I think. Besides that, I write unit tests
to get a feeling of the quality of my code. If error handling is already
thought bad, writing unit tests will probably cost you your job.
But I still recommend them. They force you to program in a much more
modular way, and they take away a lot of complexity when a project gets
larger.

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
I would check mysql_errno($connection) to see if MySQL really was told
something it could understand. If not, make sure a developer gets the
message returned by mysql_error($connection).
My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere. I've taken over
PHP projects, started by other programmers, that had no error checking
and no comments, and such projects are always a big pain in the neck. I
lose time playing Sherlock Holmes, trying to track down where a
function's parameter first originates and why it's in use. I'd rather
have a comment on it, and error message for when the wrong thing is
passed in.
There's even a better way: use good names instead of comments. Lots of
editors feature some autocomplete or intellisense that show you the
variable name. Consider:

function item($i) // $i is a one based integer

versus

function item($intOneBasedIndex)

In the last case, your editor will show this "comment" when you use it,
not just when you define it.
Obviously this slows development.
Huh? You did all the Sherlock Holmesing in your own free time then? I
also worked for a company that thought all quality as bad and too
expensive. Most of my tasks involved writing or correcting two lines of
code, and took at least three days trying to find which lines or where I
could insert them. Now THAT is slowing down development.
Is there any concensus
among developers about what is the best approach? I think whatever is
cheapest for the client should be considered the best approach, but it
seems to me cheapest-in-the-short-term is quite different from
cheapest-in-the-long-term.
I think you get the point.

Best regards
Sep 2 '06 #7
lawrence k wrote:
I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?
Obviously either someone who was entirely clueless or a very sloppy
programmer. In either case there is no way I would want to work with
anyone with that attitude.
Which of these two functions is better, the one with error checking or
the one without?

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
}
}

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
if ($result) {
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
if (is_array($row)) {
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
} else {
reportError("In getWeblogEntries, the function getRow
failed to return an array on the $i iteration.");
}
}
} else {
reportError("In getWeblogEntries, the query to the database
failed.");
}
}

Definitely the second one is better. Additionally, you've taken the
extra step of hiding the MySQL error message itself - which is a good thing.

Those messages are meant for you, the programmer, and can contain
information useful to hackers. It's much better to keep that
information private.

Although I do generally take the extra step of writing the MySQL message
to an error log.
>
My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere. I've taken over
PHP projects, started by other programmers, that had no error checking
and no comments, and such projects are always a big pain in the neck. I
lose time playing Sherlock Holmes, trying to track down where a
function's parameter first originates and why it's in use. I'd rather
have a comment on it, and error message for when the wrong thing is
passed in. Obviously this slows development. Is there any concensus
among developers about what is the best approach? I think whatever is
cheapest for the client should be considered the best approach, but it
seems to me cheapest-in-the-short-term is quite different from
cheapest-in-the-long-term.
Yes. Do all of your own error checking, write messages you aren't
afraid of your client or a website user seeing, and log more sensitive
information to a file for later reference.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Sep 2 '06 #8
lawrence k wrote:
My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere.
I think you're missing a basic point. Error messages and code comments
are form of human communication. The merit of saying something versus
not saying something obviously depends on how the listener makes use of
the information communicated. Aimless verbosity does no one any good.

If we look at the messages in your example:

"In getWeblogEntries, the function getRow failed to return an array
on the $i iteration."
"In getWeblogEntries, the query to the database failed."

Say I'm a programmer picking up your project, how would I respond?
Well, all I know is that there is something wrong in getWeblogEntries.
So I do a search for getWeblogEntries, open the file and look. Even
without your messages though I would have done the exactly the same
thing. The messages emitted by PHP gives me the file path and line
number, so they actually do a better job.

In programming as in real life, don't open your month unless you have
something worthwhile to say. A few judicious utterances is better than
a constant stream of banalities.

Sep 2 '06 #9
lawrence k wrote:
<snip>
Which of these two functions is better, the one with error checking or
the one without?
<snip>
function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
if ($result) {
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
if (is_array($row)) {
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
} else {
reportError("In getWeblogEntries, the function getRow
failed to return an array on the $i iteration.");
}
}
} else {
reportError("In getWeblogEntries, the query to the database
failed.");
}
}
<snip>

As someone has already mentioned, it would be better to capture
the errors via custom error handler which should clear all the texts
that are ready for output but to show the friendly message something
like "Script error occured, please retry later" on any fatal errors.
The error level can be triggered via trigger_error(). All errors can be
logged in a log file for the programmer to look into that later (but
the same error message shouldn't be shown to user), FWIW,
<http://groups.google.com/group/alt.comp.lang.php/msg/af1455b3c817fc0f>

Out of interest, if the script shown above is not intended to be
the example, it has some pitfalls: 1. selecting all rows is kind of
evil, 2. extract, is_array, etc are overkill.

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/

Sep 2 '06 #10

Jerry Stuckle wrote:
lawrence k wrote:
I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?

Obviously either someone who was entirely clueless or a very sloppy
programmer. In either case there is no way I would want to work with
anyone with that attitude.
Actually the fellow (whom I took the project over from) is well
regarded in the town I live. He is mostly a C programmer. He's
apparently done quite a few projects (in C) that were quite successful.
Myself and a co-worker wondered if his PHP work was merely an
expression of haste, or design. From conversation, I was given the
sense the answer was "design". But I lost time figuring out his code,
and I feel that some comments would have done a lot to speed my
comprehension. I write error checks to make life easier for the next
programmer.

Sep 2 '06 #11
lawrence k wrote:
Jerry Stuckle wrote:
>>lawrence k wrote:
>>>I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?

Obviously either someone who was entirely clueless or a very sloppy
programmer. In either case there is no way I would want to work with
anyone with that attitude.


Actually the fellow (whom I took the project over from) is well
regarded in the town I live. He is mostly a C programmer. He's
apparently done quite a few projects (in C) that were quite successful.
Myself and a co-worker wondered if his PHP work was merely an
expression of haste, or design. From conversation, I was given the
sense the answer was "design". But I lost time figuring out his code,
and I feel that some comments would have done a lot to speed my
comprehension. I write error checks to make life easier for the next
programmer.
Yep, I've had "hot shots" like that on teams before. Quite frankly, I
haven't been that impressed.

Give me a good programmer who checks response codes, comments code and
follows a good design any day.

I do remember on rather large (15 programmers/1 year) project I managed
several years ago. One of them was one of these hot shots who was also
"well regarded" by management. But he wouldn't comment his code,
wouldn't submit his code for code reviews, wouldn't change his code when
it was reviewed - you get the idea.

I finally had to take it up with his manager. His manager's comments
were something on the order of "that's the way he is - you'll have to
live with it".

The only thing was - my contract made me responsible for the project.
To make a long story short, there was a lot of hemming and hawing on the
manager's part. But my contract gave me responsibility for successful
completion of the project - and control over the people on it. They
finally had to take him off the project.

And you know what? The project finished on time and within budget. And
the people on the project were much happier. Seems a lot of them had
problems with this "hot shot" - he wrote code that was fast and
efficient, but no one else could understand it, either.

Interestingly enough, when the company found the project ran so much
better with this guy, his reputation wasn't quite so hot.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Sep 3 '06 #12
lawrence k wrote:
[should I write my own error checking?]
I believe other posters have given pretty firm answers to that... let me
just make a suggestion in the name of readability.

Instead of writing

if ( ! $thereIsAnError ) {
...
if ( ! $thereIsAnotherError ) {
...
} else {
// handle the second problem
} else {
// handle the first problem
}

use

if ($thereIsAnError)
handle_error($thereIsAnError);
...

As you can see, this puts the error checking first in the file, and it also
prevents the unholy levels of if/else nesting that can occur if you use
if/else blocks for all of your error checking. Assuming that handle_error()
will exit, you can just add a quick, two-line test to check for and handle
an error; there's no need to wrap the entire rest of the code in an else { }
block.

HTH,
--
Benjamin D. Esham
bd*****@gmail.com | AIM: bdesham128 | Jabber: same as e-mail
'I wish I had never come here, and I don't want to see no more
magic,' he said and fell silent.
— Sam in /The Fellowship of the Ring/
Sep 3 '06 #13
Following on from Chung Leong's message. . .
>lawrence k wrote:
>My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere.

I think you're missing a basic point. Error messages and code comments
are form of human communication. The merit of saying something versus
not saying something obviously depends on how the listener makes use of
the information communicated. Aimless verbosity does no one any good.

If we look at the messages in your example:

"In getWeblogEntries, the function getRow failed to return an array
on the $i iteration."
"In getWeblogEntries, the query to the database failed."

Say I'm a programmer picking up your project, how would I respond?
Well, all I know is that there is something wrong in getWeblogEntries.
So I do a search for getWeblogEntries, open the file and look. Even
without your messages though I would have done the exactly the same
thing. The messages emitted by PHP gives me the file path and line
number, so they actually do a better job.

In programming as in real life, don't open your month unless you have
something worthwhile to say. A few judicious utterances is better than
a constant stream of banalities.
Aha! Some sense from Chung Leong
* It is correct that programmers go WCPGW [1] like clocks go tick and
cows go moo.
* But it doesn't necessarily follow that the way to deal with this is
what the OP called 'error checking'.
* Distinguish between
- Errors and exceptions (Exceptions are where something doesn't work
as normal. Errors are where an incorrect result/action is obtained.)
- Detection, reporting and handling

For example if (in the UK) I ask for a date then I want it in
day-month-year order. But you might be used to m-d-y and input to my
form like that.
"1-1-2006" is not an error or an exception
"10-1-2006" is an error (10th Jan accepted though you meant 1st
October)
"1-15-2006" is an exception (you meant Jan 15th but my validation says
there isn't a 15th month)
(Not being able to handle "Unknown" or "2006" may be /faulty/ design.)
I'll leave readers to mull over the d,r,h issues with this example....

* Beware of tests that are not watertight, opaque or make a shot at, but
don't pin down the conditions that matter. In the example code given
<quote>
$row = getRow($result);
if (is_array($row)) {
extract($row);
</quote>
What does the function getRow() return? Here I'll assume it is an alias
for mysql_fetch_array() which returns FALSE if there's a problem. So if
the result is to be tested it is good practice to test according to the
signals in the documentation.
if(FALSE===getRow($result)){

It is the result of extract() that matters in the processing. (Also
it's a handy point to put in an assertion-style test along the lines of
if(3==extract($row)){ // headline,date,mainContent

* Beware of complex 'error' handling introducing new problems.

* Don't forget try...catch

So, to conclude: IMHO the original poster should get A for effort but
would be better off with simply reporting a failure at the end of the
routine. I'd do this like:

function ReportWeblogEntries() {
// ------------------------------------------------
// Prints up to last 30 rows of Weblogs table (latest at top)
// Returns actual number of entries or -ve diagnostic for failure
// ------------------------------------------------
$actualLogCount = -1; // default = failure diagnostic
$query = "SELECT * FROM weblogs ORDER BY date DESC";
if($rows=mysql_query($query)){ // fails on error
$actualLogCount = mysql_num_rows($rows);
// trap stupid number of rows inside loop
for ($i=1; $i <= $actualLogCount; $i++) { // note change of
index base
if($i>30){ // ENOUGH! STOP!
$excess = $actualLogCount-($i-1); // how many still left
to print
print("<hr><b>There are $excess more items (not
shown)</b>");
break;
}
if($row = getRow($rows)){ // can never fail!
if(3==extract($row)){ //headline,date,mainContent -vars
print( "<h1>$headline</h1>
<h7>$date</h7>";
<div
class=\"mainContent\">$mainContent</div>");
}else{
$actualLogCount = -2; // diagnostic for can never
happen
}else{
$actualLogCount = -3; // diagnostic for can never
happen
}
} // end of step through results loop
mysql_free_result($rows);
}
return $actualLogCount; // normally 0 or +ve for no of rows
}

Note from my version that the function returns /diagnostics/ from the
very first line. Since you have to look at the code to understand
exactly what's happening you don't need more than an alert and possibly
a pointer.

Note that my version frees the database resource under 'all' conditions
that matter.

Note that for the purposes of this exercise I've said "Nobody can
possibly deal with more than 30 items at a time" - so showing more would
be a /fault/ in the design.

Note the original function had a misleading name.

So spend less time on fancyfying the bits that you think might go wrong
and more on discovering what the important failure modes are; and
understanding the context in which the information is going to be used.

[1]What could possibly go wrong

--
PETER FOX Not the same since the bookshop idea was shelved
pe******@eminent.demon.co.uk.not.this.bit.no.html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.demon.co.uk>
Sep 3 '06 #14

I'm not so sure that it is faster or cheaper to write sloppy or code.

Most project have a life that extends much longer than the end of
development, so when you add up the debugging and maintenance over a
period of months or years, then the better and more fully documented
code will win every time.

However, everything should be done in moderation. Your example
shows maybe too much error checking and too little comments.

Spend less time writing error checking and more time documenting your
code. Search and Replace does wonders with this so you only write the
documentation comment once per procedure and replace it thruout the
code.



On 1 Sep 2006 21:29:16 -0700, "lawrence k" <lk******@geocities.com>
wrote:
>
I've made it habit to check all returns in my code, and usually, on
most projects, I'll have an error function that reports error messages
to some central location. I recently worked on a project where someone
suggested to me I was spending too much time writing error messages,
and that I was therefore missing the benefit of using a scripting
language. The idea, apparently, is that the PHP interpreter writes all
the error messages that are needed, and that I shouldn't write such
code myself. I was given the impression that if I needed extensive
error checking, or strict typing, then I should use a real language,
like Java, but if I'm going to use a scripting language like PHP or
Ruby, then I should leave errors to the interpreter, since the whole
point of using scripting languages is speed of development. Has anyone
else heard this argument, and do you agree with it? I'm wondering how
other PHP programmers handle error messages. Check everything or leave
it to the PHP interpreter to tell you when there is an error?

Which of these two functions is better, the one with error checking or
the one without?

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
}
}

function getWeblogEntries() {
$query = "SELECT * FROM weblogs";
$result = mysql_query($query);
if ($result) {
$howManyWeblogEntries = mysql_num_rows($result);
for ($i=0; $i < $howManyWeblogEntries; $i++) {
$row = getRow($result);
if (is_array($row)) {
extract($row);
echo "<h1>$headline</h1>";
echo "<h7>$date</h7>";
echo "<div class=\"mainContent\">$mainContent</div>";
} else {
reportError("In getWeblogEntries, the function getRow
failed to return an array on the $i iteration.");
}
}
} else {
reportError("In getWeblogEntries, the query to the database
failed.");
}
}

My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere. I've taken over
PHP projects, started by other programmers, that had no error checking
and no comments, and such projects are always a big pain in the neck. I
lose time playing Sherlock Holmes, trying to track down where a
function's parameter first originates and why it's in use. I'd rather
have a comment on it, and error message for when the wrong thing is
passed in. Obviously this slows development. Is there any concensus
among developers about what is the best approach? I think whatever is
cheapest for the client should be considered the best approach, but it
seems to me cheapest-in-the-short-term is quite different from
cheapest-in-the-long-term.
Sep 3 '06 #15
My own feeling, obviously, is that it is better to error check
everything, and to write extensive comments everywhere. I've taken over
PHP projects, started by other programmers, that had no error checking
and no comments, and such projects are always a big pain in the neck. I
lose time playing Sherlock Holmes, trying to track down where a
function's parameter first originates and why it's in use. I'd rather
have a comment on it, and error message for when the wrong thing is
passed in. Obviously this slows development. Is there any concensus
among developers about what is the best approach? I think whatever is
cheapest for the client should be considered the best approach, but it
seems to me cheapest-in-the-short-term is quite different from
cheapest-in-the-long-term.
In my personal opinion and experience, if I were a project manager and
I've heard the words "php will handle errors for you, why bother?" from
any of the programmers I work with, I would fire that person on spot.
It's HORRIBLE practice and it leads to lots of crap php code out there
and also the "not serious programmer" stereotype about php developers
(enforced mostly by java and c# folks - who (you've guessed it :) handle
their errors and exceptions). So my advice is handle all the errors, USE
the exceptions as much as you can, log errors for after analysis but
don't reinvent the wheel (e.g. don't reinvent the text of DB error
messages, just handle them and give them context).

--

B.r.K.o.N.j.A = Bionic Robotic Knight Optimized for Nocturnal Judo and
Assasination
Sep 3 '06 #16
Peter Fox wrote:
* Distinguish between
- Errors and exceptions (Exceptions are where something doesn't work
as normal. Errors are where an incorrect result/action is obtained.)
Making that distinction is important. That's where the colleague of the
OP erred. Error handling/reporting in PHP is different not because it's
a scripting language. It's different because it's designed for web
application. Unlike desktop apps, the operating environment for web
apps is usually controlled by the programmer. That allows PHP to make
the assumption that any error encountered is a programming error and
accordingly, throwing up a message to inform the programmer. Take
fopen() for instance. In a desktop app it could fail in normal
circumstances (end-user mistake etc.) In a PHP app, when it fails it
usually means the programmer did something wrong, as the file being
opened can either be a file that's part of the app or a file uploaded.
The guy is correct is saying that it's pointless to do what PHP does
for you already.
For example if (in the UK) I ask for a date then I want it in
day-month-year order. But you might be used to m-d-y and input to my
form like that.
That's not a terribly good example, I must say. User errors should
always be expected. Handling them is part of a application's basic
functionality.
What does the function getRow() return? Here I'll assume it is an alias
for mysql_fetch_array() which returns FALSE if there's a problem. So if
the result is to be tested it is good practice to test according to the
signals in the documentation.
if(FALSE===getRow($result)){
I didn't mention it since it's just an example, but there is really no
way for that condition to arise. If mysql_num_rows() succeeds, then
mysql_fetch_array() cannot fail, since the rows are in memory already.
So spend less time on fancyfying the bits that you think might go wrong
and more on discovering what the important failure modes are; and
understanding the context in which the information is going to be used.
The only real failure modes are (a) the DB connection is bad, or (b)
the table weblogs is missing or don't have the right column names.
PHP's error reporting mechanism would inform you of both. If one wants
to be helpful, then say something that's actually informative like "the
database schema is incorrect, run create_tables.php to create the
database." Otherwise, if all you're writing are messages in the vein of
"an error happened," then you might as well leave it to PHP.

Sep 4 '06 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

176
by: basecamp | last post by:
just checking the average age of programmers using this group -- thanks
55
by: amanda992004 | last post by:
Excluding the factors of the brain capability, i.e I am not asking about this factor, if you are a single, aside from enjoying coding or debugging, how do you make time to eat properly, i.e...
65
by: Nikolas Hagelstein | last post by:
Hi, First of all: i spend a lot of time on thinking and researching about how to make developing webapplications with php a more structured/systematic thing. I even fancied to switch over to...
8
by: Keith Smith | last post by:
I know this is a little off topic but I hope it is still acceptable to this forum. Please read this carefully. I am not looking for a quick answer - I am hoping to find someone who has been in my...
25
by: moondaddy | last post by:
I have an application where users need to upload images and in my web.config file I have a setting like this: <httpRuntime maxRequestLength="512" /> Which restricts image larger than 500k from...
669
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic...
18
by: firewoodtim | last post by:
I need some help in furthering my education in OOP. I have developed a set of PHP scripts that I use in a fairly sophisticated database driven website, but I am not proud of the rather amateurish...
10
by: happyse27 | last post by:
Hi All, I got this apache errors(see section A1 and A2 below) when I used a html(see section b below) to activate acctman.pl(see section c below). Section D below is part of the configuration...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, youll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Shllpp 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.