Combine multiple lines of C# code for brevity or separate for clarity

StackOverflow https://stackoverflow.com/questions/23688807

  •  23-07-2023
  •  | 
  •  

سؤال

I am fairly new to c# and trying to learn best practices. I've been faced with many situations over the last week in which I need to make a choice between longer+simpler code, or shorter code that combines several actions into a single statement. What are some standards you veteran coders use when trying to write clear, concise code? Here is an example of code I'm writing with two options. Which is preferable?

A)

        if (ncPointType.StartsWith("A"))//analog points
        {
            string[] precisionString = Regex.Split(unitsParam.Last(), ", ");
            precision = int.Parse(precisionString[1]);
        }
        else
            precision = null;

B)

        if (ncPointType.StartsWith("A"))//analog points
            precision = int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]);
        else
            precision = null;
هل كانت مفيدة؟

المحلول

There is no right or wrong. This is opinion based really.

However, remember that whether you add braces, add comments, add whitespace or whatever, it doesn't affect the performance or the size of the final assembly because the compiler optimizes it very well. So, why not go with the more verbose so that other programmers can follow it easier?

نصائح أخرى

This is basically subject to the coding standard you choose. There is no right or wrong, just personal preference.

Agree as a team what you prefer.

But even better is:

precision = ncPointType.StartsWith("A")? 
                 int.Parse(Regex.Split(unitsParam.Last(), ", ")):
                 null;

This expresses the function beiong executed (set the precision), and the conditions that control how it is set, in even less code, - without creating unnecessary temporary variables to hold a temporary result that is not used anywhere else.

If you ask me both A and B are bad practice. You should always use braces regardless of whether or not it is one line or multiple lines. This helps to prevent bugs in the future when people add additional lines of code to your if or else blocks and don't notice that the braces are missing.

Sometimes having "more" code, like using temporary variables, etc., will make your code easier to debug as you can hover over symbols. It's all about balance, and this comes with experience. Remember that you may not be the only one working on your code, so clarity above all.

Ultimately it comes down to your choice because it has nothing to do with performance, but I would also note that you cannot instantiate or define variables if you omit the curly braces:

int a = 0;
if (a == 0)
    int b = 3;

Is not valid, whereas:

int a = 0;
if (a == 0)
{
    int b = 3;
}

Is valid.

It's easier to debug option A, but option B is more concise while still being readable. You could make it even more concise with a ternary operator:

precision = ncPointType.StartsWith("A") ? int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]) : null;

Although it's far more readable this way (and still works the same way!):

precision = ncPointType.StartsWith("A") ? 
                int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]) : 
                null;

It's best to stick with the standards used in your project. Readability is far more important for maintainability than having less lines of code. In both options, the efficiency is the same, so you don't need to worry about speed in this case.

As everyone else here points out, there are no hard and fast "rules" per se, but there should probably be braces around both block of code; both A and B have characteristics similar to the Apple goto bug because the introduce potential ambiguity.

Consider:

void Main()
{
    int x=1;
    if (x==1)
        Console.WriteLine("1");
    else if (x==2)
        Console.WriteLine("NOT 1");
        Console.WriteLine("OK");
}

will produce

1
OK

To someone scanning the code, especially if it's surrounded by other, innocuous looking code, this could easily be misread as "only print "OK" if x==2). Obviously some people will spot it, some won't, but why introduce the danger for the want of a brace of braces :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top