On Jan 27, 2011, at 4:38 PM, Dirk Pranke wrote:

> I agree with all of the sentiments below, except for possibly one or two 
> cases.
> 
> Namely, sometimes you write code where the "what" is not obvious. In
> that situation, it may not be possible to change the code to make it
> more obvious, because you are bound by contract. For example, suppose
> you are implementing an interface with a method called sort(). The
> fact that you choose a quicksort or a mergesort is a useful one-line
> comment, and in my opinion is probably better than just wrapping a
> method called quicksort() and hoping it gets inlined away.

I ran into this exact situation. I wanted to add a sort function that doesn't 
copy, only swaps. It happens that heapsort is such an algorithm. I named the 
public interface nonCopyingSort, made it call a function named heapSort, and 
wrote a comment explaining why heapSort is an appropriate implementation for 
nonCopyingSort:

http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/wtf/NonCopyingSort.h

template<typename RandomAccessIterator, typename Predicate>
inline void nonCopyingSort(RandomAccessIterator start, RandomAccessIterator 
end, Predicate compareLess)
{
    // heapsort happens to use only swaps, not copies, but the essential thing 
about
    // this function is the fact that it does not copy, not the specific 
algorithm
    heapSort(start, end, compareLess);
}

Inlining works. IMO it's always better to use a well-named function to document 
what your code does than a comment. In this case I did it even though I also 
had a comment explaining why the function uses heapsort.

> 
> A slight variant of this is that you may be learning or
> reverse-engineering code where the "what" is not clear (perhaps
> because it was poorly rewritten). In the longer-term, ideally you'd
> clean up the code, but in the short term it might be useful to capture
> the "what" in comments until you can safely refactor things and delete
> the comments.

I would prefer for people to refactor instead of adding explanatory comments.

In general, I agree with what Eric and Darin said about this topic.

Regards,
Maciej

_______________________________________________
webkit-dev mailing list
webkit-dev@lists.webkit.org
http://lists.webkit.org/mailman/listinfo.cgi/webkit-dev

Reply via email to