Lengthy lines of code vs readability

624 views Asked by At

This is perfectly fine C# code and works fine provided correct URL. But the everything is just done at one line by reducing the readability of the code.

Here is the code :

         return new StreamReader(WebRequest.Create(urlName).GetResponse().GetResponseStream()).ReadToEnd();

I am just wondering what are the opinions of fellow developers on this kind of short cut way of writing code

5

There are 5 answers

1
Joel Coehoorn On BEST ANSWER

Push it into a well-named method, and perhaps break it up so that single statment stretches over a couple lines. I'd also probably use WebClient:

return new WebClient().DownloadString(urlName);
0
James Matta On

...YUCK.

I will sometimes combine a few things into one line, usually when I am dumping stuff to a stream, but never this much.

Most compilers (c++ compilers at least) will often inline variable definitions if the definition is used only once, so if you make a one time use, throw away variable. Your C# compiler will probably just replace its name with its definition.

0
Juanma On

In addition to the readability problem, you should dispose any IDisposble object you are using.

1
Guffa On

No, it's not really perfectly fine C# code. You should dispose the StreamReader, so at least have a using statement:

using (StreamReader reader = new StreamReader(WebRequest.Create(urlName).GetResponse().GetResponseStream()) {
   return reader.ReadToEnd();
}

That code may gain a bit readability by dividing it into more lines, but not very much.

Generally I prefer readable code before compact code. Having one statement on each line makes the code easier to read and understand. For example:

if (i <= 4) i = 4 - i;

This becomes more readable with the if statement on one line and the code inside it on a separate line, with the if statement always having brackets:

if (i <= 4) {
   i = 4 - i;
}

This code is of course rather readable even in the compact form, but the more complex the code is, the more it gains from putting each statement on a separate line.

0
Yuan On

One statement != one line , you can improve readability by improving formatting of your code. Of course you should not assume other people use high resolution monitors.