Like many discipline, programming is a team one. Yes, you can occasionally encounter a programmer earning a living while programming in his basement all alone. But since a lone programmer can only achieve so much on his own, most sizable projects require many programmers to cooperate.
Working with others always has it’s own set of challenges. Personality, culture, religion and many more can come as obstacles in teamwork. As programmers, even thought process can causes conflicts.
Not so long ago, I encountered a function written by a coworker that baffled me. It was only 7 lines of code, but it took me a moment to understand what it really did. I eventually went to ask the original programmer his explanation of his implementation decisions (Added as code comment, the original code had no comments).
function GetSurObj(ASurObj : TSurObj; AObj : TObject) : TSurObj; begin //First, I initialize my Result Result := nil; //Then I validate the input parameters if (ASurObj = nil) and (AObj = nil) then EXIT; //if the ASurObj = nil but AObj isn't, try to find a proper ASurObj if (ASurObj = nil) and (AObj <> nil) then Result := FindSurObj(AObj) else // if we get here, it means ASurObj <> nil Result := ASurObj; end;
When I finally understood the actual use of the function, I couldn’t believe how complicated it ended up being. To me, the following makes a lot more sense.
function GetSurObj(ASurObj : TSurObj; AObj : TObject) : TSurObj; begin Result := ASurObj; if (Result = nil) and (AObj <> nil) then Result := FindSurObj(AObj) end;
Both functions have the merit of returning exactly the same result and making the exact same validations. But it seems to me it’s a lot easier to understand the purpose of the function looking at my version where the most significant line of code is the 1st one, compared to my coworker’s version where the most significant line is the last one.
I can see the merit of initializing result and validating input parameters, but I feel that, in this situation, it just adds way too much noise to a very simple function.
What do you think? Leave a comment about which implementation you prefer and why.