3 ms·
It has everything to do with context, and the ultimate goal should be clarity for the reader. But, I also don't think you should ever compromise any non-trivial
by k3n 14y ago
It has everything to do with context, and the ultimate goal should be clarity for the reader. But, I also don't think you should ever compromise any non-trivial design for the worse to 'make it more readable'. Sometimes clever code can't be easily avoided, whether it's due to language limitations or the general design pattern itself, so proceed with caution and use lots of comments in those cases. A quick example here would be a factory method: since you're often referring to abstracted resources, you can't really make a non-clever factory without entirely defeating the purpose of the factory.
Another example would be from PHP, where you can many times do tasks in several different ways, and so you may have this code (straight from the manual) for reading the contents of a file:
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
And this isn't even very descriptive, unless you have a background in other languages such as C to grok that filesize($filename) might mean "read to the end of the file".
OTOH, this code does the exact same thing and is extremely explicit about what it's doing:
$contents = file_get_contents("/usr/local/something.txt");