Nesting methods advisable? - c#

Basically, say I have a method:
string MyMethod(string someVar);
And I need to use the return value in another method, is it advisable to do:
string myString = AnotherMethod(MyMethod(someString));
rather than:
string anotherString = MyMethod(someString);
string returnValue = AnotherMethod(anotherString);

Personally, I would use the longer version - it is more readable and makes debugging easier.
Calling a method in the parameter list of another method can be confusing to the reader.
There is a minor impact on memory usage with the longer version, as you have one additional variable that needs to be allocated, but this would be minimal.

For testing and debugging purposes (setting breakpoints/inspecting the results from each call separately) the longer version is the one I would prefer.
Regarding speed/efficiency there should be no measurable diference IMHO.

i would also prefer 2nd option.
cause it is less complex to understand and use too.

The longer one is more readable and easy to debug.
It is quite easy to set a breakpoint on the line of
string anotherString = MyMethod(someString);
Also, you can add watch on the varieable "anotherString" as well.

Related

Is there any benefit of working on string directly rather than assigning it to a var?

Is there any benefit of doing this;
private void Method()
{
var data = ConfigurationManager.AppSettings["Data"].Split('-');
}
than doing this;
private void Method()
{
var _data = ConfigurationManager.AppSettings["Data"];
var data = _data.Split('-');
}
Case: I need to read bunch of configuration values like this in the same method, multiple times (let's say every time I instantiate this class).
How will both cases will affect the performance and memory? Or are they pretty much the same things? I see assigning it to a variable will allocate space on memory for no reason.
There will be the same IL code generated in both cases.
And don't forget about The Rules of Code Optimization
The compiler will reduce those to the exact same thing. No, there's no difference in this scenario. If you're ever curious, compile it in release mode, and use ildasm to look at what it did.
However! Performance questions should never be answered by hunch - or even asked on hunch. First, determine if you are actually trying to solve a real problem - otherwise you're probably just yak shaving.
In your first case since ConfigurationManager.AppSettings["Data"] will return a string there is no harm in chaining the Split() method with it than creating a extra variable.
In second case, it would be efficient if ConfigurationManager.AppSettings["Data"] would be used multiple places. In such case, instead of fetching it again and again, you fetch it once, store it to a variable and re-use it.
Both statements are equal. You have a false understanding on when space on your memory is allocated. This actually happens inside the AppSettings-call, not on assignement. Thus when you make any call to a member the result allready exists on memory. Storing this value in a variable does not increase anything - neither memory-allocation nor performance.
However if you´d store the result in a member of your class it´ll be garbage-collected far later than your local data-variable as it doesn´t get out of scope. In this case storing your result to the member will allocate memory as long as the instance exists.
Having said this it is in mostly all cases more important to focus on your code being maintainable, that is if other developers can understand it without asking what all this about.
This means you shouldn´t ask: which horse runs faster but instead which code is easier to understand?

Any harm in changing a void return type to something else in a commonly used utility function?

if I have a function like
public void usefulUtility(parameters...) {
string c = "select * from myDB";
do_a_database_call(c);
}
that's used in alot of places, is there any possible harm in changing it to:
public bool usefulUtility(parameters...) {
string c = "select * from myDB";
bool result = do_a_database_call(c);
return result;
}
Could this possibly break any code?
I can't think of anything... but it may be possible?
Yes, virtually anything that you could possibly do that affects your public interface is a breaking change. It could be small enough that you don't care, and that nobody, or almost nobody, will actually happen to hit the corner cases, but Eric Lippert explains that there are edge cases (many of which involve Type inference) that can cause even these seemingly innocuous changes to break.
For your particular example, this code would be broken by that change.
Action a = usefulUtility;
A change like this could definitely break stuff, both in terms of binary compatibility and in terms of source compatibility.
You might want to have a look at this StackOverflow answer and its associated thread, where API-breaking changes are discussed in depth.
It's certainly possible that it could break some other code. As Lippert points out, nearly Every public change is a breaking change in some bizarre situation.
The more important question is, is it likely to cause anything to break, and the answer is no. You should be pretty safe making this change, because people aren't likely to do the bizarre kinds of things they would have to do for this to cause problems. That doesn't mean it's impossible to break some other code, but it's outside the realm of reasonable responsibility.
You would have to actually return a String or at least null for the method to compile. You could no longer end the method without a return.
If you want to be absolutely sure of not breaking anything, give the method that returns a String a different name, and leave the void method signature the same.

Is there a simpler way to call Contains() on a string that is potentially null?

Is there a simpler or less ugly way to call .Contains() on a string that is potentially null then by doing:
Assert.IsTrue((firstRow.Text ?? "").Contains("SomeText"));
I'd suggest using Assert.That syntax:
Assert.That(firstRow.Text, Does.Contain("SomeText"));
If you need to check that text is not containing a certain string:
Assert.That(firstRow.Text, Does.Not.Contain("SomeText"));
I think any of these alternatives are better, even though they are not quite as short:
// 1
Assert.IsTrue(firstRow.Text != null && firstRow.Text.Contains("SomeText"));
// 2
Assert.IsNotNull(firstRow.Text);
Assert.IsTrue(firstRow.Text.Contains("SomeText"));
// 3
var text = firstRow.Text;
Assert.IsTrue(text != null && text.Contains("SomeText"));
I think "simple" is a subjective term. Simple, to me, means "clear and easy to read", not "fewest number of characters".
Considering that this code appears to be part of a unit test, Option #2 would be best, because then you can tell from reading the test results whether the test failed due to a null value or failed because the value did not contain the expected text. Otherwise, you would have to re-execute this test with a debugger and look at the value at runtime in order to distinguish between these two cases.
"Make things as simple as possible, but not simpler." - Albert Einstein
This is one character shorter, but frankly I like your original code better.
Assert.IsTrue((firstRow.Text + "").Contains("SomeText"));
No, there aren't any. But you could write an extension method for that:
public static bool SContains(this string source, string query)
{
return source != null && source.Contains(query);
}
I would expect the string being null exposes a different error to the string not being "SomeText", in which case it would be better to have two unit tests to test the different outcomes.
In terms of methods how about using StringAssert and IsNotNull?
Assert.IsNotNull(firstRow.Text);
StringAssert.Contains(firstRow.Text, "SomeText");
(I am assuming this relates to a unit test)
According to http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.stringassert(v=vs.100).aspx
StringAssert class can be used to easily assert whether or not the stringUnderTest contains the specefied string
I think a plain No,
This would be a little less ugly and gets the implied readability
If(!string.IsNullOrEmpty(firstRow.Text))
Assert.IsTrue(firstRow.Text.Contains("SomeText"));
I would generally use something more like the following which is longer and less clever but idiomatic c# and the intent is obvious.
Assert.IsTrue( !string.IsNullOrWhiteSpace(firstRow.Text))
Assert.IsTrue( firstRow.Text.Contains("SomeText"));
In my interpretation of the question, the empty string is an error condition. That's one reason I prefer my version - the context for the test is explicit. If I wanted to include the empty string as a valid result I would use the following as the first condition, again making the test explicit:
Assert.IsNotNull(firstRow.Text)
To me this is far more important than shortening the code. In a month when I (or someone else) come back to make changes to the code it is obvious what the intent of the test is. In the original question, not so much.

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.

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