I have a code with next logic: If some boolean flag is true, one of two code fragments must be executed first and vice versa. But both of them must be executed always. Unfortunately, C# has not semantics instructions for that, like this:
if (condition) first
{
//Some code to execute first if condition is true
}
second
{
//Some code to execute first if condition is false
}
Now, I to do so:
if (condition)
{
//Code 1
//Code 2
}
else
{
//Code 2
//Code 1
}
Such neccesserities are numerous and this creates many code duplication. May be is there a better solution?
Put the code into seperate methods
public void MyMethod1
{
//first code goes here
}
public void MyMethod2
{
//second code goes here
}
if (condition)
{
MyMethod1();
MyMethod2();
}
else
{
MyMethod2();
MyMethod1();
}
This way you do not have to duplicate the code inside the methods.
You may consider writing a method such as:
public static void DoBoth(Action first, Action second, bool keepOrder)
{
if (keepOrder)
{
first();
second();
}
else
{
second();
first();
}
}
I'd create two methods with "Code 1" and "Code 2", then go on like your 2nd option:
if (condition)
{
Code1(); Code2();
}
else
{
Code 2(); Code1();
}
You could also polish this up via Actions or Delegates, depending on what "code 1" and "code 2" are.
I agree with #Steven Jeuris comment about preferring to know the underlying reason as it may point to a design decision requiring improvement. However, if you need to stick with what you have, I would suggest a queue of delegates since you imply that your example is very simple compared to the actual codebase. If not, then one of the other answers would be fine, but the below is possibly more maintainable as complexity grows.
Note: I'm putting this as an example - the parameters for GetQueue, and the logic inside it, could be improved depending on what your conditions actually are.
public Queue<Action> GetQueue(bool condition)
{
var toReturn = new Queue<Action>();
if (condition)
{
toReturn.Enqueue(DoWork1);
toReturn.Enqueue(DoWork2);
}
else
{
toReturn.Enqueue(DoWork2);
toReturn.Enqueue(DoWork1);
}
return toReturn;
}
public void MyExecutingMethod()
{
foreach (var action in GetQueue(true))
{
action();
}
}
public void DoWork1()
{
}
public void DoWork2()
{
}
You should try to avoid code duplication whenever you can. The basic idea in your case would be to try and extract everything that seems to be done more than once and try to "put" it somewhere where you only need to write it once.
In your case, say we have the following:
public void Bar()
{
...
if (condition)
{
//code for action 1
//code for action 2
}
else
{
//code for action 2
//code for action 1
}
...
}
public void Foo()
{
...
if (condition)
{
//code for action 1
//code for action 2
}
else
{
//code for action 2
//code for action 1
}
...
}
Now we obviously can see that you have some code duplication here. We can improve this the following way:
public void Bar()
{
...
if (condition)
{
Action1();
Action2();
}
else
{
Action2();
Action1();
}
...
}
public void Foo()
{
...
if (condition)
{
Action1();
Action2();
}
else
{
Action2();
Action1();
}
...
}
private void Action1()
{
//code for action 1
}
private void Action2()
{
//code for action 1
}
This looks a lot better (specially if Action1 code and Action2 code is lengthy). We have now managed to write the code for Action1 and Action2 only once no matter how many Foo or Bar style methods we have in our code. But we can still do more. You can see that we are still duplicating some obnoxious verbose code. So we can take it a step further and do the following:
public void Bar()
{
...
DoAction(condition);
...
}
public void Foo()
{
...
DoAction(condition);
...
}
private void Action1()
{
//code for action 1
}
private void Action2()
{
//code for action 1
}
private void DoAction(bool condition)
{
if (condition)
{
Action1();
Action2();
}
else
{
Action2();
Action1();
}
}
Now, that IMHO looks a lot better. Not only have we managed to write Action1 and Action2 specific code only once, we have now also managed to write that pesky method ordering logic only once too.
This has huge implications on readability and above all maintainability. For instance, if a bug crops up in Action1 now you only need to change it in one single place. In the original implementation you would have to check all the code and fix the bug everywhere.
Also, imagine the method ordering is business rules dependant, and your client (oh my what a surprise!) decides to change them. With the latest implementation you only need to change your code in one spot.
Rule of the thumb: Avoid code duplication whenever you can, it will drastically reduce the code you type and the headaches you or some poor soul will have in the near future.
I'm going to hazard a guess that code1 either have no side effects or act on the classes member variables, in which case they can be wrapped up in methods that return void. You could then do something along the lines of the following:
...
if (condition)
DoWork(() => Code1(), () => Code2());
else
{
DoWork(() => Code2(), () => Code1());
}
...
private void Code1()
{
// Code 1
}
private void Code2()
{
// code 2
}
private void DoWork(Action action1, Action action2)
{
action1();
action2();
}
I offer another suggestion (in pseudocode).
EDIT: It really depends on your situation which of various approaches you will want to take. Benefits of this approach are simplicity and flexibility. By flexibility, I mean that the decision on ordering is now separated from the code so you can easily do things like add a new ordering, or let the ordering be specified in some other means (e.g. what if you now want to associate different orderings with different users based on a property file)?
if(condition)
runOrder = [ "one", "two" ];
else
runOrder = [ "two", "one" ];
for(x=0; x<runOrder.length; x++)
{
codeToRun = runOrder[x];
switch(codeToRun)
{
Case "one": Code1();
Case "two": Code2();
}
}
Related
I have a problem on having called a generic method, I have searched very much and do not find a solution, this one is my mistake.
And I do not have knowledge of I am doing badly,
The type arguments for method 'FormGasolineUserControl.loadList<T>(list<T>,string)' cannot be inferred from the usage. try specifying the type arguments expliciy.
this is my code:
This chunk of code where I obtain the error
private void loadDataForm()
{
try
{
DateTime dateNow = DateTime.Now;
// Call Services WPF
var QueryBD = services.LoadDataFormGasoline(1, (int)ETax.Gasoline);
if (QueryBD.Company != null)
{
day.Value = dateNow.Day.ToString();
month.Value = dateNow.Month.ToString();
year.Value = dateNow.Year.ToString();
anioGravable.Value = dateNow.Year.ToString();
peridoGravable.Value = PeriodoGravable(dateNow).ToString();
//Error call Method
loadList( QueryBD.QualityDeclarate, QualityDeclarate.Name.ToString());
loadList( QueryBD.TypeDeclarate, TypeDeclarate.Name.ToString());
}
}
catch (Exception)
{
throw;
}
}
And this one is the method:
public void loadlist<T>(List<T> lista,string nameControl)
{
try
{
switch (nameControl)
{
case "TypeDeclarate":
TypeDeclarate.Items.Add(new ListItem("Select..."));
foreach (var name in lista)
{
TypeDeclarate.Items.Add(new ListItem(name.ToString()));
}
break;
case "QualityDeclarate":
QualityDeclarate.Items.Add(new ListItem("Select..."));
foreach (var name in lista)
{
QualityDeclarate.Items.Add(new ListItem(name.ToString()));
}
break;
}
}
catch (Exception)
{
throw;
}
}
My principal aim is to be able to load the usercontrol dynamicamente by means of lists consulted in database.
help me plis...
This code could be improved in a great many ways.
It should not be generic.
It could be refactored into smaller methods that are more clear.
The naming conventions do not follow C# conventions.
It takes a list but only enumerates the elements
It really operates on sequences of strings.
The try-catch is useless.
Let's fix it.
private void AddItemsToCollection(IEnumerable<string> names, IList<ListItem> items)
{
items.Add(new ListItem("Select..."));
foreach (var name in names)
items.Add(new ListItem(name));
}
See how simple that is? Make simple methods that do one thing well. Now we use that helper to make other simple methods:
private void AddItemsToCollection(IEnumerable names, IList<ListItem> items)
{
AddItemsToCollection(names.Cast<object>().Select(n => n.ToString(), items);
}
Again, super simple. One line. Let's make more one-liners:
public void AddTypeDeclarateItems(IEnumerable names)
{
AddItemsToCollection(names, TypeDeclarate.Items);
}
SO EASY. Do it again.
public void AddQualityDeclarateItems(IEnumerable names)
{
AddItemsToCollection(names, QualityDeclarate.Items);
}
And now our method is simple:
public void AddItemsToCollection(IEnumerable names, string control)
{
switch (control)
{
case "TypeDeclarate":
AddTypeDeclarateItems(names);
break;
case "QualityDeclarate":
AddQualityDeclarateItems(names);
break;
}
}
Your code will get easier to understand, easier to make correct, easier to debug, if you simplify it so that every method does one thing.
Alternative solution: move the switch into a helper:
IList<ListItem> GetItems(string control)
{
switch (control)
{
case "TypeDeclarate":
return TypeDeclarate.Items;
case "QualityDeclarate":
return QualityDeclarate.Items;
}
throw new SomeException(...);
}
And now our method is:
public void AddItemsToCollection(IEnumerable names, string control)
{
AddItemsToCollection(names, GetItems(control));
}
Again, see what happens when you make every method do one thing? Every method gets really easy to understand, and highly likely to be correct.
This is the correct way to call this method:
...
loadlist<string>(QueryBD.myListOfStrings, "nameControl");
loadlist<int>(QueryBD.myListOfInts,"nameControl");
...
But, I guess that maybe the problem is inside the class that contains the method
void loadlist<T>(List<T> lista,string nameControl).
Aswer this question: What is T? I mean, in a class declaration we have many possibilities.
We can set T argument like a class: public MyClass<T> where T : class;
A struct: public MyClass<T> where T : struct; A class that has a public constructor public MyClass<T> where T : new(),...
See all possibilities: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters
So, let's imagine that T is a class that must implements an interface and you're passing a class that doesn't implement it, so you'll not have success.
I am writing a C# web-testing project for an application that will read a value from an XML config file and perform automated testing. The code I have right now is working, however, it has to be changed every time the requirements are updated.
private void takeAction(string keyData, string locator, string action)
{
switch (keyData)
{
case "Origin":
if (action == "Input")
{
origin_input(locator, "MEL");
}
break;
case "Destination":
if (action == "Input")
{
destination_input(locator, "Manila");
}
break;
case "DepartDate":
if (action == "Input")
{
textinput(locator, "21/10/2014");
}
break;
case "ReturnDate":
if (action == "Input")
{
textinput(locator, "06/11/2014");
}
break;
case "Adult":
if (action == "Select")
{
objSelect(locator, "3");
}
break;
case "SearchButton":
if (action == "Button")
{
objClick(locator);
}
break;
...
}
}
This code matches the name of the object, checks the required action, and then calls the appropriate function with a few parameters.
I have read some examples of the Open/Closed Principle, however, I could not solve this issue as there are multiple conditions being checked at same time.
As more "keydata" will be added into the code, I believe the switch statement does not seem to be the correct option here. Any advice on improving this code would be appreciated.
IF I were you I'd use some sort of abstraction. For instance all methods you call inside the individual if statements within the switch take string locator and an optional other string parameter (or none in the last case). Furthermore I think you can simplify the logic by combining the value of the keyData and the acton parameters since when combined they produce unique key.
What you can do with this is the following:
public interface ITestableAction{
void Execute(string locator);
}
public class OriginInputAction : ITestableAction{
public void Execute(string locator){
origin_input(locator, "MEL"); //I'd make the origin_input method static...
}
}
public class DestinationInputAction : ITestableAction{
public void Execute(string locator){
destination_input(locator, "Manila");
}
}
finally your class needs to have a dictionary where the keyData and the acton will represent the keys.
private Dictionary<string, ITestableAction> actions =
new Dictionary<string, ITestableAction>();
actions.Add("OriginInput", new OriginInputAction());
actions.Add("DestinationInput", new DestinationInputAction());
etc...
so in your method instead of constantly having to check the different ways you can pair all keyData and action values you simply look up the corresponding ITestableAction for their sum:
private void takeAction(string keyData, string locator, string action)
{
string key = string.Format("{0}{1}", keyData, action);
if(actions.ContainsKey(key))
{
ITestableAction action = actions[key]
action.Execute(locator);
}
}
This is one of the "I am supposed to know it" design patterns. Can't really put my finger on what exactly it is, but it's useful. It's supposed to help you because you don't have change the logic so much every time. Just create a new class that inherits from ITestableAction and add it to the dictionary. At the end of the day the logic tree becomes shorter. But then again, please don't take this at face value... there are hundreds of ways to code something, and only you know your requirements and stakes. This is just a suggestion to hopefully point you in the right direction.
Thanks,
Martin.
You could declaratively define your cases as shown below. You could also use classes, but that gets more complicated because the classes need access to the methods that you're passing locator into. If this approach still calls for more separation, then it might be worth making each case into a class.
Interface
public delegate void TestAction(string locator);
public class ActionCase
{
public string ExpectedAction { get; set; }
public TestAction Test { get; set; }
}
Definitions
private Dictionary<string, ActionCase> cases = new Dictionary<string, ActionCase>
{
{
"Origin",
new ActionCase
{
ExpectedAction = "Input",
Test = locator => origin_input(locator, "MEL")
}
},
//Define the rest here
};
Usage
private void takeAction(string keyData, string locator, string action)
{
var case = cases[keyData];
if (action == case.ExpectedAction)
case.Test(locator);
}
Well, you could simply do something like:
switch (keyData + action)
{
case "OriginInput":
origin_input(locator, "MEL");
break;
}
I think you just need an extra variable
private void takeAction(string keyData, string locator, string action, string searchfor)
{
switch (keyData)
{
case "Origin":
if (action == "Input")
{
origin_input(locator, searchfor);
}
break;
First off, I totally apologize for the title, I don't know what the heck to put, it's such a confusing concept to really explain in a title, so bear with me.
public class fido
{
public void foo(process proc)
{
if (/* comparing by time */)
{
if (proc[parent].time < proc[child].time)
{
//do something
}
}
else if (/* comparing by priority */)
{
if (proc[parent].priority < proc[child].priority)
{
//do something
}
}
}
}
How do I go about shortening this? I was hoping it could be as simple as using a "defined" member through the parameter of foo().
For example
public class fido
{
public void foo(process proc, something mem)
{
if (/* comparing by time */)
{
if (proc[parent].mem < proc[child].mem)
{
//do something
}
}
}
}
Then I would use something like
foo(processA, time); // If I want to use time member
foo(processB, priority); // Or if I want to use priority member
I know the previous codes are 100% incorrect, but I hope you understand what I'm getting at.
I'm just trying to shorten the code because what I have is a priority queue class that uses heap and everything to prioritize values, however I need to use the class for multiple types of values, such as time and priority. I definitely do not want to create a duplicate class (totally not beneficial), I'm looking for a way I can shorten it. Does anybody know the best way?
You could pass an enum as a parameter in your method.
public class Fido
{
public void foo(Process proc, Options options)
{
if (options == Options.Time)
{
//Do time work
}
else if (options == Options.Priority)
{
//Do priority work
}
}
}
public enum Options
{
Time,
Priority
}
Note that a passing a bool instead of an enum would work here as well. It just makes things a bit less readable.
In my program I have a listbox that when the user double clicks an object it looks to a switch statement to see what event should occur. As the list begins getting larger I'm curious if there is a way to avoid having to maintain the list of objects in 2 places (once in a list to Add to the listbox, and once in the switch statement.
Is there a way to index/read/store the various Cases of my switch statement, then add them as objects to my listbox?
Example: (doesn't work, just a theory)
Switch (n)
ForEach (Case c in Cases)
{
arrayCases.Add(c);
}
listbox.Items.AddRange(arrayCases);
EDIT:
Going on the Dictionary recommendations I now have:
public void SetDictionary()
{
//add entries to the dictionary
dict["cat"] = new Action(Cat);
dict["dog"] = new Action(Dog);
//add each dictionary entry to the listbox.
foreach (string key in dict.Keys)
{
listboxTest.Items.Add(key);
}
}
//when an item in the listbox is double clicked
private void listboxTest_DoubleClick(object sender, EventArgs e)
{
testrun(listboxCases.SelectedItem.ToString());
}
public void testrun(string n)
{
//this is supposed to receive the item that was double clicked in the listbox, and run it's corresponding action as defined in the dictionary.
var action = dict[n] as Action action();
}
I believe that my code above is mostly correct and that I'm understanding it, however the action line:
var action = dict[n] as Action action();
Shows an error stating 'action' is expecting a ';'. Is my logic here accurate? If so, why is the action call incorrect?
Dictionary<string, Action> is the way to avoid. Dictionary.Keys becomes ListBox.Items.
switch(n) becomes
var action = dict[n] as Action
action();
I suggest to move your operations into separate classes. Create a base class for your operations like the following one. I added a field for the form because you probably have to interact with your form. You can also pass in other objects if required.
internal abstract class Operation
{
protected readonly MyForm form = null;
protected Operation(MyForm form)
{
this.form = form;
}
public abstract String DisplayName { get; }
internal abstract void Execute();
}
Then derive one class for each operation.
internal sealed class DoThis : Operation
{
internal DoThis(MyForm form) : base(form) { }
public override String DisplayName
{
get { return "Do this!"; }
}
internal override void Execute()
{
// Code to do this. You can use this.form to interact with
// your form from this operation.
}
}
internal sealed class DoSomethingElse : Operation
{
internal DoSomethingElse(MyForm form) : base(form) { }
public override String DisplayName
{
get { return "Do something else!"; }
}
internal override void Execute()
{
// Code to do something else.
}
}
Now you can add all your operations to the list box
this.lsitBox.Items.Add(new DoThis(this));
this.lsitBox.Items.Add(new DoSomethingElse(this));
and set the display member property.
this.listBox.DisplayMember = "DisplayName";
Finally execute the selected operation in the event handler.
((Operation)this.listBox.SelectedItem).Execute();
This pattern gives clean separation between all your operations and makes future extensions easy and clean. For example you could add a property CanExecute to all operations if you have to check if a operation is currently available. Or if you have to support localization it is easy to add logic for presenting the name of the operation in the current UI language.
Another scenario that is easily supported is if you have some code common to all operations for example logging, security checks, performance measuring and things like that.
internal abstract class Operation
{
protected readonly MyForm form = null;
protected Operation(MyForm form)
{
this.form = form;
}
public abstract String DisplayName { get; }
protected abstract void ExecuteCore();
internal void Execute()
{
Logger.Log("Executing operation " + this.DisplayName);
try
{
this.ExecuteCore();
Logger.Log("Executing operation " + this.DisplayName + " succeeded.");
}
catch (Exception exception)
{
Logger.Log("Executing operation " + this.DisplayName + " failed.", exception);
throw;
}
}
}
Note that you now have to override ExecuteCore() instead of Execute().
One final thought - using an interface IOperation instead or in combination with the abstract base class may be helpful, too. This removes the need that all operation inherit from the same base class because this might sometimes be inconvenient. But I omitted this to not overengineere this even more.
You can't* enumerate case of switch with normal code.
What you can do instead is to replace switch with map of "action name" to "action handler" and than you'll be able to reuse this map for list of action names listbox. See Tilak's answer for sample.
*) If you are really inquisitive you can enumerate choices of switch. C# code is transformed to IL and IL can be read with code. So you can get IL for a method, write (or get existing - Parser for C#) parser for IL and find implementation of switch inside the method, pick all cases. You can even go straight to C# source at build time - but it is even more involved than IL parsing.
Yes there is a way to do this by making a dictionary of lambdas.
void Main()
{
// set up your dictionary
Dictionary<string,Action> myList = new Dictionary<string,Action> {
{ "one", () => { Console.WriteLine("One function"); } },
{ "two", () => { Console.WriteLine("Two function"); }},
{ "three", () => { Console.WriteLine("Three function"); }}
};
// do a "switch" (that is invoke a function that corresponds to a name)
myList["one"]();
// loop the list of keys (that is get a list of all the names)
foreach (string key in myList.Keys)
Console.WriteLine(key);
}
the output of this program:
One function
one
two
three
Also note -- you can add to this "switch" dynamically like this (which is cool and something you can't do with a classical switch statement.)
myList.Add("four",() => { Console.WriteLine("Four function is dynamic"); });
It sounds to me like the number of cases in your switch are going to change a lot. If this is true, then you might want to consider using a mechanism other than a switch statement. Perhaps you want to do something like Alexi Levenkov suggests, and then iterate a list of the stored Action Names and execute the associated handler. This way you will avoid having to add the action name to the action map and then add it to the switch.
I was tinkering with doing the setups with our unit test specifciations which go like
Specification for SUT when behaviour X happens in scenario Y
Given that this thing
And also this other thing
When I do X...
Then It should do ...
And It should also do ...
I wrapped each of the steps of the GivenThat in Actions... any feed back whether separating with Actions is good / bad / or better way to make the GivenThat clear?
/// <summary>
/// Given a product is setup for injection
/// And Product Image Factory Is Stubbed();
/// And Product Size Is Stubbed();
/// And Drawing Scale Is Stubbed();
/// And Product Type Is Stubbed();
/// </summary>
protected override void GivenThat()
{
base.GivenThat();
Action givenThatAProductIsSetupforInjection = () =>
{
var randomGenerator = new RandomGenerator();
this.Position = randomGenerator.Generate<Point>();
this.Product = new Diffuser
{
Size =
new RectangularProductSize(
2.Inches()),
Position = this.Position,
ProductType =
Dep<IProductType>()
};
};
Action andProductImageFactoryIsStubbed = () => Dep<IProductBitmapImageFactory>().Stub(f => f.GetInstance(Dep<IProductType>())).Return(ExpectedBitmapImage);
Action andProductSizeIsStubbed = () =>
{
Stub<IDisplacementProduct, IProductSize>(p => p.Size);
var productBounds = new ProductBounds(Width.Feet(), Height.Feet());
Dep<IProductSize>().Stub(s => s.Bounds).Return(productBounds);
};
Action andDrawingScaleIsStubbed = () => Dep<IDrawingScale>().Stub(s => s.PixelsPerFoot).Return(PixelsPerFoot);
Action andProductTypeIsStubbed = () => Stub<IDisplacementProduct, IProductType>(p => p.ProductType);
givenThatAProductIsSetupforInjection();
andProductImageFactoryIsStubbed();
andProductSizeIsStubbed();
andDrawingScaleIsStubbed();
andProductTypeIsStubbed();
}
Put them in separate methods so that you can compose them in other givens. Also, use underscores to replace spaces (instead of camel case). Also, create a method Given_that that takes params of Action delegates.
protected void Given_that(params Action[] preconditions)
{
foreach (var action in preconditions)
{
action();
}
}
...
protected void a_product_is_set_up_for_injection()
{
...
}
protected void product_image_factory_is_stubbed()
{
...
}
etc...
...
Given_that(a_product_is_set_up_for_injection,
product_image_factory_is_stubbed,
product_size_is_stubbed,
drawing_scale_is_stubbed,
product_type_is_stubbed);
That being said, I think the naming of your preconditions are not BDD. They are very technical in nature and do not denote the business need. If you were to tell a non-programmer what you were testing, you would probably not say "the product is stubbed for injection." You would more likely say
Given a displacement product
that is a two inch rectangular diffuser
that has a random position
that has a bitmap
that has a size bounded by feet
that has the expected pixels per foot
Now you can compose your "given" methods with little duplication:
protected [the type of your test class] Given(params Action given)
{
given();
return this;
}
protected void That(params Action[] preconditions)
{
foreach (var precondition in preconditions)
{
precondition();
}
}
Given(a_displacement_product)
.That(is_a_two_inch_rectangular_diffuser,
has_a_random_position,
has_a_bitmap,
has_a_size_bounded_by_feet,
has_the_expected_pixels_per_foot);
Composing your Givens, Whens and Thens in separate methods is a good idea and it's the way for instance SpecFlow (http://www.specflow.org) does it. So if rather want some automation for creating that boring piece of repetetive plumbing, I would really recomend using a tool like SpecFlow. And as a bonus you get a nice reporting tool :)
An other option to make your code a bit more fluent, is to make a little BDD base class. Take a look at Jonas Follesoe's brilliant little BDD DSL up at GitHub: http://gist.github.com/406014;
public abstract class BDD<T> where T : BDD<T>
{
protected T Given { get { return (T)this; } }
protected T And { get { return (T)this; } }
protected T When { get { return (T)this; } }
protected T Then { get { return (T)this; } }
}
And as Michael Meadows point out in his great answer; If you're going the BDD way of doing TDD (which you really should), keep focus on making your spesifications readable to business people. That means; stay away from technical wordings mock, inject, factory, exception, etc.