冗长的代码行与可读性
这是完美的 C# 代码,只要 URL 正确,就可以正常工作。 但所有事情都只在一行完成,降低了代码的可读性。
这是代码:
return new StreamReader(WebRequest.Create(urlName).GetResponse().GetResponseStream()).ReadToEnd();
我只是想知道其他开发人员对这种编写代码的快捷方式有何看法
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将其推入一个命名良好的方法中,也许可以将其分解,以便单个语句可以跨越几行。 我也可能会使用 WebClient:
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:
不,这并不是真正完美的 C# 代码。 您应该处置 StreamReader,因此至少有一个
using
语句:该代码可以通过将其分成更多行来获得一点可读性,但不会太多。
一般来说,我更喜欢可读的代码而不是紧凑的代码。 每行一个语句可以使代码更易于阅读和理解。 例如:
if 语句位于一行,其中的代码位于另一行,并且 if 语句始终带有括号,这会变得更具可读性:
即使在紧凑的形式下,该代码当然也具有很强的可读性,但越复杂,代码越多,将每个语句放在单独的行中获得的收益就越大。
No, it's not really perfectly fine C# code. You should dispose the StreamReader, so at least have a
using
statement: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:
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:
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.
...恶心。
有时我会将一些东西合并到一行中,通常是当我将东西转储到流中时,但从来没有这么多。
如果定义仅使用一次,大多数编译器(至少是 C++ 编译器)通常会内联变量定义,因此如果您只使用一次,请丢弃变量。 您的 C# 编译器可能只是将其名称替换为其定义。
...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.
除了可读性问题之外,您还应该处置您正在使用的任何 IDisposble 对象。
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.