Grading an algorithm: Readability vs. Compactness
Posted
by
amiregelz
on Programmers
See other posts from Programmers
or by amiregelz
Published on 2012-09-02T15:11:34Z
Indexed on
2012/09/02
15:50 UTC
Read the original article
Hit count: 311
Consider the following question in a test \ interview:
Implement the strcpy() function in C: void strcpy(char *destination, char *source);
The strcpy
function copies the C string pointed by source
into the array pointed by destination
, including the terminating null character. Assume that the size of the array pointed by destination
is long enough to contain the same C string as source
, and does not overlap in memory with source
.
Say you were the tester, how would you grade the following answers to this question?
1)
void strcpy(char *destination, char *source)
{
while (*source != '\0')
{
*destination = *source;
source++;
destionation++;
}
*destionation = *source;
}
2)
void strcpy(char *destination, char *source)
{
while (*(destination++) = *(source++)) ;
}
The first implementation is straightforward - it is readable and programmer-friendly.
The second implementation is shorter (one line of code) but less programmer-friendly; it's not so easy to understand the way this code is working, and if you're not familiar with the priorities in this code then it's a problem.
I'm wondering if the first answer would show more complexity and more advanced thinking, in the tester's eyes, even though both algorithms behave the same, and although code readability is considered to be more important than code compactness. It seems to me that since making an algorithm this compact is more difficult to implement, it will show a higher level of thinking as an answer in a test. However, it is also possible that a tester would consider the first answer not good because it's not readable.
I would also like to mention that this is not specific to this example, but general for code readability vs. compactness when implementing an algorithm, specifically in tests \ interviews.
© Programmers or respective owner