Grading an algorithm: Readability vs. Compactness [closed]

Consider the following exam / interview question:


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 interviewer examiner, how would you grade the following answers to this question?

1)

void strcpy(char *destination, char *source)
{
  while (*source != '')
    {
      *destination = *source;
       source++;
       destination++;
    }
    *destination = *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 interviewer’s examiner’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 an exam. However, it is also possible that an interviewer examiner would consider the second 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 exams interviews.

7

The second answer shows the developer understands the C edge cases better. However, the first version is easier to read and understand because it does not require understanding of these edge cases.

If you are asked the question, ask the interviewer or examiner what they are looking for. If in doubt, go for readable code over compactness every time. Interviewers and examiners can reach decision fatigue quickly and making it easier on them will help you.

If the interviewer or examiner wants more, do the readable version first then given them the second version and explain why it works. This will also help you because you can make shorter conceptual leaps.

1

It all depends on the requirements for that piece of code.

  • Is it meant to be fast?
  • Is it meant to use minimal memory?
  • Is it meant to be reliable?
  • It it meant to be maintainable?

The other thing you need to consider is the guideline:

Make it right, then make it fast

The first example would be the ideal first implementation of the function which would satisfy the 3rd and 4th requirements on my list above. It would also be sufficient for an application that wasn’t time critical or memory limited etc. The second example might be what you would code if you needed to satisfy the 1st and 2nd requirements or you later discovered issues with your initial code (unlikely in this specific case).

As far as a tester is concerned the actual complementation shouldn’t be a factor in determining whether the code passes the tests or not. All that matters is that it:

  1. Produces the correct result
  2. Does so in a “reasonable” time (which will vary from application to application)
  3. Uses a “reasonable” amount of computer resources (ditto)

However, on re-reading your question I see that you are using the word “tester” for the person conducting the interview. In this case as you are looking at the code to judge the skill level or competency of the programmer, then the second example would be “better” as it shows that the programmer understands how pointers and pointer incrementation works.

The caveat to that though is unless the code is truly “write once” (i.e. it’s never going to be looked at again) you’d want the code in the first example.

7

In C the expression x++=y++ is extremely common and thus easily understood, and IMO should be preferred over the longer x=y; x++; y++; whenever possible as it expresses the INTENT better. That leaves the check for terminating the loop.

while(*source != '')

vs

while(*source)

vs

while(*destination++ = *source++){}

Understanding the 2nd and 3rd depends upon understanding two things, that C considers zero to be false and everything non-zero to be true and that the assignment operators return a result.

Both of these should be ingrained in even a junior C programmer and easily picked up by those coming from another language.

In short, I don’t consider the second harder to read, and in fact find the first more difficult to read in the context of a C program — in a language without ++ the first would of course be required, but programming in langauge a as if it was language b is confusing. The question “why is this code doing that” is much harder than “what is this code doing”, and non-standard usage makes me ask why…

Now, if you want to mark these down for some reason, look no further than the lack of comments. When dealing with pointers, such unstated restrictions are just begging for mistakes.

In general, if I’m asking people to write code in an interview, I’m looking to see if they write code that I’d want to debug and maintain. That would lead me to prefer answers like the first example.

However, anyone asking this specific question is probably testing to see if the interviewee knows the very common strcpy idiom in the second example. This is a test of their knowledge of pointers and C, not of the readability or compactness of their code.

There are a few things which come to mind.

If it works, it should be good enough. Focusing obsessively on code formatting isn’t any more productive as focusing obsessively on premature optimization. In most cases it adds no value.

You mentioned “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.“. That is then a problem because the programmer isn’t competent enough with such structures. Such compact structures are actually quite common in simple pieces of code like that, and any experienced programmer immediately understands and actually prefers them because they are simple.

This is highly a matter of style, which varies between persons. I don’t think there’s a correct answer to question like this.

Tester context

First, let us define testers. The distinction between software development and software testing roles happens to involve source code access. Developers are constantly in touch with details of the code, focusing on unit testing. Team members called testers are nearly always intentionally oblivious of the lowest levels of implementation, focusing on integration testing, stress testing, load testing, compatibility testing. A tester is therefore most likely to notice source code structure when a typo breaks a build or when a stack trace makes it to the logs.

Using whatever style that other members of your team find easy to maintain usually means that testers will see fewer build breaks and behavior deficiencies in the long run. When in doubt, ask your team or go after simplicity.

Code review context

When code is being reviewed by a fellow developer prior to commit, differences in code style do matter, of course. The one that is standard within the organization/product/project, or otherwise familiar to other team members, is the correct one. The others are incorrect – minus points and rework.

If a developer can explain why a particular practice is in their view better than the current standard, and why the standard should be updated (this question already provides a plenty of available arguments either way), that is plus points, but there is no reason for intentionally deviating first and explaining only second.

Interview context

During an interview, typos, indentation differences, etc., do not really matter. Your two implementations compile to the exact same binary code. Compared to the standard (pun intended) implementations of the same task, either of our equivalent samples is much easier to read, much slower, and also much safer to use to people not deeply familiar with the standard C library. This is partly because the “does not overlap” part of the task might have been translated to the restrict keyword but wasn’t.

The difference in coding style does say things about the soul of the developer. Both coding styles shown are completely industry standard ones, so it would be silly to judge the experience or skills of the candidate based on coding style alone. However, it is possible that the two programmers would eventually be offered differently oriented roles, or that a particular organization would find a fit with only one of those two personality styles.

Why can’t you give both answers?

I once had someone tell me I had the wrong answer in an interview and deny me the job because of it, even though my procedure worked. He wanted the quick way instead of the readable way (it was a game company). He explained his clever shortcut, but it was still a big disappointment for me. I sulked around feeling cheated for a couple weeks before looking up and trying out his solution. It turned out to have a serious bug that would have prevented it from working!

In hindsight, I should have continued working on the problem immediately after leaving the interview (or at least the next day when I cooled off). That way I could have contacted him and continued the discussion about the problem, maybe emailed him a test case to demonstrate where his preferred solution failed, and suggested a correction that solved the problem closer to his way, but without the bug.

Most of the candidates I’ve asked questions of in interviews have gotten them wrong. I finally gave up and just asked candidates to describe a recent project they felt excited about. That’s probably a better interview question any way. Because it’s open-ended, you get a feel for someone’s style and perspective as well as their knowledge and ability. If anyone had ever given me two correct answers to a question and discussed the relative strengths and weaknesses, I think I would have passed out. Someone like that would have to be a convicted serial killer AND a sex offender to not get the job! Maybe I wasn’t hiring from the best talent pool, but there you have it.

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.

You have your answer there.

When interviewers look at your code, they will also see your coding style. Readability is important for production code, so try to show them you can write such code.
For an exam you should aim for understandability as well, so your code is not wrongfully determined to be faulty.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật