想要从这个社区获得洞察力的快速问题:哪一个更可取?
// How many spaces are there in the beginning of string? (and remove them)
int spaces = text.Length;
text = text.TrimStart(' ');
spaces -= text.Length;
Run Code Online (Sandbox Code Playgroud)
// How many spaces are there in the beginning of string? (and remove them)
int spaces = text.Length - (text = text.TrimStart(' ')).Length;
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 36
我不喜欢他们中的任何一个.编写清晰代码的一些准则:
选项(1)违反了本指南; 变量"spaces"被注释为"文本中有多少个空格",但它实际上并没有这个含义!它通过作为文本中的字符数开始其生命周期,并将其生命周期结束为以前在文本中的空格数.它在整个生命周期中意味着两种不同的东西,它们都不是所记录的意思.
表达式语句只有一个副作用.("表达式语句"是由单个表达式组成的语句;在C#中,合法语句表达式是方法调用,对象构造,增量,减量和赋值.)
除非表达式是表达式语句的单个副作用,否则表达式没有副作用.
选项(2)显然违反了这些准则.做多个副作用的表达式语句很难推理,它们很难调试,因为你不能把断点放在你想要的地方,这一切都很糟糕.
我会重写你的片段以遵循这些准则.
string originalText = text;
string trimmedText = originalText.TrimStart(' ');
int removedSpaces = originalText.Length - trimmedText.Length;
text = trimmedText;
Run Code Online (Sandbox Code Playgroud)
每行一个副作用,每个变量在整个生命周期中意味着完全相同的东西.
Can*_*ice 12
我做选项1b:
int initial_length = text.Length;
text = text.TrimStart(' ');
int spaces = initial_length - text.Length;
Run Code Online (Sandbox Code Playgroud)
当然,它几乎与选项一重复,但它更清晰一些(稍后您可能需要字符串的初始长度).
归档时间: |
|
查看次数: |
1332 次 |
最近记录: |