Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

how do professional PHP developers handle defaults for function parameters?

2 views
Skip to first unread message

lawrence k

unread,
Jul 6, 2007, 5:35:20 PM7/6/07
to

I'm working in PHP 4. Even if a parameter is mandatory, I nearly
always give it a default value of "false". Then I print an error
message if someone who is calling my function forgot the mandatory
parameter:

function outputHtmlToShowFile($fileName=false) {
if ($fileName) {
// code goes here
} else {
echo "In outputHtmlToShowAFile() the code expected the first
parameter to be a file name, but instead the value was false";
}
}

How do others handle default parameter values?

I've been avoiding this:

function outputHtmlToShowFile($fileName) { }

because if I do this and someone forgets to pass a file name to the
function, then the PHP parser issues an error. I've been assuming
that relying on the PHP parser to write my error messages for me is
unprofessional. Does anyone else feel that way?

Iván Sánchez Ortega

unread,
Jul 6, 2007, 5:53:55 PM7/6/07
to
lawrence k wrote:

> because if I do this and someone forgets to pass a file name to the
> function, then the PHP parser issues an error. I've been assuming
> that relying on the PHP parser to write my error messages for me is
> unprofessional. Does anyone else feel that way?

It's not unprofessional. It is over-engineered and unneccesary, tough.

If "someone" forgets to pass you a parameter, it is because:
- They haven't looked at your function definition (they are bad programmers)
- You haven't specified that they have to pass you a parameter (*you* are a
bad programmer)

So:
- Document your code (use doxygen/phpdoc/whatever)
- Tell other programmers you work with how your code works, and what they
can expect from it.


The "professional" way to go is to write specs on paper, then have everyone
read them, then assume everybody will be following them.


And, finally: do not attempt to do some work that a interpreter or a
compiler does better than you. And don't try implementing technical
solutions to non-technical problems.

Hope that helps,
--
----------------------------------
Iván Sánchez Ortega -ivansanchez-algarroba-escomposlinux-punto-org-

Un ordenador no es un televisor ni un microondas, es una herramienta
compleja.

ZeldorBlat

unread,
Jul 6, 2007, 10:49:24 PM7/6/07
to
On Jul 6, 5:53 pm, Iván Sánchez Ortega <ivansanchez-...@rroba-

As a "professional" PHP programmer I second Iván's comments.

pangea33

unread,
Jul 7, 2007, 12:06:43 AM7/7/07
to
My post got longer and longer as my thoughts came together on this
subject. The gist of my claim is that you shouldn't build something as
FRAGILE as a function that breaks if there are argument variations,
when you can simply build a more robust function in the first place.
The final answer? Pass in a structure rather than require ongoing
maintenance of all references to a function so as to avoid an error
you never should have gotten in the first place.

As another "professional" PHP programmer I have to disagree with the
responses the OP has been getting. An unchanging set of arguments
makes sense when you're working with a small codebase, but sometimes
one might want to call a function from multiple locations that have
different requirements. Suppose you have a PHP function that creates
and executes a MySQL select query. A search page might be designed to
support text matches on a couple columns, only to find out that
additional fields need to be supported for generating reports.

There are two options here. You can create your function with a static
set of arguments that fails when it is called with missing parameters,
then counter with the retort that the dude who called it was a "bad
programmer." This is totally useless when your production sites are
throwing unnecessary errors. The second option is to pass in a
structure and simply check for various optional arguments.

When I need to expand the capabilities of an existing function to
support new requirements, I simply have to make a modification to the
UDF rather than to all existing code. You might disagree with me, but
I can guarantee it's a lot easier to maintain a site when you don't
have to touch all references to a function whenever you want to
improve it.

Any "professional" programmer who relies on the vast repository of
*documentation* present in most projects in industry is either an
idealistic novice, or EXTREMELY fortunate for the places they've
worked.

Here is a brief example of my technique...

>From a calling page:
--------------------
if ($rsVideoListObj->videolistid > 0) {
$videoListVideoStruct->videolistid = $rsVideoListObj->videolistid;
$rsVideoListVideos = getVideoListVideos($videoListVideoStruct);
}

>From My UDF:
------------
// get videos for videolist
function getVideoListVideos($inStruct) {
$queryStr = " SELECT vlj.recordid, vlj.videolistid, vlj.videoid ";
if( isset($inStruct->getVideoInfo) ) {
$queryStr .= " , v.videolinkurl, v.showname, v.episodename,
v.createdby, v.videocaption, v.videoiconimage ";
$queryStr .= " , v.regionid, v.urlforsite, v.r2rmediasiteurl,
v.googleanalytics ";
}
$queryStr .= " FROM videolistvideojoin vlj ";
if( isset($inStruct->getVideoInfo) ) {
$queryStr .= " LEFT JOIN videos v ON vlj.videoid = v.videoid";
}

$queryStr .= " WHERE 0=0 ";
if( isset($inStruct->videolistid) ) {
$queryStr .= " AND vlj.videolistid = ".$inStruct->videolistid;
}
if( isset($inStruct->videoid) ) {
$queryStr .= " AND vlj.videoid = ".$inStruct->videoid;
}
if( isset($inStruct->orderby) ) {
$queryStr .= " ORDER BY ".$inStruct->orderby;
}

$rsData = mysql_query($queryStr);
if ( mysql_error() && $_SESSION["enabledebug"] ) {
echo mysql_error();
}

$returnVal = $rsData;

return $returnVal;

Iván Sánchez Ortega

unread,
Jul 7, 2007, 5:13:33 AM7/7/07
to
pangea33 wrote:

> As another "professional" PHP programmer I have to disagree with the
> responses the OP has been getting.

And now I have to disagree with you ;-)

> An unchanging set of arguments makes sense when you're working with a
> small codebase, but sometimes one might want to call a function from
> multiple locations that have different requirements.

Wrong approach, IMHO. That sounds like building a big, ugly monolithic
function, at which you can throw everything you want.

The "right" way to go is to go modular. Abstract complexity in small
modules.

> Suppose you have a PHP function that creates and executes a MySQL select
> query.

Yes, it's called Zend_Db::query() ;-)

> A search page might be designed to support text matches on a couple
> columns, only to find out that additional fields need to be supported for
> generating reports.

Then you should have one fnuction that gets a 'search text' as its only
parameter, and calls the generic (and private) query-building function. For
additional fields, use another function that receives different parameters
and calls the generic query-building function...


> There are two options here. You can create your function with a static
> set of arguments that fails when it is called with missing parameters,
> then counter with the retort that the dude who called it was a "bad

> programmer." [...] The second option is to pass in a


> structure and simply check for various optional arguments.

OK, suppose I call fopen() with the wrong arguments. The two options here
are:
- I was a bad programmer for not reading the fopen() documentation
- The guys that programmed fopen() (and libc) are stupid for not accepting a
variable list of arguments


> When I need to expand the capabilities of an existing function to
> support new requirements, I simply have to make a modification to the
> UDF rather than to all existing code.

When I need to expand the capabilities of the existing *system*, I create
new functions that call the underlying ones. Monolithic is bad, modular is
good, right?

> You might disagree with me, but I can guarantee it's a lot easier to
> maintain a site when you don't have to touch all references to a function
> whenever you want to improve it.

It's much easier to add things at the top and not touching the working code
at all :-D

--
----------------------------------
Iván Sánchez Ortega -ivansanchez-algarroba-escomposlinux-punto-org-

Habit is habit, and not to be flung out of the window by any man, but coaxed
down-stairs a step at a time.
-- Mark Twain, "Pudd'nhead Wilson's Calendar

Jerry Stuckle

unread,
Jul 7, 2007, 9:21:19 AM7/7/07
to
pangea33 wrote:

<snip>

>
> Any "professional" programmer who relies on the vast repository of
> *documentation* present in most projects in industry is either an
> idealistic novice, or EXTREMELY fortunate for the places they've
> worked.
>

Sorry, I completely disagree here. I've managed projects from a single
programmer (me) to over 100 programmers.

Any "professional" programmer will include the documentation as part of
the project. It's part of the job. And anyone who doesn't document
isn't much of a programmer. Or, on a larger project, most of the design
will be created by designers.


> Here is a brief example of my technique...
>
>>From a calling page:
> --------------------
> if ($rsVideoListObj->videolistid > 0) {
> $videoListVideoStruct->videolistid = $rsVideoListObj->videolistid;
> $rsVideoListVideos = getVideoListVideos($videoListVideoStruct);
> }
>

And I agree with Iván. You're approach looks huge and unwieldy. Much
better to make it more modularized.

And P.S. - please don't top post.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstu...@attglobal.net
==================

Sanders Kaufman

unread,
Jul 7, 2007, 6:19:07 PM7/7/07
to
pangea33 wrote:

> Any "professional" programmer who relies on the vast repository of
> *documentation* present in most projects in industry is either an
> idealistic novice, or EXTREMELY fortunate for the places they've
> worked.

Amen.
I write from specs, I write my own code, and then I use my IDE's
documentation utility to document it.

STILL - I keep finding myself forgetting how my own functions are
supposed to work.

Sanders Kaufman

unread,
Jul 7, 2007, 7:19:56 PM7/7/07
to
Jerry Stuckle wrote:

> Any "professional" programmer will include the documentation as part of
> the project. It's part of the job. And anyone who doesn't document
> isn't much of a programmer. Or, on a larger project, most of the design
> will be created by designers.

Like the lawyers say - "If it didn't happen on paper, it didn't happen".

Jerry Stuckle

unread,
Jul 7, 2007, 9:16:24 PM7/7/07
to

I write from specs - which include function calls, etc. When I find a
function needs to change the doc changes with it.

And that's how I run the multi-programmer projects I manage, also.

No spec is perfect - there are going to be changes to it. But those
changes need to be documented, also.

The result is a set of doc not a lot unlike what PHP has for their doc.

gosha bine

unread,
Jul 7, 2007, 10:12:24 PM7/7/07
to
pangea33 wrote:
> My post got longer and longer as my thoughts came together on this
> subject. The gist of my claim is that you shouldn't build something as
> FRAGILE as a function that breaks if there are argument variations,
> when you can simply build a more robust function in the first place.

If something is going to fail, let it fail. The sooner it fails, the
more chances to discover and fix the bug.

> An unchanging set of arguments
> makes sense when you're working with a small codebase, but sometimes
> one might want to call a function from multiple locations that have
> different requirements.

In a large project it's more likely that you use OOP rather than bare
functions. In OOP, when you need to modify existing functionality, you
extend or aggregate, but not rewrite it.

> There are two options here. You can create your function with a static
> set of arguments that fails when it is called with missing parameters,
> then counter with the retort that the dude who called it was a "bad programmer."

Yes, someone who calls a function with wrong arguments is a bad (or
simply careless) programmer.

> This is totally useless when your production sites are
> throwing unnecessary errors.

You do test your software before it goes production, don't you?

>
> When I need to expand the capabilities of an existing function to
> support new requirements, I simply have to make a modification to the
> UDF rather than to all existing code.

Again, the decent use of OOP might help here. When you need a new
feature, just extend the baseclass, and if your classes are properly
decoupled, this change won't affect the rest of the program.

>
> Any "professional" programmer who relies on the vast repository of
> *documentation* present in most projects in industry is either an
> idealistic novice, or EXTREMELY fortunate for the places they've
> worked.
>

That's the point where I tend to agree with you. Documentation should
document behaviour, not syntax. The best documentation for the syntax is
the source itself.


--
gosha bine

extended php parser ~ http://code.google.com/p/pihipi
blok ~ http://www.tagarga.com/blok

Jerry Stuckle

unread,
Jul 7, 2007, 11:35:17 PM7/7/07
to
gosha bine wrote:

> pangea33 wrote:
>>
>> Any "professional" programmer who relies on the vast repository of
>> *documentation* present in most projects in industry is either an
>> idealistic novice, or EXTREMELY fortunate for the places they've
>> worked.
>>
>
> That's the point where I tend to agree with you. Documentation should
> document behaviour, not syntax. The best documentation for the syntax is
> the source itself.
>
>

And this is where I disagree with you. How a function goes about doing
something is immaterial. What is important is the syntax of calling the
function and an *overview* of the behavior.

Do you use the PHP source code to figure out how to call fopen()? Do
you even know how fopen() does its job?

All you really need is the same thing that's in the PHP doc - function
name, parameters, an overview of what it does (NOT how it goes about
doing its job) and return value.

IOW, KISS. Trying to understand how functions work is unnecessary
detail - detail which will get you confused even on a relatively small
project.

Henk verhoeven

unread,
Jul 10, 2007, 3:40:18 PM7/10/07
to
lawrence k wrote:
> How do others handle default parameter values?

I guess you mean "how do others handle missing parameters?"

Well, on the development server my error handler will produce a walkback
so that i can see where the call was coming from.

Example:

/** class of the user interface component being called upon
class PntFilterFormPart extends PntPagePart {

*// function that will be called */
function setImplicitCombiFilter(&$combiFilter) {

(....)

/** Front controller class /*
class Site extends PntSite {

function setErrorHandler() {
includeClass('ErrorHandler');
$this->errorHandler =& new ErrorHandler();
$this->errorHandler->startHandling();
}

(....)

/* class of the actual controller producing the requested page, contais
the errorneous call */
class MclUrenSearchPage extends ObjectSearchPage {
function &getFilterFormPart() {
$part =& parent::getFilterFormPart();

$part->setImplicitCombiFilter(); //parameter missing
//should have passed an instance of PntSqlCombiFilter

return $part;
}

Output from development server:

E_WARNING: 'Missing argument 1 for
PntFilterFormPart::setImplicitCombiFilter(), called in
C:\metaclass\websites\@ndere\webtoko\classes\mcl\project\classMclUrenSearchPage.php
on line 9 and defined' in
C:\metaclass\websites\@ndere\webtoko\classes\pnt\web\parts\classPntFilterFormPart.php
at line 585
Request params:
'pntType'=>'Uren',
'pntHandler'=>'SearchPage',
'pntScd'=>'d',
'PHPSESSID'=>'66381c07e127a5ab7e3309dc27598741'

class function line
-----------------------------------------------------------
PntFilterFormPart setImplicitCombiFilter
MclUrenSearchPage getFilterFormPart 9
PntObjectSearchPage getRequestedObject 75
PntObjectIndexPage initForHandleRequest 41
PntPage handleRequest 122
PntSite forwardRequest 203
array('pntType'=>'Uren', 'pntHandler'=>'SearchPage', 'pntScd'=>'d',
'PHPSESSID'=>'66381c07e127a5ab7e3309dc27598741')

PntSite handleRequest 194
- - 5 project\index.php


BTW, passing objects by reference is standard procedure in php4. It
excludes the use of defaults.

Greetings,

Henk Verhoeven,
www.phpPeanuts.org.

pangea33

unread,
Jul 10, 2007, 9:04:52 PM7/10/07
to
On Jul 10, 3:40 pm, Henk verhoeven <news1@phpPeanuts_RemoveThis.org>
wrote:


There was a lot of good feedback in this thread, and I am not the sort
of self-absorbed developer who is closed to the viewpoints of others.
A lot of you have made me rethink portions of my original post. Thanks
for keeping it clean and for giving some alternatives rather than
simply bashing. Hopefully some others will weigh in on the subject too.

lawrence k

unread,
Jul 13, 2007, 1:04:22 PM7/13/07
to
On Jul 7, 10:12 pm, gosha bine <stereof...@gmail.com> wrote:
> pangea33 wrote:
> > My post got longer and longer as my thoughts came together on this
> > subject. The gist of my claim is that you shouldn't build something as
> > FRAGILE as a function that breaks if there are argument variations,
> > when you can simply build a more robust function in the first place.
>
> If something is going to fail, let it fail. The sooner it fails, the
> more chances to discover and fix the bug.

That's an interesting reply. Do you do any error checking at all in
your code? If so, what do you error check for?

lawrence k

unread,
Jul 13, 2007, 1:17:02 PM7/13/07
to
On Jul 7, 10:12 pm, gosha bine <stereof...@gmail.com> wrote:
> pangea33 wrote:
> > There are two options here. You can create your function with a static
> > set of arguments that fails when it is called with missing parameters,
> > then counter with the retort that the dude who called it was a "bad programmer."
>
> Yes, someone who calls a function with wrong arguments is a bad (or
> simply careless) programmer.

"Bad programmer" sounds almost like a moral judgment. Which is fine,
but it wasn't what I was looking for, exactly, with my original post.
I'm looking for what is considered effective. I may have poorly
phrased my concerns. I guess what I'm looking for is other people's
opinions on whether PHP's built-in error messages are an effective way
to manage large projects. (For me, a large project is one that has 10
people working on it.) I was writing long error messages because I
thought they provided more information to my teammates. Do you feel
PHP's error messages are effective in communicating to others what
problems might arise from the code?

It seems to me that every project will have errors, and somehow those
errors must be fixed. We all hope to keep the error-fixing time to a
minimum. Does it save any time to write a lot of error messages? If I
don't write error messages, then I put the burden of finding the
problem onto programmer who has called a function with the wrong
number or type of parameters. (The "wrong type" scenario is usually
harder to debug than the "wrong number" scenario.) They can read the
documentation and perhaps figure out the problem. Has time been saved
if I invest time in writing the documentation, and they invest time
reading the documentation? I've wondered sometimes if more time would
be saved simply by writing highly detailed error messages. It isn't a
terrible way to communicate with one's teammates.

> > This is totally useless when your production sites are
> > throwing unnecessary errors.
>
> You do test your software before it goes production, don't you?

Is the argument that error messages can be done away with so long as
one has a unit test for every possible error? I've thought about this.
I'm going to try this on my next project: no error messages, just unit
tests. We'll see how that goes.


lawrence k

unread,
Jul 13, 2007, 1:22:57 PM7/13/07
to
On Jul 7, 9:21 am, Jerry Stuckle <jstuck...@attglobal.net> wrote:
> pangea33 wrote:
>
> <snip>
>
>
>
> > Any "professional" programmer who relies on the vast repository of
> > *documentation* present in most projects in industry is either an
> > idealistic novice, or EXTREMELY fortunate for the places they've
> > worked.
>
> Sorry, I completely disagree here. I've managed projects from a single
> programmer (me) to over 100 programmers.
>
> Any "professional" programmer will include the documentation as part of
> the project. It's part of the job. And anyone who doesn't document
> isn't much of a programmer. Or, on a larger project, most of the design
> will be created by designers.

Do you think that documentation can be replaced by unit tests?


lawrence k

unread,
Jul 13, 2007, 1:24:56 PM7/13/07
to
On Jul 7, 9:21 am, Jerry Stuckle <jstuck...@attglobal.net> wrote:
> pangea33 wrote:
>
> <snip>
>
>
>
> > Any "professional" programmer who relies on the vast repository of
> > *documentation* present in most projects in industry is either an
> > idealistic novice, or EXTREMELY fortunate for the places they've
> > worked.
>
> Sorry, I completely disagree here. I've managed projects from a single
> programmer (me) to over 100 programmers.
>
> Any "professional" programmer will include the documentation as part of
> the project. It's part of the job. And anyone who doesn't document
> isn't much of a programmer. Or, on a larger project, most of the design
> will be created by designers.

I should have rewritten my last question. Let me try again:

"In a hypothetical situation where you only have time and money to
either write documentation for your code, or produce unit tests for
your code, which would you do?"

Sanders Kaufman

unread,
Jul 13, 2007, 12:52:17 PM7/13/07
to
lawrence k wrote:

> "In a hypothetical situation where you only have time and money to
> either write documentation for your code, or produce unit tests for
> your code, which would you do?"


Re-activate my resume.

Jerry Stuckle

unread,
Jul 13, 2007, 9:00:24 PM7/13/07
to

That's like asking if ice cream will replace airplanes. They are two
entirely different things.

Jerry Stuckle

unread,
Jul 13, 2007, 9:01:21 PM7/13/07
to

I would extend the contract so it can be done right. Or refuse it in
the first place.

I don't do contracts which are guaranteed to fail.

Dikkie Dik

unread,
Jul 14, 2007, 9:24:47 AM7/14/07
to
>> Do you think that documentation can be replaced by unit tests?

> That's like asking if ice cream will replace airplanes. They are two
> entirely different things.

No they're not. Unit test demonstrate the behaviour of the code. Both
the good behaviour and the bad. The accepting of a task, the rejecting
if it, and even defaults and special environments.

Any diagrams I have go with the unit tests. For a few good reasons:
- There is no documentation. Even if there is, it is probably outdated,
beyond reach of developers or has never existed. The real problem with
normal documentation is that it is complete decoupled from the code and
has therefore nothing to do with it. Even <language>Doc tags are usually
wrong, as they are just comments and are therefore not compiled. The
code is the documentation, as it is the only thing you can rely on to be
accurate.
- You run the tests before you start your work. So you see them. Every
day. More than once a day. Your face is put into it, in the most heavy
way that does not include violence. You know it exists. You know where
it is. Hey, you might as well read them.

For your info, unit tests are not a collection of red and green lights.
They are a collection of self-explanatory tests, stating what input they
offer, and what output is expected. AND they demonstrate that the code
actually works that way. They also demonstrate "programming flow" like
the need to call special initializers or disposers.

Best regards

Jerry Stuckle

unread,
Jul 14, 2007, 1:40:50 PM7/14/07
to
Dikkie Dik wrote:
>>> Do you think that documentation can be replaced by unit tests?
>
>> That's like asking if ice cream will replace airplanes. They are two
>> entirely different things.
>
> No they're not. Unit test demonstrate the behaviour of the code. Both
> the good behaviour and the bad. The accepting of a task, the rejecting
> if it, and even defaults and special environments.
>
> Any diagrams I have go with the unit tests. For a few good reasons:
> - There is no documentation. Even if there is, it is probably outdated,
> beyond reach of developers or has never existed. The real problem with
> normal documentation is that it is complete decoupled from the code and
> has therefore nothing to do with it. Even <language>Doc tags are usually
> wrong, as they are just comments and are therefore not compiled. The
> code is the documentation, as it is the only thing you can rely on to be
> accurate.

A project without accurate documentation is an incomplete project. All
the projects I've managed have had complete and accurate documentation.

And if the documentation is decoupled from the code, you have the wrong
documentation.

> - You run the tests before you start your work. So you see them. Every
> day. More than once a day. Your face is put into it, in the most heavy
> way that does not include violence. You know it exists. You know where
> it is. Hey, you might as well read them.
>
> For your info, unit tests are not a collection of red and green lights.
> They are a collection of self-explanatory tests, stating what input they
> offer, and what output is expected. AND they demonstrate that the code
> actually works that way. They also demonstrate "programming flow" like
> the need to call special initializers or disposers.
>
> Best regards

I've been programming for almost 40 years now, and consulting for almost
17 years. In that time I've managed a lot of multi-programmer projects,
and I've been involved in many more. I know what documentation and unit
tests are.

And you just proved by your very own statements that they are two
entirely different things.

And BTW - in my projects, all tests are written by an independent group
of testers - according to the documentation at hand. If the
function/class/module/unit fails the test, either the code being tested
is incorrect, or the documentation is incorrect.

Assuming, of course, the test itself isn't in error.

Obviously you've never worked on a project where documentation was a
priority. I know how it is - there are a lot of programmers in the same
position. But every project I've been on which is fully documented has
gone much more smoothly with fewer errors when they have full and
accurate documentation.

R. Rajesh Jeba Anbiah

unread,
Jul 15, 2007, 7:37:16 AM7/15/07
to

IMHO, the default parameters options are for handling the
situation to have default values; it's not meant to professionally
handle exception of missing params.

If you define a function with default params in it, it would
usually mean that the function can be called without any params for
it's default behavior. So, if you want to handle missing params, use
exception/error handler.

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

0 new messages