ejdipq
Last Updated: March 08, 2016
·
485
· padawin
B4b98290bc8c9874f8d69d03f8d345fd

A way to write a method in a class

Couple of days ago, during peer programming session with a colleague, we had to write a method in some class in PHP.
Here's how I proceeded:
We had the method's signature and we were ready to implement it. Just when we were about to do it, I told my colleague: "ok, we have to implement this method, we know what it get in its input and we know what type of data it must return (an array in our case), so first, let's write that". And here's what I wrote:

protected function _myFunction($arg1, $arg2...)
{
    $return = array();

    return $return;
}

And then we started to actually implement the method.
I like this approach of coding, it prevents you from forgetting some parts of the implementation (returning your data for example) and then you can focus on the implementation in itself.

I saw quite a few time to see some code failing or not behaving the way I expect it to just because the return was forgotten.

It is also useful with tests, by implementing first your input and outputs, you can test your code from the beginning (the method must return an (empty) array), and then implementing it and updating the tests.

Say Thanks
Respond

3 Responses
Add your response

14247
D42a7264714dee5006b9c99d2567a320

@datishans I see your point here, one should definitely strive to write code that's idiomatic and self-explanatory and avoid adding obvious comments. It is useful, however, to always put comment blocks before class definitions and methods for the purposes of generating documentation.

over 1 year ago ·
14344
Db1a3ce02ccb657a170a90f35ecc614c

@datishans While I agree with naming things so they're blinding obvious, and with autocompletion in most decent IDEs there's no reason not to, it's worth noting that in loosely typed languages (e.g. PHP) the comment is pretty vital to being able to work out what arguments to supply to a method. As well as for generating documentation (which I rarely bother with in well commented code) it also helps your IDE to display pretty info to you when autocompleting.

@padawin: nice article and definitely a practice I'm going to adopt

over 1 year ago ·
14348
B4b98290bc8c9874f8d69d03f8d345fd

Thanks guys for the contributions and feedbacks ;-)

For the (class|method) comments, I don't always use them (not enough?). I think, as @datishans said, if the signature is clear enough, the comments are not necessary.
I've seen guidelines (used along with phpcs and some hooks) where the comments are mandatory, and in the end that creates a lot of noise in the code, which could be prevented (especially on setters/getters for example...)

over 1 year ago ·