How to safely and cleanly rewrite critical/production code? [closed] - c#

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.

Related

How to define a method with custom invocation syntax "using" or "try" or "catch" or "set"? [closed]

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.
What do you think?
I'm trying to create a log method. I'm wondering how to define it, with following invocation syntax:
logging(var loggerContext = new LogManager(input)){ // create a new logger context and store input
//var results = Method();
} // store results in logger context
How to implement logging??
An alternative pattern I frequently use is something like this:
void WithLogging(Action action)
{
// set up logging here
action();
// save results here
}
Then you can use it like so:
WithLogging(() =>
{
//do some things here
});
As other posters have noted, defining new keywords is not something you can do in C#. You may find Boo interesting, particularly macros.
Sometimes it makes sense to implement IDisposable for such cases with custom logic in constructor and Dispose method:
class Logmanager : IDisposable
{
public Logmanager()
{
this.Log("Start");
}
private void Log(string message)
{
// some logging implementation
}
public void Dispose()
{
this.Log("Finish");
}
}
Then you can put it in using statement:
using (var logger = new Logmanager())
{
// you can add something to logger here, e.g. store results
}

Linq Any() vs foreach [closed]

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.

Should you use return or else? Which of these is optimal? [closed]

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'.

Converting IF statements to simple statement - Which one is efficient? [closed]

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.

C# : Proper "if - elseif" formatting [closed]

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

Categories

Resources