Question

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

Was it helpful?

Solution

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);

OTHER TIPS

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.

...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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top