r/PHPhelp • • Aug 27 '21

Documentation

Every once in awhile I'll see the advice "document your code". What does this mean for a PHP programmer writing a small open source project? To make sure to use the "wiki" tab on GitHub? To make sure to use docblocks above each method?

Is it even worth adding docblocks? Don't @param, @return, etc. just duplicate what the top of the method (e.g. function myFunctionName(string $param1, bool $param2): array {) already tells us?

After one adds docblocks, what is the next step, run some kind of software that turns the docblocks into an HTML website?

7 Upvotes

6 comments sorted by

4

u/ThreeForksNoSpoon Aug 27 '21

One of the most important things is that you explain why your code does something.

For example: we all need some "weird hacks" sometime, and just a quick comment like // we don't do [what you'd expect], because [weird behavior you are trying to avoid or whatever] is really helpful. Even if you're the only one working on it, it will prevent you from trying to refactor it in the future, and see your tests fail again. (Or even worse: putting a bug in production.)

Doc blocks can be useful if you explain more about the expected parameters.

For example, when working with a project like WordPress you might have something like this:

/**
* @param $post Can either be a post object, or the ID of a post
**/
function get_data($post)

That's something you can't get from the name of the variable, and naming it $post_object_or_post_id isn't a good idea either.

Same with return values. Maybe you want to explain that something can return false on failure, or an array on success.

Or even false on failure, a string for one value, and an array if there are multiple values.

Note that these things might indicate bad design, but that's besides the point.

3

u/kAlvaro Aug 27 '21

What does this mean for a PHP programmer writing a small open source project?

Most developers hate reading and writing documentation. Commercial software often provides documentation for the sake of having it, typically in the form of a separate set of lengthy documents that many times merely list all the application menus and settings, sometimes even skipping those few items that are less intuitive and would really need to be documented, as a result of having some poor guy in charge of producing such texts for a living.

The great thing about open source projects maintained as hobby is that you can document only what you really want. For me, the bare minimum is a simple paragraph that explains what the software does and what it can be used for (rather than what programming language is written on and what licence it uses), together with a README file that starts by explaining how to set up the software without any prior knowledge.

Apart from that, you should basically document what you would like to know if it was someone else's software. Keep it simple, but useful—there's no boss to complain if you haven't met your daily quota ;-)

function myFunctionName(string $param1, bool $param2): array {) already tells us?

In this precise example you can use @return to clarify what kind of array you get:

@return string[] Available foos in lexicographical order

2

u/CyberJack77 Aug 27 '21

Well, I think you need 2 (or sometimes even 3) types of documentation, no matter the size of the project.

1. Project documentation:

This should tell you what the project does, how to install it, and how it can be used. If it's a library to use in other projects, make sure to include samples on how to use it.

2. Clean, clear, well-structured code with type hints, return types, and proper names for everything:

All code in the project should be well structured, should be using namespaces, or even implement DDD. All methods, variables, classes, interfaces, traits, constants (and everything else) should have clear names that explain the purpose. This should almost document the code by itself (from a developer's point of view).

A method called 'loadSingleData' is an example of a bad name. It does not tell you anything (except that you expect a single result). The same goes for variable names like array, data, d, list, param1 (you name it). These are all bad because they do not explain their purpose.

If you have a list of Customers, name it $customers. Simple, clean and now every developer knows what kind the data the $customers variable contains.

Even when doing this throughout the code, there are still some things you cannot do in PHP, so you need extra documentation to explain it. That's when you use docblocks.

One of the things that should always be added is Exceptions. Adding them to a docblock makes it clear that an exception might be thrown, and any modern IDE's can use this (to suggest adding try/catch blocks for example).

Another example is passing or returning array's, which is a bad thing in itself, but that is a totally different discussion.

Example:

/**
 * @param array<int, string> $emailAddresses
 * @throws InvalidEmailAddressException
 */
public function validateEmailAddresses(array $emailAddresses): void {
    foreach ($emailAddresses as $emailAddress) {
        if (!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidEmailAddressException(
                sprintf('Invalid email address "%s"', $emailAddress)
            );
        }
    }
}

In this example, both the parameter and the exception are added to the docblock. The @param array<int, string> $emailAddresses line tells you there is a parameter called $emailAddresses which has the type array. The array is using ints as keys and strings as values.

Tools like PHPStan can use this docblock to analyze the code and make sure it's correct.

You can also write it like this, in case you have an associative array:

/**
 * @param array{firstName: string, lastName: string} $person 
 */

When passing objects, you don't need the docblock because the code explains itself. In this example, the parameter must always be of type Order and the returned value is always a CustomerCollection.

public function getCustomersFromOrder(Order $order): CustomerCollection {
    // Code here
}

3. Tests

If your project contains tests (unit, behat, to other tests), the test can be used to figure out how the project works, but if you have the first 2 options of this list, then the tests are just tests to validate the working of the project.

In case you don't have clean, clear, well-structured code with type hints, return types, and proper names for everything, then tests might be the only way to figure out how your project works. But at that point, your project might not be maintainable anymore and I doubt it will be used often.

Conclusion

Just remember that documentation is being used in different ways. Project documentation is used to determine what the project does. In the case of a library, it will be used to determine if someone wants to embed it in their own project. So having good project documentation will help with the project adaptation.

Examples in the project documentation and the documentation the code provides by itself will help the developers who are actually using the code.

Tests are more for the developer of the project, to make sure things don't break when making changes, but when the project lacks documentation, they can be used by the developers as well.

1

u/redditupf Aug 27 '21

thats correct :) i just write comments with a short description of what each section of the code does. im pretty sure thats what documenting your code means. its optional though. when i first began coding i used to overdo it and write line by line descriptions lol

1

u/[deleted] Aug 27 '21

Yes docblocks and no they're not redundant. A param type and param name isn't often enough to document what should be passed in, how its used or mutated, and more

Look at production libraries and you'll see that everything is docblocked

1

u/chevereto Aug 28 '21

To make sure to use the "wiki" tab on GitHub? To make sure to use docblocks above each method?

No, it refers that you write a tech document where you explain how to use it for others. Depending on the project it could be one paragraph up to a distributed documentation and depending on users you may require more than just one documentation scope.

Is it even worth adding docblocks? Don't @param, @return, etc. just duplicate what the top of the method

Depends, in some systems (specially before the language had the current great type support), we had to use docblocks to indicate stuff like "an array map for strings" or to hint the type on loops and whatnot. For those cases docblocks will be still relevant for a while.

As a rule of thumb, avoid commenting in your code. 😉