Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason why table layout in code is considered bad?

My colleagues tell me that table based formatting of code is bad and it is no readable and I should follow conventions. What's that bad about table based formatting? Why is it banned?

I'm asking because for me it's much more readable.

Examples (not real code):

if (res == ResultType.Failure)               
  something = ProcessFailure(..);
if (res == ResultType.ScheduledAndMonitored) 
  something = DoSomething(...) && DoSomething3(..);
if (res == ResultType.MoreInfoAvailable)     
  info = GetInfo(..);
if (res == ResultType.OK && someCondition)   
  something = DoSomething2(..);
.... continued

versus

if (res == ResultType.Failure)               something = ProcessFailure(..);
if (res == ResultType.ScheduledAndMonitored) something = DoSomething(...) && DoSomething3(..);
if (res == ResultType.MoreInfoAvailable)     info      = GetInfo(..);
if (res == ResultType.OK && someCondition)   something = DoSomething2(..);
.... continued

Why I think the second one is better:

  • I don't need to parse the text by eyes - I see the structure of the commands at one glance.
  • I see immediatelly
    • that there are some ifs and assignments
    • that the enum used in conditions is ResultType and nothing more
    • that only the last condition is composed from two expressions

Update: this is not a real code. I just wanted to show some example. Consider it like it's an old code that somebody wrote some time ago and you need to read it. Why the first formatting is preferred over the second?

like image 322
stej Avatar asked Jul 22 '10 16:07

stej


2 Answers

When your colleagues say you should follow conventions, does that mean your team has a formatting convention? If that is the case, that is enough reason right there. When everybody formats their code the same way, it is easier to read your teammate's code.

like image 166
Peter Recore Avatar answered Oct 03 '22 19:10

Peter Recore


The "table-based" layout you describe can be very useful in certain cases:

public string GetMessageFromErrorCode(int code)
{
    switch (code)
    {
        case 1: return "OK";
        case 2: return "Syntax Error";
        case 3: return "Other error";
    }
}

Note that this example is a valid exception to the c# rule that "All case statements must also include a break."

I am not fond of being rigid about code layout. Following a coding standard is a good thing. But as soon as you start doing things like using several parameters with long names in function calls, writing linq queries, or using anonymous methods or intricate lambda statements, it can make your code more readable to break the rules from time to time.

See Also:
Anonymous Methods / Lambda's (Coding Standards)

like image 22
Robert Harvey Avatar answered Oct 03 '22 19:10

Robert Harvey