Is it considered accepted using var's as "shortcuts" in c#? - c#

One use for the var type in c# seems to be shortcuts/simplifying/save unnecessary typing. One thing that I've considered is this:
MyApp.Properties.Settings.Default.Value=1;
That's a ton of unnecessary code. An alternative to this is declaring:
using MyApp.Properties;
-- or --
using appsettings = MyAppp.Properties.Settings;
leading to: appsettings.Default.Value=1 or Settings.Default.Value=1
Abit better, but I'd like it shorter still:
var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
appsettings.Value=1;
Finally, it's short enough, and it could be used for other annoyingly long calls too but is this an accepted way of doing it? I'm considering whether the "shortcut var" will always be pointing to the existing instance of whatever I'm making a shortcut too? (obviously not just the settings as in this example)

It's acceptable code in that the compiler will take it and know what to do with it. It's acceptable code logically in that it shortens code later. It's really not any different than actually defining the variable type (int/bool/whatever) rather than saying var. When you're in the studio, putting your mouse of the variable gives you its compiled type, so there shouldn't be any real issue with it. Some might call it lazy, but laziness is the mother of invention. As long as your code doesn't become unreadable, I can't see how it would be much of a problem.

There is nothing wrong with that, as long as the code is clear.

In Fact, var is more and more used exactly for that : shortening the code.
Specially in the case of
MyClass myClass = new MyClass();
Which is very clear enough using
var myClass = new MyClass();
And btw, ReSharper helps you enforce that var is used everywhere it can be !

Seems fine to me, it can enhance readability especially if you're using that long .notated syntax many times.
As a side, if you're using an indexed property or an autogenerated property (which does work on the fly for the GETTER) multiple times, then there can be a performance hit for each access of this property. That's microoptimisation though, so probably shouldn't worry too much about that.

Just be careful to know that the static variables you are referencing do not change from underneath you. For instance, the following would break your "shortcut":
var appsettings = MyFirstCSharpApp.Properties.Settings.Default;
MyFirstCSharpApp.Properties.Settings.Default = new DefaultSettings(); // new reference
appsettings.Value=1;
Of course, I am not suggesting that you would ever write code that does this, but we are talking about global variables here... any code anywhere can change out this reference. Caching the reference in appsettings CAN be dangerous in cases like these... one of the many pitfalls of being coupled to static variables, IMO.

Related

Is it bad coding style to not assign a new instance to a variable?

At the top of my program I have a code segment that looks like this
var XXXAssembler = new XXXAssembler(ctx);
XXXAssembler.LoadXXX();
var YYYAssembler = new YYYAssembler(ctx );
YYYAssembler.LoadYYY();
var ZZZAssembler = new ZZZAssembler(ctx);
ZZZAssembler.LoadZZZ();
In the above logic I use each varaible once to call the respective loader, and I don't use the variables anywhere else.
I can change the code to this
new XXXAssembler(ctx).LoadXXX();
new YYYAssembler(ctx ).LoadYYY();
new ZZZAssembler(ctx).LoadZZZ();
This reduces the size of the code, but I'd like to think it simplifies it as well. I could see the usefulness of variables for debugging, but I don't think that's necessarily a good reason. Others may disagree.
Is the non-varaible version considered bad coding style?
Unless you're going to use the object assigned to the Assembler variable, then there's no need for it.
I'd say get rid of it, clean up the code, and then if you need it later you can bring it back.
new XXXAssembler(ctx).LoadXXX(); is absolutely fine as long as you don't have use the reference returned by new XXXAssembler(ctx) elsewhere.
If u ask me, the size of the code doesn't matters. Only matter is that, when you see the code 1 year later, to know how it does what it needs to do, and how to rewrite / reuse / etc.
As you mention, the only technical reason to assign the created object to a variable is if you need to use it or look at it somewhere. If you're confident that you'll never need to do this, you don't need to create a new variable, and you can shorten up your code a bit.
But I'll offer up two caveats:
(1) I often find that I need to look at the output of a method before it returns, or at the instance of the object created by the new statement when I'm debugging. So sometimes instead of doing this:
public MyObject ReturnSomeObject()
{
return new MyObject();
}
I'll do this instead:
public MyObject ReturnSomeObject()
{
var myObject = new MyObject();
return myObject;
}
Just so I can look at it in the debugger. It clutters up my code a bit, but it can be very helpful when I'm trying to figure out why something else went wrong.
(2) If you find that you can do the sort of thing you're describing very often, you may want to take a harder look at how your classes are structured. What's the point of a class that has a method that returns nothing and which doesn't modify the internal state of the class in any fashion that you're interested in? To take your example above, presumably your various LoadXXX() methods should return some sort of status code, or modify some status property of the object, or return a pointer to the file that they loaded, or, well, something. If they do, but you're not bothering to look at it - well, that's another problem. If the methods really don't need to modify any aspect of the object's internal state, then you should look strongly at making them static: it allows you to avoid running the class constructor each time you call them, it expresses their intent more clearly, and it allows the compiler to notify you of a possible inconsistency if you do decide that they need to modify the object state at some point in the future.
Nothing hard-and-fast here, just some guidelines.
If you are never going to use the Object again, but for this case, I don't see the point in giving them names. It adds needless lines of clutter to your code.
I think not assiging to a variable is fine. I do this in many cases, e.g. for some unittest mocks new Mock<IInterfaceToMock>.Object or for callbacks functors SomeFunctionAcceptingCallback(args, new CallbackHandler()).

Any reason not to use `new object().foo()`?

When using extremely short-lived objects that I only need to call one method on, I'm inclined to chain the method call directly to new. A very common example of this is something like the following:
string noNewlines = new Regex("\\n+").Replace(" ", oldString);
The point here is that I have no need for the Regex object after I've done the one replacement, and I like to be able to express this as a one-liner. Is there any non-obvious problem with this idiom? Some of my coworkers have expressed discomfort with it, but without anything that seemed to be like a good reason.
(I've marked this as both C# and Java, since the above idiom is common and usable in both languages.)
This particular pattern is fine -- I use it myself on occasion.
But I would not use this pattern as you have in your example. There are two alternate approaches that are better.
Better approach: Use the static method Regex.Replace(string,string,string). There is no reason to obfuscate your meaning with the new-style syntax when a static method is available that does the same thing.
Best approach: If you use the same static (not dynamically-generated) Regex from the same method, and you call this method a lot, you should store the Regex object as a private static field on the class containing the method, since this avoids parsing the expression on each call to the method.
I don't see anything wrong with this; I do this quite frequently myself.
The only exception to the rule might be for debugging purposes, it's sometimes necessary to be able to see the state of the object in the debugger, which can be difficult in a one-liner like this.
If you don't need the object afterwards, I don't see a problem - I do it myself from time to time as well. However, it can be quite hard to spot, so if your coworkers are expressing discomfort, you might need to put it into a variable so there are no hard feelings on the team. Doesn't really hurt you.
You just have to be careful when you're chaining methods of objects that implement IDisposable. Doing a single-line chain doesn't really leave room for calling Dispose or the using {...} block.
For example:
DialogResult result = New SomeCfgDialog(some_data).ShowDialog();
There is no instance variable on which to call Dispose.
Then there is potential to obfuscate intent, hurt rather than improve readability and make it tougher to examine values while debugging. But those are all issues particular to the object and the situation and the number of methods chained. I don't think that there is a single reason to avoid it. Sometimes doing this will make the code more concise and readable and other times it might hurt for some of the reasons mentioned above.
As long as you're sure that the object is never needed again (or you're not creating multiple instances of an identical object), then there's no problem with it.
If the rest of your team isn't comfortable with it, though, you might want to re-think the decision. The team should set the standards and you should follow them. Be consistent. If you want to change the standard, discuss it. If they don't agree, then fall in line.
I think thats ok, and would welcome comments/reasons to the contrary. When the object is not short lived (or uses unmanaged resources - ie COM) then this practice can get you into trouble.
The issue is readability.
Putting the "chained" methods on a separate line seems to be the preferred convention with my team.
string noNewlines = new Regex("\\n+")
.Replace(" ", oldString);
One reason to avoid this style is that your coworkers might want to inspect the object in a debug mode. If you compound the similar instantiation the readability goes down a lot. For example :
String val = new Object1("Hello").doSomething(new Object2("interesting").withThis("input"));
Generally I prefer using a static method for the specific example you have mentioned.
The only potential problem I could see is - if, for some reason, new Regex were NULL because it was not instantiated correctly, you would get a Null Pointer Exception. However, I highly doubt that since Regex is always defined...
If you don't care about the object you invoke the method on, that's a sign that the method should probably be static.
In C#, I'd probably write an extension method to wrap the regex, so that I could write
string noNewlines = oldString.RemoveNewlines();
The extension method would look something like
using System.Text.RegularExpressions;
namespace Extensions
{
static class SystemStringExtensions
{
public static string RemoveNewlines(this string inputString)
{
// replace newline characters with spaces
return Regex.Replace(inputString, "\\n+", " ");
}
}
}
I find this much easier to read than your original example. It's also quite reusable, as stripping newline characters is one of the more common activities.

Should I fully declare throw-away objects?

If I need to do something like this:
var connection = new Connection(host);
connection.Execute(Commands.Delete);
Is there anything wrong in doing this:
(new Connection(host)).Execute(Commands.Delete);
The first example may be more readable, but the second works better if I need to do this multiple times:
(new Connection(anotherHost)).Execute(Commands.Create);
(new Connection(someOtherHost)).Execute(Commands.Update);
(new Connection(host)).Execute(Commands.Delete);
Does your Connection class implement IDisposable? Then:
using (var connection = new Connection(host))
{
connection.Execute(Commands.Delete);
}
First thing I am a Java person and I havent used C#
But based on your code and knowing similarity with java what I can say is -
If your Connection class maintains a state information then its meaningful to create new object every time. But if it is stateless then its pretty inefficient to create multiple objects. You can create one and re-use the same.
i.e. If you cannot set the 'host' to a connection once created, then both approaches you mentioned should not make any difference.
The more verbose you are, the easier of a time you will have debugging.
The effect on your code readability really depends on how much you're trying to wrap into one line - if you've got a single idea that just takes a lot of different words to express, putting it in one line isn't a big deal in my opinion. But if you're trying to cram multiple ideas into one line you'll lose clarity.
For instance. We'll start with a simple idea that just takes some space to express:
transactionTime = generationTime + retrievalTime + processingTime + loggingTime
And here we have a more complex idea that we happen to express in one line:
logTransactionData(processTransaction(retrieveTransaction(generateTransactionQuery())))
I think that the first example is easier to understand at a glance than the second, even though they're about the same in character length.
So in general: consider how likely it is you'll need to debug the line, as well as your idea-complexity-to-line ratio.
Yes, you're initializing a new object, using it, and loosing it! you cannot reuse it again and it's gonna be there somewhere, until GC collects it! So, there's no harm in storing new initialized objects in a variable, and declaring them in another line makes your code more readable.

In C# should I reuse a function / property parameter to compute cleaner temporary value or create a temporary variable?

The example below may not be problematic as is, but it should be enough to illustrate a point. Imagine that there is a lot more work than trimming going on.
public string Thingy
{
set
{
// I guess we can throw a null reference exception here on null.
value = value.Trim(); // Well, imagine that there is so much processing to do
this.thingy = value; // That this.thingy = value.Trim() would not fit on one line
...
So, if the assignment has to take two lines, then I either have to abusereuse the parameter, or create a temporary variable. I am not a big fan of temporary variables. On the other hand, I am not a fan of convoluted code. I did not include an example where a function is involved, but I am sure you can imagine it. One concern I have is if a function accepted a string and the parameter was "abused", and then someone changed the signature to ref in both places - this ought to mess things up, but ... who would knowingly make such a change if it already worked without a ref? Seems like it is their responsibility in this case. If I mess with the value of value, am I doing something non-trivial under the hood? If you think that both approaches are acceptable, then which do you prefer and why?
Thanks.
Edit: Here is what I mean when I say I am not a fan of temp variables. I do not like code like this:
string userName = userBox.Text;
if (userName.Length < 5) {
MessageBox.Show("The user name " + userName + " that you entered is too short.");
....
Again, this may not be the best way to communicate a problem to the user, but it is just an illustration. The variable userName is unnecessary in my strong opinion in this case. I am not always against temporary variables, but when their use is very limited and they do not save that much typing, I strongly prefer not to use them.
First off, it's not a big deal.
But I would introduce a temp variable here. It costs nothing and is less prone to errors. Imagine someone has to maintain the code later. Better if value only has 1 meaning and purpose.
And don't call it temp, call it cleanedValue or something.
It is a good practice not to change the values of incoming parameters, even if you technically can. Don't touch the value.
I am not a big fan of temporary variables.
Well, programming is largely about creating temporary variables all over the place, reading and assigning values. You'd better start to love them. :)
One more remark regarding properties. Although you could technically put a lot of logic there, it is recommended to keep properties simple and try not to use any code that could throw exceptions. A need to call other functions may indicate that this property is better be made a method or that there is some initialization code needed somewhere. Just rethink what you're doing and whether it does really look like a property.

Anonymous Instantiation Syntax - Good or Bad?

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

Categories

Resources