Which of the following code blocks are more logical? - c#

Imagine a condintion should be true for a method to do its stuff. Which block represents the best approach (performance related and readability), or if not what is your suggestion?!
private void method()
{
if(!condition)
{
MessageBox.Show("ERROR!");
return;
}
else
{
//DO STUFF
}
}
OR
private void method()
{
if(condition)
{
//DO STUFF
}
else
{
MessageBox.Show("ERROR!");
return;
}
}

Neither. Use a guard clause instead:
private void method()
{
if(!condition)
{
MessageBox.Show("ERROR!");
return;
}
//inputs have been checked, proceed with normal execution
}
Done this way you can deal with all the exceptional behaviour up-front and avoiding excessive levels of indentation for the normal execution path.

Well, neither, as you wouldn't use both else and return.
So, you would either do:
private void method() {
if (!condition) {
MessageBox.Show("ERROR!");
} else {
//DO STUFF
}
}
or:
private void method() {
if (condition) {
//DO STUFF
} else {
MessageBox.Show("ERROR!");
}
}
or:
private void method() {
if (!condition) {
MessageBox.Show("ERROR!");
return
}
//DO STUFF
}
or:
private void method() {
if (condition) {
//DO STUFF
return;
}
MessageBox.Show("ERROR!");
}
Which you use depends mostly on what the code actually does. The code is seldom as simple as in the examples, so it matters what more the code will do.
The first two have the advantage of having a single exit point, which often makes it easier to follow the code. You would usually put the shorter code first, as it's easier to spot there than in an else after a larger code block.
The third is often used to validate input before continuing with the main code, and you can easily have more than one validation:
private void method() {
if (!condition) {
MessageBox.Show("ERROR!");
return
}
if (!anotherCondition) {
MessageBox.Show("ANOTHER ERROR!");
return
}
//DO STUFF
}
The fourth is useful if you have several conditions that you don't want to put in the same if statement:
private void method() {
if (condition) {
var data = GetSomeData();
if (data.IsValid) {
var moreData = GetSomeMoreData();
if (moreData.IsValid) {
//DO STUFF
return;
}
}
}
MessageBox.Show("ERROR!");
}

Second! Second!
But I do admit to doing the first sometimes if the "//DO STUFF" is really long and nested.

I prefer an "If condition" approach as opposed to the negation of a condition, but that's just personal preference.

It depends.
In most cases, the second version.
if the amount of code in the (!condition) block is only a few lines of code, and the code in the (condition) block is a LOT of code, then I'd reverse the answer. it's easier to read through the if statement if you can see the "else" without having to scroll.

I prefer a guard clause as David mentions, but in the general case you should put the most common case first. It makes it easier to follow the flow of a method.

Readability/standards wise. I would accept number 2. I don't think there is a difference performance wise, but I'm not a low-level guy.

As usually this is a question which asks for the following answer: "it depends" and I'll show by two examples.
IF NOT CONDITION
For the ASP .Net Web Forms validation I'm seeing very often this code
protected void btSubmit_OnClick(object sender, EventArgs e)
{
Page.Valide();
if (!Page.IsValid)
return;
var customer = new Customer();
// init 20 properties of customer
....
var bo = new CustomerBO();
bo.Save(customer);
}
There is another one much more popular:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
IF CONDITION
public void UpdateCustomer(int customerId, string ...../*it might be a customer type also*/)
{
using (var ctx= CreateContext())
{
var customer = ctx.Customers.FirstOrDefault(c=>c.CustomerId = customerId);
if ( customer != null)
{
/*code update 20 properties */
}
}
}
I hope the code is clear :P

This is more of a style question than a "logical" question. Both of these approaches work, and which one you will use generally depends on your style as a thinker/developer.
That said, once you start using either one of these styles, it generally pays to be consistent. Having large classes where some functions do it the first way and others the second way can lead to maintainability concerns later.
Robert Martin's Clean Code presents an interesting chapter on functions that suggests, whichever way you choose, the //DO STUFF part should be another function call
Functions Should Only Do One Thing

Related

Can I reduce these lines of code make double key press to switch between two of if/else if options

I would like to reduce this to the fewest possible lines of code.
This using C# code in Unity, but the question is more about basic refactoring. There is no timer yet, I'm simply trying to write code print timer started/timer stopped to the Unity console.
void Update()
{
pressSpacebar();
}
void pressSpacebar()
{
if (Input.GetKeyDown("space"))
{
if(!timerIsRunning)
{
StartTimer();
}
else if (timerIsRunning)
{
StopTimer();
}
}
}
bool timerIsRunning;
void StartTimer()
{
timerIsRunning = true;
print("Timer Running");
//to check if bool changed (and not just the text)
print(timerIsRunning);
}
void StopTimer()
{
timerIsRunning = false;
print("Timer Stopped");
print(timerIsRunning);
}
Ok, so for starters, I'd remove the Update() method because it merely calls pressSpacebar() which is pointless. Just call it directly wherever Update() is needed.
Also, I removed the else if because it's not needed. Either it returns true in the if statement then break or it doesn't. Removes lines of code, not sure if it's technically worth it. Finally, because your other methods don't do much in the way of making significant changes, I moved them inside of your pressSpaceBar() method, assuming that you don't need those other StartTimer() and EndTimer() elsewhere in code. In my example, I swapped out two methods for one that swaps and effectively does the same thing.
Option 1: Methods StartTimer() and EndTimer() Not used elsewhere.
void pressSpacebar()
{
if (Input.GetKeyDown("space"))
{
//Source: #Enigmativity
//Sets by using the not operator. Acts as a switch.
timerIsRunning = !timerIsRunning;
print(timerIsRunning);
}
}
Option 2: Methods StartTimer() and EndTimer Are used elsewhere.
void pressSpacebar()
{
if (Input.GetKeyDown("space"))
{
TimerManager();
}
}
//INFO: Replaced startTimer() & stopTimer() with this to switch.
void TimerManager()
{
//Source: #Enigmativity
//Sets by using the not operator. Acts as a switch.
timerIsRunning = !timerIsRunning;
print(timerIsRunning);
}
As thought experiment, I guess if you don't mind a bit string interpolation, and bitwise XOR, you can further reduce the amount of code to run your sample.
bool timerIsRunning;
void Update() // I'm leaving this unchanged as you might need to add more context here, otherwise, feel free to unline `pressSpacebar()` here and remove more lines
{
pressSpacebar();
}
void pressSpacebar() {
if (Input.GetKeyDown("space"))
print($"Timer {((timerIsRunning ^= true) ? "Running" : "Stopped")}, {timerIsRunning}");
}
Upd oh, you also can drop squiggly brackets here too
Timerless solution
A use case like this one does not require an actual timer. You can just keep track of the start time and measure the difference, which results in pretty simple code.
DateTime? _startTime;
void pressSpacebar()
{
if (!Input.GetKeyDown("space")) return;
if (_startTime.HasValue)
{
var duration = DateTime.Now - _startTime.Value;
print("Timer ran for {0} seconds", duration.Seconds);
_startTime = null;
}
else
{
_startTime = DateTime.Now;
print("Timer started.");
}
}
While this is not much shorter than your original code, it eliminates the need to add the timer code (that you hadn't added yet) which will hopefully make your overall solution both shorter and easier to understand.

Class Variable UnChanged by Asyncronous Method

EDIT: I know this is bad code, that's why I tagged it with anti-pattern.
OK, so this is some actual real code I found today:
public class ServiceWrapper
{
bool thingIsDone = false; //class variable.
//a bunch of other state variables
public string InvokeSoap(methodArgs args)
{
//blah blah blah
soapClient client = new Client();
client.doThingCompleted += new doThingEventHandler(MycompletionMethod);
client.doThingAsync(args);
do
{
string busyWork = "";
}
while (thingIsDone == false)
//do some more stuff
}
private void MyCompletionMethod(object sender, completedEventArgs e)
{
//do some other stuff
thingIsDone = true;
}
}
OK, so I'm aware of why this is bad, obviously. But what's actually making me ask this question is, thingIsDone never seems to be true in the InvokeSoap method, even if set true in MyCompletionMethod, but only if complied in Release. It behaves as one would "expect" in Debug mode.
Adding Thread.Sleep(100) inside the while loop also fixes it. What's up with this?
The CPU may cache the value of thingIsDone, since that thread cannot change it between reads.
You need volatile to force the writes to be published so the other thread can read it.
You can use Thread.Yield() in the loop.
do
{
string busyWork = "";
Thread.Yield();
}
while (thingIsDone == false)

Cleaner code: Re-factor multiple nested if statements

I have code that looks something like this:
if(condition1)
{
//do some stuff
if(condition2)
{
//do some other stuff
if(condition3)
{
//do some more stuff
if(condition4)
{
//you probably got the point by now...
}
}
}
And I would like to re-factor it to code that looks better and is easier to follow.
So far the best I got Is:
do{
if(!condition1){break;}
//do some stuff
if(!condition2){break;}
//do some other stuff
if(!condition3){break;}
//do some more stuff
if(!condition4){break;}
//you probably got the point by now...
}while(false);
My question is:
Is there another better way I am missing?
I don't think it is relevant, but I am using C#...
Possibly encapsulate the functionality you need for each boolean condition into a method and use the method instead of specifying condition1, condition2, condition3 etc.
private boolean isRed() {
//do some stuff
}
private boolean isBlue() {
//do some other stuff
}
private boolean isGreen() {
//do some more stuff
}
...
if(isRed() && isBlue() && isGreen()) {
//do some more stuff
}
Since you are using C#, the idea of #dseibert could be extended a little bit more and made flexible using delegates, in this case Func.
You could create a List that holds Func's and add as many functions with the signature bool function(void) as you want and then evaluate the result of all of them using LINQ.
Three example functions to play with:
private bool isRed()
{
System.Console.WriteLine("red");
return true;
}
private bool isBlue()
{
System.Console.WriteLine("blue");
return false;
}
private bool isGreen()
{
System.Console.WriteLine("green");
return true;
}
List holding Funcs, that is filled with the test functions and initialized result:
var actions = new List<Func<bool>>();
actions.Add(() => isRed());
actions.Add(() => isGreen());
actions.Add(() => isBlue());
var result = true; // initial value
Evaluate all functions at once:
actions.ForEach(a => result &= a());
System.Console.WriteLine(result);
Now the only thing that you need to do is create a new method and add it to the list.
The downside of this solutions is that every method is always called even if the result is already false, but the code within the ForEach extension method could be optimized.

Code improvement: Better alternatives to this pattern?

In a similar question:
What is this pattern called? Soft Lock?
I was asking about the name of the pattern for the code listing below.
public class MyClass
{
public event EventHandler MyEvent;
private bool IsHandlingEvent = false;
public MyClass()
{
MyEvent += new EventHandler(MyClass_MyEvent);
}
void MyClass_MyEvent(object sender, EventArgs e)
{
if (IsHandlingEvent) { return; }
IsHandlingEvent = true;
{
// Code goes here that handles the event, possibly invoking 'MyEvent' again.
// IsHandlingEvent flag is used to avoid redundant processing. What is this
// technique, or pattern called.
// ...
}
IsHandlingEvent = false;
}
}
It seems that most of the conversation was centered around why we should an should not do this, so I think that this question provides a better forum to tackle the problem and address all of the issues. What is the better / proper way to handle this?
There are series of problems with that pattern. If you want to invoke the handler only once, you would do something like this:
protected static object _lockObj = new object();
protected static bool _isHandled = false;
void MyClass_MyEvent(object sender, EventArgs e)
{
if(_isHandled)
return;
lock(_lockObj)
{
if(_isHandled)
return;
_isHandled = true;
MyOtherPossiblyRecursiveMethod(); // Actually does all your work
_isHandled = false;
}
}
void MyOtherPossiblyRecursiveMethod()
{
}
This way, only one thread should be able to access the actual work method.
I will use something like:
using( var sl = new SoftLock() )
{
sl.Execute(()=>{....});
}
the execute will raise the internal boolean to prevent re-entering. In the dispose that flag would be resetted. Execute will call the lambda just if the flag is false. This is to ensure flag go to false even if exception happens ( causing handler never executed ) and maybe is a little better to see. Of course this is not thread safe, as the original code, but this because we are talking about preventing double execution from the same thread.
The original code is a sufficient (and very lightweight) way to prevent recursion in a single-threaded app. So if during your event handling function you could get into code that might be firing the event again you will not enter infinite recursion.
But the code is not sufficient to prevent access from multiple threads, due to the potential for race conditions. If you need to ensure only one thread gets to run this event, then you should use a stronger locking mechanism, like a Mutex or Semaphore.
The following works in single- and multi-threaded scenarios and is exception-safe... also if need be it can be modified to allow for a certain level of reentrancy (for example 3 levels)...
public class MyClass
{
public event EventHandler MyEvent;
private int IsHandlingEvent = 0;
public MyClass()
{
MyEvent += new EventHandler(MyClass_MyEvent);
}
void MyClass_MyEvent(object sender, EventArgs e)
{
// this allows for nesting if needed by comparing for example < 3 or similar
if (Interlocked.Increment (ref IsHandlingEvent) == 1 )
{
try {
}
finally {};
}
Interlocked.Decrement (ref IsHandlingEvent);
}
}

How to prevent duplicates, macro or something?

Well, the problem is that I've got a lot of code like this for each event passed to the GUI, how can I shortify this? Macros wont do the work I guess. Is there a more generic way to do something like a 'template' ?
private delegate void DownloadProgressDelegate(object sender, DownloaderProgressArgs e);
void DownloadProgress(object sender, DownloaderProgressArgs e) {
if (this.InvokeRequired) {
this.BeginInvoke(new DownloadProgressDelegate(DownloadProgress), new object[] { sender, e });
return;
}
label2.Text = d.speedOutput.ToString();
}
EDIT:
OK, how can I make this using anonymous delegate in BeginInvoke:
this.BeginInvoke(new DownloadProgressDelegate(DownloadProgress), new object[] { sender, e });
I personally prefer to put the actual action in an Action, then check if this requires an invoke -- this also has the benefit of not needing to declare so many delegates for use with your BeginInvokes. In other words,
void DownloadProgress(object sender, DownloaderProgressArgs e)
{
Action updateLabel = () => label2.Text = d.speedOutput.ToString();
if (this.InvokeRequired)
{
this.BeginInvoke(updateLabel);
}
else
{
updateLabel();
}
}
void DownloadSpeed(object sender, DownloaderProgressArgs e) {
Action updateSpeed = () =>
{
string speed = "";
speed = (e.DownloadSpeed / 1024).ToString() + "kb/s";
label3.Text = speed;
};
if (this.InvokeRequired)
{
this.BeginInvoke(updateSpeed);
}
else
{
updateSpeed();
}
}
This approach lends itself well to use an extension method on Controls that takes an Action and runs it through the check for InvokeRequired.
At a minimum, the extension method should look something like:
public static void MaybeInvoke(this Control c, Action action)
{
if (c.InvokeRequired)
{
this.BeginInvoke(action);
}
else
{
action();
}
}
Annoyingly, the non-generic Action wasn't introduced until .NET 3.5, so you would need to modify things a bit in the examples I gave -- probably using MethodInvoker -- if you're using an earlier version.
You could try T4... but I don't know if it will fit your case well.
One humble thought is to create one routine that handles all your BeginInvoke cases based on a request-type enumerate and using a switch statement. Then at least you only have to check InvokeRequired once. Note that you should probably use if/else rather than return to control the flow.
Well, one way could be to put the generic codes in static class, and access it like, for instance:
Utility.DownloadSpeedUpdate(frm, sender, e);
.net has (in one sense) a rather poor UI framework that actively encourages the problem you have, and the mixing of business logic and UI.
You may be able to make some headway with generics, delegates, and base class/static helper methods.
However, ideally, you need to layer a UI manager on top of .net that helps you out with this properly. This would allow you to separate the UI from the commands that it executes (i.e. you would dynamically bind UI events like keypresses, menu choices, button clicks etc to underlying command objects rather than handling the UI events directly). The UI event handlers would simply look up the command that is bound to the event, then call a centralised "execute Command X" method, and this would handle all the marshalling to the UI thread, etc.
As well as cleaning up this whole mess, this allows you to easily add things like key bindings and scripting/automation to your app, and makes the UI infinitely more scalable and maintainable.
It's no coincidence that this is the core command dispatch approach used in WCF - If you're not using WCF then it's unfortunately up to you to implement an equivalent. It takes a little bit of work to implement a basic command dispatch system, but unless your application is trivial, you'll be glad you did it.
Here's a sample that will save you a bunch of coding if you have many functions requiring InvokeRequired checks. You should notice a few important things:
I use EventHandler<DownloaderProgressArgs> instead of creating new delegates for each function.
The GetInvokeRequiredDelegate function wraps the code that is the same for all of these functions.
This code could be moved into a static class to let you share this among several forms, but that would require more work and a different structure. As it is here, the function just knows which form you're dealing with because the function exists inside that form.
This is all the code that I set up to test GetInvokeRequiredDelegate<T>():
public partial class Form1 : Form
{
public event EventHandler<DownloaderProgressArgs> OnDownloadProgress;
public event EventHandler<DownloaderProgressArgs> OnDownloadSpeed;
public Form1()
{
InitializeComponent();
OnDownloadProgress += GetInvokeRequiredDelegate<DownloaderProgressArgs>(DownloadProgress);
OnDownloadSpeed += GetInvokeRequiredDelegate<DownloaderProgressArgs>(DownloadSpeed);
new System.Threading.Thread(Test).Start();
}
public void Test()
{
OnDownloadProgress(this, new DownloaderProgressArgs() { DownloadSpeed = 1000, speedOutput = 5 });
OnDownloadSpeed(this, new DownloaderProgressArgs() { DownloadSpeed = 2000, speedOutput = 10 });
}
EventHandler<T> GetInvokeRequiredDelegate<T>(Action<object, T> action) where T : EventArgs
{
return ((o, e) =>
{
if (this.InvokeRequired)
{
this.BeginInvoke(action, new object[] { o, e});
} else
{
action(o, e);
}
});
}
void DownloadProgress(object sender, DownloaderProgressArgs d)
{
label2.Text = d.speedOutput.ToString();
}
void DownloadSpeed(object sender, DownloaderProgressArgs e)
{
string speed = "";
speed = (e.DownloadSpeed / 1024).ToString() + "kb/s";
label3.Text = speed;
}
}
public class DownloaderProgressArgs : EventArgs {
public int DownloadSpeed;
public int speedOutput;
}

Categories