I just installed Reshaper 4.5 and it has come up with the following suggestions:
return this.GetRuleViolations().Count() == 0; -- REMOVE this.
new string[] { this.ID.ToString(), this.Registration } -- REMOVE string, MAKE ANONYMOUS TYPE
int i = Method.GetNumber(); -- REPLACE int WITH var
Should I do these?
I think in some cases it is going to make the code less readable but will it improve performance? what are the benefits of making these changes?
Thanks
1) The explicit this pointer is only necessary when the reference would otherwise be ambiguous. Since GetRuleViolations is defined on the type, you most likely do not need this.
Another point here is that if GetRuleViolations return an IEnumerable of something, you will generally be much better off using Any() instead of Count() == 0 as you risk enumerating the entire sequence.
2) String can be inferred from the initialization.
3) Resharper prefers var over specific types.
Apart from the obvious benefit of your little square going green, if you are writing code that will be maintained by someone else later, it makes good sense not to use your personal preference in coding syntax. Resharper is becoming useful in formatting code in a way that is recognisable to a very wide audience.
I belong to the school of thought that says it doesn't matter who's way is right. If we all stick to a pattern, we'll all find it easier to read each others code.
So, in my humble opinion, don't change the default resharper settings. Just accept that if you use the defaults, you make life simple for everyone.
I think the first one is for the purpose, if you want to make "GetRuleViolations()" a static method. Then you have not to remove the "this" identifier.
For the 3rd one - the one that annoys me the most. It provides the reader with less information and i think it's just a matter of showing off a newish feature.
I'd say - use var when you know the return type and use the correct object type when you do not like this:
var reader = new XmlReader(.... // Implicit
XmlReader reader = SomeClass.GetReader() // Explicit when you can't be sure
First one: Resharper is asking about removing this which is just a style thing to me. Nothing more, keeping it won't harm performance in any way. It is just a matter of readability.
For second and third: Resharper normally prefers using var instead of specific data type, that's why the suggestions. I believe it is a matter of personal choice and provides no extra gain other than readability.
The first seems unclear to me. You usually don't have to prefix this. as long as there are no ambiguities, which I cannot tell from this example. Resharper is probably right. The other two won't improve performance, the compiled result will be the same. It's just a matter of taste and, of course, your coding guidelines.
The first one should be configurable. As far as I remember, you can tell ReSharper whether you want to have "this." in front of only fields, methods, both or none.
Using "var" will not change anything in the generated CIL code, so the performance will stay the same. I haven't used ReSharper for some time and I don't know why it promotes anonymous types so aggressively, but one advantage of "var" is that it's more resistant to change.
Meaning if, instead of calling Method.GetNumber(), you called a wrapper, eg. Filter(Method.GetNumber()) in the same line that returns a Nullable, you won't have to update the variable's type.
None of these will have any effect on performance, only on readability.
I find suggestions 1 and 2 to be more readable, and 3 less readable than your original code.
But you don't need to just follow these suggestions if, e.g., you find them less readable or if they violate your company's code style standard. When you put the cursor on the squiggly line, press Alt-Enter to show the list of Contex Actions. One of them will be to to change the severity of the inspection; you can not show it at all or show it as a hint. You can find a complete list of inspections at ReSharper | Options | Code Inspection | Inspection Severity.
Related
According to General Naming Conventions of .NET framework:
X DO NOT use abbreviations or contractions as part of identifier names.
For example, use GetWindow rather than GetWin.
X DO NOT use any acronyms that are not widely accepted, and even if they are, only when necessary.
I've once consider GetName can be used for my method, but I believe it's not so sematically meaningful.
In order not to deviate too far from the naming convention, I've tried to figure out widely accepted acronyms, but I just run out of ideas for the following method:
String GetExplicitInterfaceMemberImplementationName(MemberInfo info) {
return info.DeclaringType.Name+"."+info.Name;
}
For this case, it is, in fact, not really longer than the statement, but just the identical length; and Type.Delimiter should be used rather than ".". However, the naming problems so often bothers me.
So, what method name should I declare? And for the long-term solutions, what can I do?
For an additional question, is there an API out of the box does the same thing?
Edit 1:
Stop and think, such a good suggestion for me.
For the purpose of its statement, also for semantic and not breaking the naming conventions, I got an idea from [AddAttributeStoreCommand.TypeQualifiedName Property]; so I now declare it as:
public static String GetTypeQualifiedName(this MemberInfo info) {
return info.DeclaringType.Name+"."+info.Name;
}
Yet, a long-term solution hasn't come up ..
Edit 2:
I'm not sure whether it's a good practice to name like this ..
public static String GetTypeDotItsName(this MemberInfo info) {
return info.DeclaringType.Name+"."+info.Name;
}
Code Complete 2nd Edition has this to say about method name length:
Make names of routines as long as necessary
Research shows that the optimum average length for a variable name is 9 to 15 characters. Routines tend to be more complicated than variables, and good names for them tend to be longer. Michael Rees of the University of Southampton thinks that an average of 20 to 35 characters is a good nominal length (Rees 1982). An average length of 15 to 20 characters is probably more realistic, but clear names that happened to be longer would be fine.
Note the word average. If the method name is as clear as possible, and it's 50 characters, then whatever. It's fine.
However, the book does mention another thing a few paragraphs up:
If you have routines with side effects, you’ll have many long, silly names, The cure is not to use less-descriptive routine names; the cure is to program so that you cause things to happen directly rather than with side effects.
Of course, side effects aren't the issue here, but you can extend the idea. Ask yourself "Is this long, silly name popping up because I'm doing overly complicated stuff?" If you're sure that you need an ExplicitMemberInterfaceImplementationName, then fine, but it can at least be something to stop and think about.
1) Put in the information that is needed to make the purpose of the method clear. You can probably halve the length of your example name without any loss of understanding about what it fits.
2) guidelines are guidelines. Don't slavishly follow rules when they become counter productive. If using an abbreviation makes it easier to read and understand the code, use abbreviations. The main thing is to try to limit abbreviations to long names that are commonly used, and use intuitive and commonly used abbreviations for them, so that anyone reading your code can easily work out what they mean. For example, decl is a common abbreviation for declaration, and difficult to mistake for anything else.
3) sometimes you can avoid the need to abbreviate by using a synonym.
I think you could probably drop interface and member from your name without losing the meaning.
But perhaps the "explicit interface implementation name" is actually the "explicit name" - explicit has a well defined meaning, especially in the context if your class, and you can always add the fully watertight legal definition in your documentation comment. So: "GetExplicitName"
I was reading through some C# code of mine today and found this line:
if (ProgenyList.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) return;
Notice that you can tell without scrolling that it's an "if" statement that works with ItemContainerGenerator.Status, but you can't easily tell that if the "if" clause evaluates to "true" the method will return at that point.
Realistically I should have moved the "return" statement to a line by itself, but it got me thinking about languages that allow the "then" part of the statement first. If C# permitted it, the line could look like this:
return if (ProgenyList.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated);
This might be a bit "argumentative", but I'm wondering what people think about this kind of construct. It might serve to make lines like the one above more readable, but it also might be disastrous. Imagine this code:
return 3 if (x > y);
Logically we can only return if x > y, because there's no "else", but part of me looks at that and thinks, "are we still returning if x <= y? If so, what are we returning?"
What do you think of the "then before the if" construct? Does it exist in your language of choice? Do you use it often? Would C# benefit from it?
Let's reformat that a bit and see:
using System.Windows.Controls.Primitives;
...
if (ProgenyList.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
{
return;
}
Now how hard is it to see the return statement? Admittedly in SO you still need to scroll over to see the whole of the condition, but in an IDE you wouldn't have to... partly due to not trying to put the condition and the result on the same line, and party due to the using directive.
The benefit of the existing C# syntax is that the textual order reflects the execution order - if you want to know what will happen, you read the code from top to bottom.
Personally I'm not a fan of "return if..." - I'd rather reformat code for readability than change the ordering.
I don't like the ambiguity this invites. Consider the following code:
doSomething(x)
if (x > y);
doSomethingElse(y);
What is it doing? Yes, the compiler could figure it out, but it would look pretty confusing for a programmer.
Yes.
It reads better. Ruby has this as part of its syntax - the term being 'statement modifiers'
irb(main):001:0> puts "Yay Ruby!" if 2 == 2
Yay Ruby!
=> nil
irb(main):002:0> puts "Yay Ruby!" if 2 == 3
=> nil
To close, I need to stress that you need to 'use this with discretion'. The ruby idiom is to use this for one-liners. It can be abused - however I guess this falls into the realm of responsible development - don't constrain the better developers by building in restrictions to protect the poor ones.
It's look ugly for me. The existing syntax much better.
if (x > y) return 3;
I think it's probably OK if the scope were limited to just return statements. As I said in my comment, imagine if this were allowed:
{
doSomething();
doSomethingElse();
// 50 lines...
lastThink();
} if (a < b);
But even just allowing it only on return statements is probably a slippery slope. People will ask, "return x if (a); is allowed, so why not something like doSomething() if (a);?" and then you're on your way down the slope :)
I know other languages do get away with it, but C#'s philosophy is more about making The One Right WayTM easy and having more than one way to do something is usually avoided (though with exceptions). Personally, I think it works pretty well, because I can look at someone else's code and know that it's pretty much in the same style that I'd write it in.
I don't see any problem with
return 3 if (x > y);
It probably bothers you because you are not accustomed to the syntax. It is also nice to be able to say
return 3 unless y <= x
This is a nice syntax option, but I don't think that c# needs it.
I think Larry Wall was very smart when he put this feature into Perl. The idea is that you want to put the most important part at the beginning where it's easy to see. If you have a short statement (i.e. not a compound statement), you can put it before the if/while/etc. If you have a long (i.e. compound) statement, it goes in braces after the condition.
Personally I like languages that let me choose.
That said, if you refactor as well as reformat, it probably doesn't matter what style you use, because they will be equally readable:
using System.Windows.Controls.Primitives;
...
var isContainersGenerated =
ProgenyList.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated;
if (!isContainersGenerated) return;
//alternatively
return if (!isContainersGenerated);
There is a concern reading the code that you think a statement will execute only later to find out it might execute.
For example if you read "doSomething(x)", you're thinking "okay so this calls doSomething(x)" but then you read the "if" after it and have to realise that the previous call is conditional on the if statement.
When the "if" is first you know immediately that the following code might happen and can treat it as such.
We tend to read sequentially, so reading and going in your mind "the following might happen" is a lot easier than reading and then realising everything you just read needs to be reparsed and that you need to evaluate everything to see if it's within the scope of your new if statement.
Both Perl and Ruby have this and it works fine. Personally I'm fine with as much functionality you want to throw at me. The more choices I have to write my code the better the overall quality, right? "The right tool for the job" and all that.
Realistically though, it's kind of a moot point since it's pretty late for such a fundamental addition in C#'s lifecycle. We're at the point where any minor syntax change would take a lot of work to implement due to the size of the compiler code and its syntax parsing algorithm. For a new addition to be even considered it would have to bring quite a bit of functionality, and this is just a (not so) different way of saying the same thing.
Humans read beginning to end. In analyzing code flow, limits of the short term memory make it more difficult to read postfix conditions due to additional backtracking required. For short expressions, this may not be a problem, but for longer expressions it will incur significant overhead for users that are not seasoned in the language they are reading.
Agreed with confusing , I never heard about this construction before , so I think correct way using then before if must always contents the result of else, like
return (x > y) ? 3 : null;
else way there is no point of using Imperative constructions like
return 3 if (x > y);
return 4 if (x = y);
return 5 if (x < y);
imho It's kinda weird, because I have no idea where to use it...
It's like a lot of things really, it makes perfect sense when you use it in a limited context(a one liner), and makes absolutely no sense if you use it anywhere else.
The problem with that of course is that it'd be almost impossible to restrict the use to where it makes sense, and allowing its use where it doesn't make sense is just odd.
I know that there's a movement coming out of scripting languages to try and minimize the number of lines of code, but when you're talking about a compiled language, readability is really the key and as much as it might offend your sense of style, the 4 line model is clearer than the reversed if.
I think it's a useful construct and a programmer would use it to emphasize what is important in the code and to de-emphasize what is not important. It is about writing intention-revealing code.
I use something like this (in coffeescript):
index = bla.find 'a'
return if index is -1
The most important thing in this code is to get out (return) if nothing is found - notice the words I just used to explain the intention were in the same order as that in the code.
So this construct helps me to code in a way which reflects my intention slightly better.
It shouldn't be too surprising to realize that the order in which correct English or traditional programming-language grammar has typically required, isn't always the most effective or simplest way to create meaning.
Sometimes you need to let everything hang out and truly reassess what is really the best way to do something.
It's considered grammatically incorrect to put the answer before the question, why would it be any different in code?
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
There Currently is a local debate as to which code is more readability
We have one programmer who comes from a c background and when that programmer codes it looks like
string foo = "bar";
if (foo[foo.Length - 1] == 'r')
{
}
We have another programmer that doesn't like this methodology and would rather use
if (foo.EndsWith("r"))
{
}
which way of doing these types of operations is better?
EndsWidth is more readable to someone who has never seen C or C++, C#, or any other programming language.
The second one is more declarative in style but I can't tell you objectively if it is more readable sine readability is very subjective. I personally find the second one more readable myself but that is just my opinion.
Here is an excerpt from my article:
Most C# developers are very familiar
with writing imperative code (even
though they may not know it by that
name). In this article, I will
introduce you to an alternative style
of programming called declarative
programming. Proper declarative code
is easier to read, understand, and
maintain.
As professionals, we should be
striving to write better code each
day. If you cannot look at code you
wrote three months ago with a critical
eye and notice things that could be
better, then you have not improved and
are not challenging yourself. I
challenge you to write code that is
easier to read and understand by using
declarative code.
Number 2 is better to read and to mantain.
Example: Verify the last 2 characters ...
Option 1)
if (foo[foo.Length - 1] == 'r' && foo[foo.Length - 2] == 'a')
{
}
Option 2)
if (foo.EndsWith("ar"))
{
}
last 3? last 4?...
I come from a C/C++ background and I vote for Endswith!
Readability rules, especially if it implies intent.
With the first example I must discover the intent - which is left for interpretation. If it appears to have a bug, how do I know that's not intentional?
The second example is telling me the intent. We want to find the end character. Armed with that knowledge I can proceed with evaluating the implementation.
I think the second way is better because it is more easy to read and because the first one duplicates logic of EndsWith method which is bad practice.
I think the right answer would be the one that is actually correct. EndsWith properly returns false for empty string input whereas the other test will throw an exception trying to index with -1.
Not only is EndWith more readable, but also more 'correct'.
As a rule, if there is a framework method provided to do the job ... use it.
What if foo == string.Empty?
IMO, the intent of the original author is clearer in the second example. In the first, the reader must evaluate what the author is trying to accomplish by pulling the last index. It is not difficult, but requires more effort on the part of the reader.
Both approaches are valid, but the endswith method is easier to read in my opinion. It also does away with the potential to make typing mistakes etc with the more complicated form..
EndsWith is probably safer. But the indexer is probably faster.
Endswith probably checks to see if the input string is empty. They will probably both throw null reference exceptions. And the indexer will fail is the length is 0.
As for readability, they both say the same thing to me, but I have been programming for a while. The .EndsWith(...) is probably faster to grasp without considering context.
It pretty much does the same thing. However, it gets more complicated with more than one character in the endswith argument. However, the first example is slightly faster as it uses no actual functions and thus requires no stack. You might want to define a macro which can be used to simply make everything uniform.
I think the main criteria should be which of these most clearly says what the developer wants to do. What does each sample actually say?
1)Access the character at position one less than the length, and check if it equals the character 'r'
2)Check if it ends with the string "r"
I think that makes it clear which is the more maintainable answer.
Unless and until it does not affect the program performance, no problem you can use either way. But adding code comments is very important for conveying what is being accomplished.
From an error handling standpoint, EndsWith.
I much prefer the second (EndsWith) version. It's clear enough for even my manager to understand!
The best practice is to write code that is easily readable. If you used the first one, developers that are debugging your code may say, "What is this dev trying to do?" You need to utilize methods that are easily explained. If a method is too complicated to figure out, retract several methods out of it.
I would definitely say the second one, legibility and simplicity are key!
Also, if the "if" statement has one line, DONT BOTHER USING BRACES, USE A SINGLE INDENTION
Remember that in classic C, the only difference between a "string" and an array of characters is that terminating null character '\0', so we had to more actively treat them accordingly and to make sure that we did not run off the end of the array. So the first block of code bases its thought process on the concept of an array of characters.
The second block of code bases the thought process on how you handle a string more abstractly and with less regard to its implementation under the covers.
So in a nutshell, if you are talking about processing characters as the main idea behind your project, go with the first piece. If you are talking about preparing a string for something greater and that does not necessarily need to focus on the mechanics of the ways that strings are built -- or you just want to keep it simple -- go with the second style.
Some of this might summarize others' contributions at this point, but more analogously put, are you playing "Bingo();" or are you "playing a game with a two-dimensional array of random integers, etc.?"
Hopefully this helps.
Jim
"Code is written to be read by humans and incidently run by computers" SICP
EndsWith FTW!!
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Which one is better (implicit control flow via return or control flow via if) -- see below. Please explain what you see as advantage/disadvantage to either one. I like option A because it's less code.
Flow via Return:
public ActionResult Edit(MyClass class)
{
if (!class.Editable)
return null;
class.Update();
return View();
}
Flow via If/Else:
public ActionResult Edit(MyClass class)
{
if (class.Editable)
{
class.Update();
return View();
}
else
{
return null;
}
}
There's not much difference in this specific example, but in general I like the first approach because it uses a guard clause to return early. If you start adding nested conditions to the second approach you'll see that your code readability will suffer. Guard clauses can go a long way toward reducing the nesting depth, and really enhance the readability of your code.
I personally like the if/else approach. For one, your if statement is a positive, not a negative, making it easier to read. For two, you've encapsulated the conditions in curly brackets, and I'm a fan of that style.
Anyway, it's much easier to follow what's going on in the second than in the first. And that always wins in my book.
I prefer the second approach for the sake of readability and maintainability. Readability because it just reads 'cleaner' to me than the first approach, and maintainability because I don't have to worry about adding curly braces if I need to modify the if or else clauses. Further, the first approach is only 7 characters less than the second approach if you don't include new lines, which hardly seems a justification for choosing the first over the second.
That said, I actually prefer this:
public ActionResult Edit(MyClass class)
{
ActionResult rv = null;
if (class.Editable)
{
class.Update();
rv = View();
}
return rv;
}
It's more code, but I can now set a single breakpoint on the return statement to inspect the value being returned instead of having to set two breakpoints to do the same in the two choices you offered.
Both of those statements are controlling flow via an if statement. It's just a matter of how you handle the condition.
I'm always on the fence when it comes to writing logic statements like this. Part of me likes the first option because it's a little less code. The other part of me likes the second option because it's much easier to follow the flow of logic. With the first option, it's easy to miss the return statement which can lead to manageability issues in the future.
...and for that reason, the second option always wins in my book. It's better to write code that is easier to read and maintain than try to take shortcuts.
I would prefer the one I identify as being the one which EXECUTES less code.
If it is more common to class.Editable being false then I'd go for A.
But this example does not give much of an advantage in either case.
In any given situation a developer should analyze the input and adjust the code to be optimized on the most common input data.
EDIT:
To clarify:
By executes less code I in reality mean is most efficient...
Exit early - I prefer to see all the conditions that will cause the method to exit without doing much up front. I avoid else statements if I can at all avoid it.
This is actually a fairly prominent school of thought among the Code Contracts crowd.
under these circumstances, I would go with option A. In this case you are doing your input validation and then preventing execution of the rest of the code if the input is not valid (not editable). This keeps the entire body of the function out of a big if/else statement and makes it more readable.
However, I would also consider raising an exception rather than retuning a null - that is assuming that passing in a non-editable object into an "edit" function isn't a normal occurrence.
They are both valid options, and one isn't necessarily any better than the other. Which one you choose is, ultimately, personal preference. Yes, Option A results in slightly less code, but overall they are pretty much equal.
In both cases you are controlling flow via an if and a return. It's really a question of how you prefer to see your boolean logic - negative or positive?
Is ActionResult an enum or a base class? If it's an enum, why are you returning null when Edit returns what appears to be an enum? Wouldn't it be cleaner simply to return an ActionResult value that indicates no action was taken because the object wasn't in an editable state?
I prefer if/else, too. Legibility, readability and maintainability stands above anything else, for me.
First option, using return, is better, because:
you have a place to put all guards and preconditions, near your asserts and all that stuff.
for me, it's easier to think "let's see all that can be wrong, and return. From this point, I have everything I need and I am on the Happy Path
if you do use the if / else approach, you have all code in that method / function indented. Add other if, or for, and things start to get funny
One proponent of this method (return) is Marcus Zarra, in the Cocoa is my Girlfriend coding style
I prefer the first option, provided the case you check is a guard/precondition that needs to be met for the method call to be valid. Although you could argue if you should return null, or throw an (Argument)Exception. When a class isn't editable, should it really be a parameter for this method?
Maybe a better option would be to create an IEditable interface and implementing this on the class you're passing an instance of right now.
I also prefer option 1. For me, it reads better like a book. Also I'm always pained by there not being a return at the end of option 2.
For quick tasks where I only use an instantiated object once, I am aware that I can do the following:
int FooBarResult = (new Foo()).Bar();
I say this is perfectly acceptable with non-disposable objects and more readable than the alternative:
Foo MyOnceUsedFoo = new Foo();
int FooBarResult = MyOnceUsedFoo.Bar();
Which do you use, and why?
Would you ever use this type of anonymous instantiation in a production app?
Preference: with parenthesis "(new Foo()).Bar();" or without "new Foo().Bar();"?
(Edited to abstract question away from Random class)
Side note regarding random numbers: In fact, no, your specific example (new Random().Next(0,100)) is completely unacceptable. The generated random numbers will be far from uniform.
Other than that, in general, there is not much difference between the two. The compiler will most probably generate the exact same code in either case. You should go with the most readable case (long statements might harm readability; more code will do it too, so you have to make the trade-off in your specific case).
By the way, if you chose to go with the single line case, omit the unnecessary parens (new MyObject().Method() will do).
You might want to consider the implications of using the code in the debugger. The second case will allow you to inspect the object you've created, whereas the first won't. Granted you can always back out to the second case when you're attempting to debug the code.
I've done it both ways and don't really have a preference. I prefer whatever looks more readable, which is highly dependent on the complexity of the class and method being called.
BTW -- you might want to pick a different example. I fear that your point might get lost in discussions over the best way to generate random numbers.
If you are only using the object once, the first way is better all the time.
It is shorter and clearer, because it makes it explicit that you will not use the object later.
It will probably compile to the same CIL anyway, so there's no advantage to the second form.
First statement. It's more readable, has less code and doesn't leave temps around.
The second one is debugging friendly, while the first one isn't. The second wins only because of this.
In fact the first way, creating a temporary, is more readable for two reasons:
1) it's more concise
There's less code to read, there's no unnecessary local variable introduced, and no potential name clash with another local, or shadowing of any variable with the same name in an enclosing scope
2) it communicates something that the second form doesn't, that the object is being used temporarily.
Reading it, I know that that instance is never going to be used again, so in my "mental compiler" that I use to understand the code I'm reading, I don't have to keep a reference to it any more than the code keeps a reference to it.
As Mehrdad notes, though, doing it with a Random class isn't a good idea.
As he also notes, the redundant parentheses make it less concise; unless you're in a dusty corner of a language, assume that competent programmers know the language's operator precedence. In this case, even if I don't know the operator precedence, the alternative parse (calling new on a function's return) is nonsensical, so the "obvious" reading is the correct reading.
int RandomIndex = (new Random()).Next(0,100);
int RandomIndex = new Random().Next(0,100);