Should I created class or create if? - c#

I have a situation:
I nee to do something with a class.
What should be more efficiente, modify the method this way witf IFs or created methos for each action?
public value Value(int command)
{
if (command == 1)
{
DoSomething1();
}
if (command == 2)
{
DoSomething2();
}
else
{
return empty();
}
}
There are going to be like 50 o more of this commands.
Whats isbetter in terms of performance on execution and size of the exectuable?

At a high-level, it looks like you're trying to implement some kind of dynamic-dispatch system? Or are you just wanting to perform a specified operation without any polymorphism? It's hard to tell.
Anyway, based on the example you've given, switch block would be the most performant, as the JIT compiler converts it into an efficient hashtable lookup instead of a series of comparisons, so just do this:
enum Command { // observe how I use an enum instead "magic" integers
DoSomethingX = 1,
DoSomethingY = 2
}
public Value GetValue(Command command) {
switch(command) {
case Command.DoSomethingX: return DoSomethingX();
case Command.DoSomethingY: return DoSomethingY();
default: return GetEmpty();
}
}
I also note that the switch block also means you get more compact code.

This isn't a performance problem as much as it is a paradigm problem.
In C# a method should be an encapsulation of a task. What you have here is a metric boatload of tasks, each unrelated. That should not be in a single method. Imagine trying to maintain this method in the future. Imagine trying to debug this, wondering where you are in the method as each bit is called.
Your life will be much easier if you split this out, though the performance will probably make no difference.

Although separate methods will nearly certainly be better in terms of performance, it is highly unlikely that you should notice the difference. However, having separate methods should definitely improve readability a lot, which is a lot more important.

Related

Best way to check that at least one textbox of many has content?

I have a 'search page' where it is required that at least one textbox has some input. The following method verifies this like so:
if (!String.IsNullOrEmpty(txtNome.Text))
{
return true;
}
if (!String.IsNullOrEmpty(txtEndereco.Text))
{
return true;
}
if (!String.IsNullOrEmpty(txtCidade.Text))
{
return true;
}
if (!String.IsNullOrEmpty(txtCEP.Text))
{
return true;
}
return false;
There hasn't been any problems with the results from this method. My question is related to performance: Is there a better way to make this check? One possible alternative I've thought of:
string X = String.Concat(txtNome.Text,...,txtCEP.Text)
if(!String.IsNullOrEmpty(X))
{
return true;
}
I think that using the if-return pattern is better when the first field isn't empty, but for other use-cases, using String.Concat is better.
Could someone let me know which way is better and why? Is there another, even better way?
If all the controls are of the same type, you could put all the controls you want to check in an array then use Linq's Any extension method:
return new[] { txtNome, txtEndereco, txtCidade, txtCEP }
.Any(x => !String.IsNullOrEmpty(x.Text));
Or alternatively, if not all of the controls are of the same type, create an array of strings:
return new[] { txtNome.Text, txtEndereco.Text, txtCidade.Text, txtCEP.Text }
.Any(x => !String.IsNullOrEmpty(x));
The performance difference between this and a plain old if-else-block will be negligible.
From a pure performance standpoint, the only way your original method could get more efficient is if you wrote the checks in order of the most used to least used.
But simple operations like comparing values are near-instantaneous for even old, outdated technology. Trying to optimize here is a genuine waste of your time. Instead focus on learning ways to write code quicker and more concisely, so when you re-visit the code in the future, it will be much easier to understand and modify. p.s.w.g's answer shows how you can leverage linq; I'd recommend trying that out.
On a side note, I'd recommend that you instead of String.IsNullOrEmpty(), you use String.IsNullOrWhiteSpace(). Again, it does requires a slight additional performance overhead, but it is much more useful.

Switch inside loops impacting performance?

I'm in a scenario where I'm looping through data and formatting it in specific ways based on a setting, and I'm concerned that what I feel is best stylistically might impede performance.
The basic pattern of the code is as follows
enum setting {single, multiple, foo, bar};
Data data = getData(Connection conn, int id);
setting blah = data.getSetting();
foreach (Item item in data)
{
switch(blah)
{
case blah.single:
processDataSingle(item blah);
break;
...
}
}
My concern is that there might be thousands, or even tens of thousands of items in data. I was wondering if having the switch inside the loop where it may be evaluated repeatedly might cause some serious performance issues. I know I could put the switch before the loop, but then each case contains it, which seems much less readable, in that it's less apparent that the basic function remains the same.
You could set up a delegate/action once, then call it every time in the loop:
Data data = getData(Connection conn, int id);
setting blah = data.getSetting();
Action<Item> doThis;
switch (blah)
{
case blah.single:
doThis = i => processSingleData(i blah);
break;
...
}
foreach (Item item in data)
{
doThis(item);
}
Basically, put the body of each "case" in an Action, select that Action in your switch outside the loop, and call the Action in the loop.
You could create a method to keep readability, then pass the data to the method:
void processAllData(IEnumerable<Item> data, setting blah)
{
switch(blah)
{
case blah.single:
foreach (Item item in data)
{
}
}
// next case, next loop ...
}
Then it's just a one-liner:
processAllData(data, blah);
This approach is readable since it encapsulates complexity, concise since you only see what you have to see and efficient since you can optimize the cases.
By using a Action delegate this way, you can factorize your code a lot
enum setting {single, multiple, foo, bar};
Data data = getData(Connection conn, int id);
var processAll = new Action<Action<item>>(action =>
{
foreach(var item in data)
action(item);
});
setting blah = data.getSetting();
switch(blah)
{
case blah.single:
processAll(item => processDataSingle(item, blah));
break;
...
}
It certainly does have the potential to affect performance if you're talking about possibly running the comparison tens of thousands of times or more. The other problem that could potentially arise in the code that you've written here is what happens if you need to add to your enum. Then you'd need to open up this code and adjust it to take care of that circumstance, which violates the Open/Closed Principle.
The best way, IMO, to solve both problems at once would be to use a Factory pattern to take care of this (see posts here and here for some advice on starting that). All you'd need to do is have an interface whose implementations would call the method that you'd want to call in your switch code above. Create a factory and have it pick which implementation to return back to your code (before the loop) based on the enum passed in. At that point all your loop needs to do is to call that interface method which will do exactly what you wanted.
Afterwards, any future feature additions will only require you to create another implementation of that interface, and adjust the enum accordingly. No muss, no fuss.
It's almost certainly slower to put the switch in the loop like that. Whether it's significant or not is impossible to say - use a Stopwatch to see.
If the values in the switch statement are near one to another, the compiler will produce a lookup table instead of N if statements. It increases performance, but it's hard to say when the compiler will decide to do this.
Instead you can create a Dictionary<switchType,Delegate>, populate it with pairs of value-action, and then selecting the appropriate action will take about O(1) as dictionary is a hash table.
dictionary[value].Invoke().

Is there any reason to use the 'return' in the second line in the method ?

I have this code that we can write in two ways
First Way
void func(int val)
{
if(val == 0)
return;
// Do something ...
}
Second Way
void func(int val)
{
if(val != 0)
{
// Do something ...
}
}
The Question:
Is there any reason to use the first way ?
Is there any Advantage to use the first way ( in C++ or in C# )
The main reason to use the first way is to reduce nesting in your source file.
See Invert “if” statement to reduce nesting.
Basically this becomes important when '// Do something ...' is a lot of code.
Imagine, that there's more than one condition, and look at this:
if (...)
{
if (...)
{
if (...)
{
if (...)
{
if (...)
{
...
}
}
}
}
}
and this:
if (!...)
return;
if (!...)
return;
if (!...)
return;
if (!...)
return;
if (!...)
...
I think, the second one is more readable an convenient.
If there's one or two conditions, the difference is insignificant.
Yes there are advantages as mentioned in previous answers. Since it is tagged in C++ care should be taken for freeing the allocated memory in case of using First Way.
For Eg there can be bad code like this
void func(int val)
{
Foo *obj = new Foo();
if(val == 0)
return;
// Do something ...
delete obj; // Possible Memory leak
}
There is no difference - whether to use one or the other depends entirely on your subjective preference for one or the other, influenced by readability, understandability, etc
if you want to exit quick on a defined value, so return before should be better,
but if this case is rare, so probably it's better to directly work on good data.
depending on which language you use, implications on performance should be greater, or insignificant.
if it's intended for clarity, so make some functions called after conditions should be good.
Some parts manage different cases, some parts process it.
maintainability and readability should be improved this way.
if you call as the first way then its not run the rest of the things. because it return directly. but if you use second way the codes inside the will run.
Void methods do not require a return statement always. But you can use a 'return' in a strategic place to avoid executing unnecessary statements when you have encountered an exit condition.

Is it bad practice to use return inside a void method?

Imagine the following code:
void DoThis()
{
if (!isValid) return;
DoThat();
}
void DoThat() {
Console.WriteLine("DoThat()");
}
Is it OK to use a return inside a void method? Does it have any performance penalty? Or it would be better to write a code like this:
void DoThis()
{
if (isValid)
{
DoThat();
}
}
A return in a void method is not bad, is a common practice to invert if statements to reduce nesting.
And having less nesting on your methods improves code readability and maintainability.
Actually if you have a void method without any return statement, the compiler will always generate a ret instruction at the end of it.
There is another great reason for using guards (as opposed to nested code): If another programmer adds code to your function, they are working in a safer environment.
Consider:
void MyFunc(object obj)
{
if (obj != null)
{
obj.DoSomething();
}
}
versus:
void MyFunc(object obj)
{
if (obj == null)
return;
obj.DoSomething();
}
Now, imagine another programmer adds the line: obj.DoSomethingElse();
void MyFunc(object obj)
{
if (obj != null)
{
obj.DoSomething();
}
obj.DoSomethingElse();
}
void MyFunc(object obj)
{
if (obj == null)
return;
obj.DoSomething();
obj.DoSomethingElse();
}
Obviously this is a simplistic case, but the programmer has added a crash to the program in the first (nested code) instance. In the second example (early-exit with guards), once you get past the guard, your code is safe from unintentional use of a null reference.
Sure, a great programmer doesn't make mistakes like this (often). But prevention is better than cure - we can write the code in a way that eliminates this potential source of errors entirely. Nesting adds complexity, so best practices recommend refactoring code to reduce nesting.
Bad practice??? No way. In fact, it is always better to handle validations by returning from the method at the earliest if validations fail. Else it would result in huge amount of nested ifs & elses. Terminating early improves code readability.
Also check the responses on a similar question: Should I use return/continue statement instead of if-else?
It's not bad practice (for all reasons already stated). However, the more returns you have in a method, the more likely it should be split into smaller logical methods.
The first example is using a guard statement. From Wikipedia:
In computer programming, a guard is a
boolean expression that must evaluate
to true if the program execution is to
continue in the branch in question.
I think having a bunch of guards at the top of a method is a perfectly understandable way to program. It is basically saying "do not execute this method if any of these are true".
So in general it would like this:
void DoThis()
{
if (guard1) return;
if (guard2) return;
...
if (guardN) return;
DoThat();
}
I think that's a lot more readable then:
void DoThis()
{
if (guard1 && guard2 && guard3)
{
DoThat();
}
}
There is no performance penalty, however the second piece of code is more readable and hence easier to maintain.
In this case, your second example is better code, but that has nothing to do with returning from a void function, it's simply because the second code is more direct. But returning from a void function is entirely fine.
It's perfectly okay and no 'performance penalty', but never ever write an 'if' statement without brackets.
Always
if( foo ){
return;
}
It's way more readable; and you'll never accidentally assume that some parts of the code are within that statement when they're not.
I'm going to disagree with all you young whippersnappers on this one.
Using return in the middle of a method, void or otherwise, is very bad practice, for reasons that were articulated quite clearly, nearly forty years ago, by the late Edsger W. Dijkstra, starting in the well-known "GOTO Statement Considered Harmful", and continuing in "Structured Programming", by Dahl, Dijkstra, and Hoare.
The basic rule is that every control structure, and every module, should have exactly one entry and one exit. An explicit return in the middle of the module breaks that rule, and makes it much harder to reason about the state of the program, which in turn makes it much harder to say whether the program is correct or not (which is a much stronger property than "whether it appears to work or not").
"GOTO Statement Considered Harmful" and "Structured Programming" kicked off the "Structured Programming" revolution of the 1970s. Those two pieces are the reasons we have if-then-else, while-do, and other explicit control constructs today, and why GOTO statements in high-level languages are on the Endangered Species list. (My personal opinion is that they need to be on the Extinct Species list.)
It is worth noting that the Message Flow Modulator, the first piece of military software that EVER passed acceptance testing on the first try, with no deviations, waivers, or "yeah, but" verbiage, was written in a language that did not even have a GOTO statement.
It is also worth mentioning that Nicklaus Wirth changed the semantics of the RETURN statement in Oberon-07, the latest version of the Oberon programming language, making it a trailing piece of the declaration of a typed procedure (i.e., function), rather than an executable statement in the body of the function. His explication of the change said that he did it precisely because the previous form WAS a violation of the one-exit principle of Structured Programming.
While using guards, make sure you follow certain guidelines to not confuse readers.
the function does one thing
guards are only introduced as the first logic in the function
the unnested part contains the function's core intent
Example
// guards point you to the core intent
void Remove(RayCastResult rayHit){
if(rayHit== RayCastResult.Empty)
return
;
rayHit.Collider.Parent.Remove();
}
// no guards needed: function split into multiple cases
int WonOrLostMoney(int flaw)=>
flaw==0 ? 100 :
flaw<10 ? 30 :
flaw<20 ? 0 :
-20
;
Throw exception instead of returning nothing when object is null etc.
Your method expects object to be not null and is not the case so you should throw exception and let caller handle that.
But early return is not bad practice otherwise.

Implementing a "LazyProperty" class - is this a good idea?

I often find myself writing a property that is evaluated lazily. Something like:
if (backingField == null)
backingField = SomeOperation();
return backingField;
It is not much code, but it does get repeated a lot if you have a lot of properties.
I am thinking about defining a class called LazyProperty:
public class LazyProperty<T>
{
private readonly Func<T> getter;
public LazyProperty(Func<T> getter)
{
this.getter = getter;
}
private bool loaded = false;
private T propertyValue;
public T Value
{
get
{
if (!loaded)
{
propertyValue = getter();
loaded = true;
}
return propertyValue;
}
}
public static implicit operator T(LazyProperty<T> rhs)
{
return rhs.Value;
}
}
This would enable me to initialize a field like this:
first = new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value });
And then the body of the property could be reduced to:
public HeavyObject First { get { return first; } }
This would be used by most of the company, since it would go into a common class library shared by most of our products.
I cannot decide whether this is a good idea or not. I think the solutions has some pros, like:
Less code
Prettier code
On the downside, it would be harder to look at the code and determine exactly what happens - especially if a developer is not familiar with the LazyProperty class.
What do you think ? Is this a good idea or should I abandon it ?
Also, is the implicit operator a good idea, or would you prefer to use the Value property explicitly if you should be using this class ?
Opinions and suggestions are welcomed :-)
Just to be overly pedantic:
Your proposed solution to avoid repeating code:
private LazyProperty<HeavyObject> first =
new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value });
public HeavyObject First {
get {
return first;
}
}
Is actually more characters than the code that you did not want to repeat:
private HeavyObject first;
public HeavyObject First {
get {
if (first == null) first = new HeavyObject { MyProperty = Value };
return first;
}
}
Apart from that, I think that the implicit cast made the code very hard to understand. I would not have guessed that a method that simply returns first, actually end up creating a HeavyObject. I would at least have dropped the implicit conversion and returned first.Value from the property.
Don't do it at all.
Generally using this kind of lazy initialized properties is a valid design choice in one case: when SomeOperation(); is an expensive operation (in terms of I/O, like when it requires a DB hit, or computationally) AND when you are certain you will often NOT need to access it.
That said, by default you should go for eager initialization, and when profiler says it's your bottleneck, then change it to lazy initialization.
If you feel urge to create that kind of abstraction, it's a smell.
Surely you'd at least want the LazyPropery<T> to be a value type, otherwise you've added memory and GC pressure for every "lazily-loaded" property in your system.
Also, what about multiple-threaded scenarios? Consider two threads requesting the property at the same time. Without locking, you could potentially create two instances of the underlying property. To avoid locking in the common case, you would want to do a double-checked lock.
I prefer the first code, because a) it is such a common pattern with properties that I immediately understand it, and b) the point you raised: that there is no hidden magic that you have to go look up to understand where and when the value is being obtained.
I like the idea in that it is much less code and more elegant, but I would be very worried about the fact that it becomes hard to look at it and tell what is going on. The only way I would consider it is to have a convention for variables set using the "lazy" way, and also to comment anywhere it is used. Now there isn't going to be a compiler or anything that will enforce those rules, so still YMMV.
In the end, for me, decisions like this boil down to who is going to be looking at it and the quality of those programmers. If you can trust your fellow developers to use it right and comment well then go for it, but if not, you are better off doing it in a easily understood and followed way. /my 2cents
I don't think worrying about a developer not understanding is a good argument against doing something like this...
If you think that then you couldn't do anything for the fear of someone not understanding what you did
You could write a tutorial or something in a central repository, we have here a wiki for these kind of notes
Overall, I think it's a good implementation idea (not wanting to start a debate whether lazyloading is a good idea or not)
What I do in this case is I create a Visual Studio code snippet. I think that's what you really should do.
For example, when I create ASP.NET controls, I often times have data that gets stored in the ViewState a lot, so I created a code snippet like this:
public Type Value
{
get
{
if(ViewState["key"] == null)
ViewState["key"] = someDefaultValue;
return (Type)ViewState["key"];
}
set{ ViewState["key"] = value; }
}
This way, the code can be easily created with only a little work (defining the type, the key, the name, and the default value). It's reusable, but you don't have the disadvantage of a complex piece of code that other developers might not understand.
I like your solution as it is very clever but I don't think you win much by using it. Lazy loading a private field in a public property is definitely a place where code can be duplicated. However this has always struck me as a pattern to use rather than code that needs to be refactored into a common place.
Your approach may become a concern in the future if you do any serialization. Also it is more confusing initially to understand what you are doing with the custom type.
Overall I applaud your attempt and appreciate its cleverness but would suggest that you revert to your original solution for the reasons stated above.
Personally, I don't think the LazyProperty class as is offers enough value to justify using it especially considering the drawbacks using it for value types has (as Kent mentioned). If you needed other functionality (like making it multithreaded), it might be justified as a ThreadSafeLazyProperty class.
Regarding the implicit property, I like the "Value" property better. It's a little more typing, but a lot more clear to me.
I think this is an interesting idea. First I would recommend that you hide the Lazy Property from the calling code, You don't want to leak into your domain model that it is lazy. Which your doing with the implicit operator so keep that.
I like how you can use this approach to handle and abstract away the details of locking for example. If you do that then I think there is value and merit. If you do add locking watch out for the double lock pattern it's very easy to get it wrong.

Categories