Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should I write more descriptive function names or add comments?

This is a language agnostic question, but I'm wandering what people prefer in terms of readability and maintainability... My hypothetical situation is that I'm writing a function which given a sequence will return a copy with all duplicate element removed and the order reversed.

/*
*This is an extremely well written function to return a sequence containing 
*all the unique elements of OriginalSequence with their order reversed
*/    
ReturnSequence SequenceFunction(OriginalSequence)
{...}

OR

UniqueAndReversedSequence MakeSequenceUniqueAndReversed(OriginalSequence)
{....}

The above is supposed to be a lucid example of using comments in the first instance or using very verbose function names in the second to describe the actions of the function.

Cheers,

Richard

like image 998
probably at the beach Avatar asked Dec 07 '22 22:12

probably at the beach


1 Answers

I prefer the verbose function name as it make the call-site more readable. Of course, some function names (like your example) can get really long.

Perhaps a better name for your example function would be ReverseAndDedupe. Uh oh, now it is a little more clear that we have a function with two responsibilities*. Perhaps it would be even better to split this out into two functions: Reverse and Dedupe.

Now the call-site becomes even more readable:

Reverse(Dedupe(someSequence))

*Note: My rule of thumb is that any function that contains "and" in the name has too many responsibilities and needs to be split up in to separate functions.

like image 135
Andrew Hare Avatar answered May 28 '23 09:05

Andrew Hare