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.
I frequently run into the following problem, I was wondering if there is any better way to deal with it:
if (A || B)
{
//Start stuff if either A or B is true. Then:
if (A && B)
//DoSomething
else if (A && !B)
//DoSomething
else if (B && !A)
//DoSomething
}
I'm asking because the if-elseif-elseif eventually looks like a big mess to read through, when the comments are replaced by code. Not even talking about what to do when theres a C involved. Any help is welcome~
At the very least, the two last conditions are a bit redundant and can be simplified:
if (A && B)
//DoSomething
else if (A)
//DoSomething
else if (B)
//DoSomething
Since we already know that both cannot be true. Apart from that, I don’t see how this could be simplified much further. Since you are essentially interested in each permutation of cases, you fundamentally need to treat them all.
This can't really be answered, but anyway, here are some thoughts:
Use Polymorphism
Factor out methods
Related
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 9 years ago.
I have some critical production routines need to be rewritten from scratch. Take a simple example:
public class ProductionClass {
public IList<Values> WillBeFiredIfThisBreaks(Input input) {
...
}
}
The input object has way too many permutations to unit test thoroughly, and I want to play it safe because these routines are heavily used everyday. So, my thought was to:
1) Rename and mark the current implementation as obsolete.
2) Write a new implementation that falls back on the old one if there are any issues (see below)
3) Remove the old implementation after the new one has been running in prod for a month or two without issues.
public class ProductionClass {
public IList<Values> WillBeFiredIfThisBreaks(Input input) {
try{
var ret = NewImpl(input);
} catch(Exception){
ret = null;
}
if(ret == null || ret.Count == 0){
Log.Error("NewImpl Failed! Inputs: {0}", inputs);
return OldImpl(input);
}
return ret;
}
public IList<Values> NewImpl(Input input) {
...
}
[Obsolete("Rewritten 03/18/2013, throw away once NewImpl confirmed stable", false)]
public IList<Values> OldImpl(Input input) {
...
}
}
The above approach is a bit ugly in that I'll have to go through and recreate this logic for every method that I need to rewrite. (And I'll correspondingly need to remove the fallback logic and delete the obsolete methods in every location when the new code is confirmed stable). So my question is: Are there any .NET frameworks or design patterns which make this sort of "ultra-paranoid" code rewrite a bit more elegant?
Since you ask for a pattern, a possible response is to use AOP with method weaving. But a better response would be concentrate your effort in creating the unit test.
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.
Just wonder which approach is faster and better to use or which do you prefer
bool userHavePermission = user.Permissions.Any(x => x.UpperName == "ADMINISTRATOR");
or
foreach (Permission p in _Permissions)
{
if (p.UpperName == name.ToUpper())
return true;
}
return false;
Thanks
It's almost same code, the only difference being that with the second code snippet you're gonna get a NullReferenceException at runtime if the name variable is null because you will be calling the .ToUpper() method on a null instance. The first looks shorter, safer and more readable, it's what I would use. And to ensure that there won't be any NREs:
return user
.Permissions
.Any(x => string.Equals(x.UpperName, name, StringComparison.OrdinalIgnoreCase));
Using Any is the better approach as it is one line. It reads easier and takes up less space.
Additionally it is unclear what the Permissions object is but if it's a entity of somekind representing a database table then Any is definitely better as you only return the result of the query where the foreach is going to resolve the entire list of Permissions before the iteration begins.
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.
Given the following:
bool isCorrect = theAnswer == 42;
Which is the preferred way of testing false boolean logic in C# (programming in general)?
if (!isCorrect)
// throw exception
or
if (isCorrect == false)
// throw exception
The reason I ask is because one of our senior developers at work suggests we should always use the latter approach as it enhances readability and ensures other developers can clearly see the false check; an exclamation mark is easy to miss. I much prefer the former as it's more concise and readable enough to me.
I understand that this may be a subjective issue so was wondering if there was a concrete preference mentioned in any coding style.
I have seen production code from senior developers containing such code:
if (isCorrect.ToString().Length == 5)
But I'm still using:
if (!isCorrect)
Use what you think is more readable for you, there is no statistics among all developers))
The preferred way (I'm not sure if it actually is a best practice, but it definitely should be) is to not test false
// First question: "Is the answer correct ?"
bool isCorrect = theAnswer == 42;
// Second question: "What if it is ?"
if (isCorrect)
{
}
else //Third question: "What if it isn't ?"
{
}
It's not only more logical, but saves you from scrolling around to skip error handling if you need to follow the actual flow of your code.
Also, it's worth pointing out for completeness that boolean names should always be positive: think isCorrect VS isNotWrong ... isPositive VS isNotNegative ... much easier not only to read but to understand too.
Given the following:
bool isCorrect = theAnswer == 42;
The clearest way to check the inverse is (IMHO!):
bool isWrong = !isCorrect;
...
if (isWrong)
// throw exception
You are right that (!condition) is more concise.
The senior dev is right that (condition == false) is more 'visible' (or readable if you like).
Since it just boils down to preference, you should just do what the senior dev suggests and keep everything consistent whether you like it or not. When you are the senior dev you can go back and change everything.
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.
Which of these is more optimal? Does it matter which one you use?
If (condition is true)
{
MessageBox.Show("bad data");
return;
}
//mode code here
or
If (condition is true)
{
MessageBox.Show("bad data");
}
else
{
//mode code here
}
The two are functionally the same. Neither is actually superior to the other in terms of behavior or performance. The only real issue here is readability, and that will vary based on the specifics of the example and the programming team involved. So in short, pick whatever you want.
Note that your example should probably be a bit more complete for these assertions to hold true. It should really be comparing;
public static void returnMethod()
{
if (true)
MessageBox.Show("bad data");
//restOfMethod
}
with:
public static void elseMethod()
{
if (true)
MessageBox.Show("bad data");
else
{
//restOfMethod
}
}
I assume what you mean is something more like
If (condition is true)
{
MessageBox.Show("bad data");
return;
}
...more code here...
vs
If (condition is true)
{
MessageBox.Show("bad data");
}
else
{
...more code here...
}
No, there is no performance difference.
This would fall more to design preferences. Some people are die-hard-never-use-returns-to-get-out-of-a-method while others like to keep their code simple and neat, and if using a return helps that, so much the better.
This depends on a few things. Do you have additional code after the conditional which would no longer be applicable? If so, then return would be more optimal as it would prevent the impending statements from running.
The other idea is how this is placed? If this is in a method that has a return, you would use that. Likewise, if it was not applicable to have the surrounding function would accept a return, you wouldnt want to use return.
Does that make some sense?
I'd say never have an empty else {} statement, unless it's just a place holder and in that case do something like
else
{
//Todo: Fill in logic to handle the else case, waiting for business to get back to me
}
Personally I think returning inside an "if" is fine, but if there's nothing below that if, writing "return;" is a waste of a few hundred pixels. If it does exactly the same thing with few pixels and isn't any harder to understand, I'd always go for it.
In the scenario where if-else and return would do the same thing (some examples are provided in other answers), I think readability is what matters.
I think that for one 'if' it doesn't really matter if you write an 'else' or directly 'return'.
It gets worse when some 'if-else' statements are nested. It can be quite unreadable with multiple 'return' inside a method too.
I'm not a fan about nesting if-else's, neither of placing multiple returns inside the same method. But if I have to choose, I prefer to have multiple 'return'.
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.
I hope everyone will enjoy reading this.
I have two IF statements below
public int GetTax(Item item)
{
int tax=0;
if(item.Name.Equals("Book"))
{
tax = 10;
}
if(item.Imported)
{
tax += 5;
}
return tax;
}
I have converted above if condition to this.
public int GetTax(Item item)
{
return 5 * ((int)item.Name.Equals("Book") * 2 + ((int)item.Imported));
}
Which one do you think efficient? and justify why?
If compiled literally the 2nd method is more efficient, because there is no branching.
Whenever there is branching, there is some branch prediction, which could miss, and therefore cause the CPU to re-execute the machine instructions.
Having said that, depending on the compiler, what you have written may be simple enough for it to optimize to equivalent code. This does depend on the return type of what you call. If the return type is boolean, they are equivalent.
However, if for example, item.Imported is actually of integer type, then the two examples you gave are not equivalent, and the compiler may not compile both to the same thing.
Because optimization is very compiler-dependent. If it was important to minimize runtime, you will only know for sure if you benchmark the code.