Dynamic method dispatch based on value of variable - c#

Long switch statments are often frowned upon. The solution is to use polymorphism. However what if the thing I'm switching on is not a type code? What I would like to do is replace the switch statement with something like this...
public void HandleString(string s = "Hello")
{
...
}
public void HandleString(string s = "Goodbye")
{
...
}
...
HandleString("Hello"); // results in the first method being called.
This would replace the following...
string s = "Hello";
switch(s)
{
case "Hello":
...
break;
case "Goodbye":
...
break;
default;
break;
}
Any ideas? In theory I think you could do away with 'if/switch' statements altogether and just call methods that are automatically bound based on the value of an expression.

If you have a large number of options, and high possibility that there will be more in the future - or you just need to system to be easily extensible - then you can always use an explicit dispatch table:
Dictionary<string, Action<string>> actions =
new Dictionary<string, Action<string>>()
{
{ "Hello", HandleHello },
{ "Goodbye", HandleGoodbye }
};
private static void HandleHello(string s) { ... }
private static void HandleGoodbye(string s) { ... }
...
actions[s](s);
You can also provide a way to extend the table by allowing external clients of your API to register their own handler for a given string.

There are languages that implement that sort of semantics. One that I'm familiar with is the compiler generator tool called Elegant from Phillips.
In a language like this, a simple factorial algorithm might look like:
fact (value : Int) : Int
conditions value < 0
{
{ "Illegal input value\n" } astype Message
return 0
}
fact (value = 0) : Int
{
return 0
}
fact (value = 1) : Int
{
return 1
}
fact (value : Int) : Int
{
return value * fact(value - 1);
}

Related

Switch on one true expression c#

I would have liked to do something like
switch(true) {
case box1.Checked:
do_something(); break;
case box2.Checked:
do_something_else();
and_some_more(); break;
default:
complain_loudly();
}
But that is not allowed in c#; it is in php.
Is there a neater way, besides a
if (box1.Checked) {
do_something();
} else if (box2.checked)
...
?
With C# 7 using case with when. See also The case statement and the when clause
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Box box1 = new Box();
Box box2 = new Box();
box2.Checked = true;
switch (true)
{
case true when box1.Checked:
Console.WriteLine("box1 is checked");
break;
case true when box2.Checked:
Console.WriteLine("box2 is checked");
break;
default:
Console.WriteLine("neither box checked");
break;
}
return;
}
}
class Box
{
public bool Checked = false;
}
}
Output:
box2 is checked
I would try something like this - find fist checked checkbox from collection and then switch-case by name of checked control...
Something like this:
var checkedCb = this.Controls.OfType<CheckBox>().Where(c => c.Checked).First();
switch (checkedCb.Name)
{
case "cbOne":
break;
case "cbTwo":
break;
default:
break;
}
PHP seems to resolve a switch differently than C#.
In C# you switch over an expression and use the cases to define possible constant results of the expression you switched over. The neat thing about the C# switch is that it might be optimized which requires the cases to be constant expressions.
Your first Problem is that your cases are not constant.
As a result of point 1: If both of your checkboxes are checked which one should be executed? This is a problem that would cause a runtime issue and cannot be evaluated at compile time. C# will not allow multiple cases of the same value.
I don't want to provide any examples of optimization here, simply because I would tell a lot of lies. If you want to know more about these optimizations you may read up to Eric Lipper's blog post about it:
https://blogs.msdn.microsoft.com/ericlippert/2009/06/11/what-does-the-optimize-switch-do/
As a solution: KISS
Keep it simple stupid - meaning - use an if else.
EDIT:
I don't think it adds to readability nor simplicity of your code. This is basically just me trying to do something weird like the switch statement you know from PHP. Please don't use it. I wouldn't recommend using it.
(It takes more space and time, initially and during each call, than a simple if else)
public partial class MainWindow : Window
{
private CheckBox[] _checkboxes;
private Dictionary<int, Action> _checkboxActions = new Dictionary<int, Action>();
public MainWindow()
{
InitializeComponent();
List<CheckBox> checkboxes = new List<CheckBox>();
checkboxes.Add(CheckBox1);
checkboxes.Add(CheckBox2);
_checkboxes = checkboxes.ToArray();
_checkboxActions.Add(CheckBox1.GetHashCode(), OnCheckBox1Checked);
_checkboxActions.Add(CheckBox2.GetHashCode(), OnCheckBox2Checked);
}
public void InvokeCheckboxActions()
{
Action action;
foreach(var checkbox in _checkboxes)
{
if(checkbox.IsChecked == true)
{
int checkboxPtr = checkbox.GetHashCode();
if(_checkboxActions.TryGetValue(checkboxPtr, out action))
{
action();
}
}
}
}
private void OnCheckBox1Checked()
{
Console.WriteLine("Checkbox 1 was checked");
}
private void OnCheckBox2Checked()
{
Console.WriteLine("Checkbox 2 was checked");
}
}
I think this code will have desired behavior.
public enum Mode { None, Break, Continue };
public sealed class Branch<T>
{
public Mode Mode { get; }
public T Value { get; }
public Action Action { get; }
public Branch(T value, Action action, Mode mode = Mode.None)
{
Value = value;
Action = action;
Mode = mode;
}
}
public static class CaseHelper
{
public static void Switch<T>(T condition, params Branch<T>[] branches)
{
bool Continue = false;
foreach (var branch in branches)
{
if (branch.Value.Equals(condition) || Continue)
{
branch.Action();
}
if (branch.Mode == Mode.Break) break;
Continue = branch.Mode == Mode.Continue;
}
}
}
usage:
CaseHelper.Switch(true, new Branch<bool>(box1.Checked, doSomething1), new Branch<bool>(box2.Checked, () => doSomething2()));
but it looks not very elegant
P.S.:
We can add implicit conversion operator to Branch
public static implicit operator Branch<T>(Tuple<T, Action, Mode> triple)
{
return new Branch<T>(triple.Item1, triple.Item2, triple.Item3);
}
public static implicit operator Branch<T>(Tuple<T, Action> duple)
{
return new Branch<T>(duple.Item1, duple.Item2);
}
and use something like this:
CaseHelper.Switch(true,
(Branch<bool>)Tuple.Create<bool, Action>(box1.Checked, doSomething1),
(Branch<bool>)Tuple.Create<bool, Action, Mode>(box2.Checked, () => doSomething2(), Mode.Break)
);

What is best practice for returning value or error message from method in c#?

I am trying to find the cleanest solution for returning value or error message from function / method in c#.
For now I have tried:
public float ValidateValue (float value)
{
if (value == VALID_VALUE)
{
return value;
}
else
{
throw new ArgumentException("Invalid value", "value");
}
}
This solution seems to be good enough but in Clean Code Cheap Sheet I have found:
Using Exceptions for Control Flow – Don't do this
Using exceptions for control flow:
has bad performance, is hard to understand and results in very hard
handling of real exceptional cases.
What will you do in the case of invalid input?
If you are writing code at the UI level that is taking the input from the user then it makes most sense to do something like:
private bool IsValid(float value)
{
return value == VALID_VALUE; // replace with real check.
}
Then in the calling code you would have:
public void ReactToInput()
{
float value = HoweverYouGetTheFloatFromTheUser();
if(!IsValid)
{
//Code to display error message.
}
else
{
//Code to do something useful.
//
//Code to display result.
}
}
Because your job at this level is "take what the user gave me, return what they want as best I can" and at this level its best to have the possibility of the user doing something incorrect front and centre.
If you are writing code for other code to make use of, then it makes most sense to do something like:
private void CheckValid(float valid)
{
if(value != VALID_VALUE) // replace with real check.
throw new ArgumentException();
}
Then in the calling code you would have:
public float DoWork(float value)
{
CheckValid(value)
//Code to do something useful.
//
//Code to return result.
}
Here your job is to do what the method's task is cleanly and return a meaninful result (or void if there isn't one). If you can't do that job, because the input you were given is nonsense (or for any other reason) then you need to stop as soon as you can and deal with that problem. You could do this by returning an error/success code every time and having calling code checking it every time, but while this approach does indeed have some advantages, exceptions let us:
Write with a focus on the correct behaviour.
Pass up exceptions.
For an example of 1, compare:
private bool WithExceptions()
{
return A() > B() && C() > D();
}
private bool WithExplicitChecks(out bool result)
{
result = false;
int a;
int b;
if(!A(out a))
return false;
if(!B(out b))
return false;
if(a <= b)
return true;
int c;
int d;
if(!C(out c))
return false;
if(!D(out d))
return false;
result = c > d;
return true;
}
For an example of 2, consider:
private void A()
{
if(_someField == null)
throw new InvalidOperationException("field not ready");
_someField.DoSomething();
}
private void B()
{
A();
}
private void C()
{
B();
}
private string D()
{
try
{
C();
}
catch(InvalidOperationException)
{
Console.Error.WriteLine("Was not ready");
}
}
Obviously a real case would have B() and C() do more, but we can see here that only A() has to worry about raising exceptions and only D() about dealing with them, B() and C() can both just concentrate on the main concern.*
The two approaches can be mixed. Consider:
private static string CheckValid(string path)
{
if(path.Length == 0)
return "You cannot enter an empty file path";
switch(path[path.Length - 1])
{
case '\\':
case '/':
return "You cannot enter a directory path";
}
return null;
}
public static void Main(string[] args)
{
Console.WriteLine("Enter a file path");
var path = Console.ReadLine().Trim();
var validationError = CheckValid(path);
if(validationError != null)
Console.Error.WriteLine(validationError);
else
{
try
{
using(var reader = new StreamReader(path))
Console.WriteLine(reader.ReadToEnd());
}
catch(FileNotFoundException)
{
Console.Error.WriteLine("File not found");
}
catch(UnauthorizedAccessException)
{
Console.Error.WriteLine("Access denied");
}
catch(IOException ioe)
{
Console.Error.WriteLine(string.Format("I/O Exception: {0}", ioe.Message));
}
}
Console.Read();
}
This simple program takes a file path from the user, and opens the relevant file and outputs the contents as text. It takes both approaches to error-handling.
Because we can easily check for invalid input that is empty, or which ends with / or \, that is done with simple control-flow and we present an error message instead of doing something.
Other issues we can only know about by trying to open the file and failing, so in those cases we handle the exceptions. I combine both explicit checks for two types of problem along with one for a general class of problems, and act accordingly.
There is a third type of exception handling here; if an exception happens that I don't expect at all, the program fails with a exception message being dumped for debugging purposes. This is the case anywhere you don't catch all exceptions, but a very useful one; because I don't have a blanket catch or catch(Exception) I don't confuse exceptions I'm expecting to deal with (go me for handling them!) with exceptions that are there because I made a mistake in not realising they could happen (boo me! now I have to fix it).
This is a simple program that takes a file path from the user, and outputs the contents of the file. Note that it combines both approaches:
*Do though always consider that something started in a method may not be finished if an exception busts through it.
If you want to validate some input value, I would expect a bool to be returned indicating 'valid' or 'invalid', or no return value and an exception thrown when the value is invalid.
So I would suggest to use this:
public bool ValidateValue(float value)
{
return value == VALID_VALUE;
}
Or this:
public void ValidateValue(float value)
{
if (value != VALID_VALUE)
{
throw new ArgumentException("Invalid value", "value");
}
}
So throwing an exception is not a problem, especially when there are multiple reasons to reject, and you want to distinguish the various reasons. Otherwise, just use a bool, like int.TryParse does for example.
A tuple may be useful to solve that issue:
public Tuple<float,string> ValidateValue (float value)
if (value == VALID_VALUE)
{
return new Tuple<bool, string>(value,string.Empty);
}
else
{
return new Tuple<bool, string>(false,"Invalid value");
}
When calling a function, check if the error string is empty first:
var validation = ValidateValue(myFloatValue);
if (validation.Item2 != string.Empty)
{
// report error
}
else
{
// No error core here validation.Item1 is your result
}
One idea could be to have some generic model. You may have some model roughly like:
public class MyReturnModel
{
public bool Success { get; set; }
public string ErrorOrSuccessMessage { get; set; }
public dynamic AnyModelToReturn { get; set; }
}
Now let's apply this on your provided case:
public MyReturnModel ValidateValue(float value)
{
//function logic here
bool result = value == VALID_VALUE;
string msg = result ? "valud is valid" : "value is invalid";
return new MyReturnModel { Success = result, ErrorOrSuccessMessage = msg }
}

Default param value for delegate [duplicate]

This question already has answers here:
Optional delegates in C# [duplicate]
(4 answers)
Closed 9 years ago.
I need to call a delegate method passed as a parameter, but since this parameter is optional I want to set the default value to a method implemented in the "destination" class.
This is an example where it almost works as expected:
public class AgeCalculator
{
public void SetAge(Client client, Func<int, int> getAge = default(Func<int, int>))
{
client.Age = getAge != default(Func<int, int>) ? getAge(client.Id) : this.getAge(client.Id);
}
private int getAge(int clientId) {
return 10;
}
}
And then..
class Program
{
static void Main(string[] args)
{
AgeCalculator calculator = new AgeCalculator();
Client cli1 = new Client(1, "theOne");
calculator.SetAge(cli1);//Sets 10
calculator.SetAge(cli1, getAge);//Sets 5
}
private static int getAge(int clientId) {
return 5;
}
}
The question now; what is the default value that has to be setted to avoid asking about the delegate value?
Tried "public void SetAge(Client client, Func getAge = this.getAge)" with no luck.
Is there a tag or different definition needed on AgeCalculator.getAge?, should I use dynamic methods?
Thanks in advance.
Note: The real scenario involves more complex logic in a TDD oriented project, this is a sample to summarize the situation.
Default values for method arguments must be compile-time constants. Writing default(Func<...>) is just verbose syntax for null, which is the default value for reference types (as a delegate, Func is a reference type) and the only default value you can use in this context.
However, you can do much better with the old-fashioned way of offering two overloads for the method:
public void SetAge(Client client)
{
// Select any default value you want by calling the other overload with it
SetAge(client, this.getAge);
}
public void SetAge(Client client, Func<int, int> getAge)
{
client.Age = getAge(client.Id);
}
This is basically doing what you are asking, the only thing is that the hints given by VS won't show that a function is being used as the default if null isn't used. If that isn't a problem then this solution is logically as close as you are going to get.
public class AgeCalculator
{
public void SetAge ( Client client , Func<int , int> getAge = null)
{
// assigns this.getAge to getAge if getAge is null
getAge = getAge ?? this.getAge;
client.Age = getAge( client.Id );
}
private int getAge ( int clientId )
{
return 10;
}
}
You can also make this something that allows a variable method to be plugged in if you want to change the default setter dynamically. It is identical logic just another way, this is beneficial if you know you will use the same function multiple times in a row.
public class AgeCalculator
{
public void SetAge ( Client client )
{
client.Age = GetAge( client.Id );
}
private Func<int,int> _getAge;
public Func<int,int> GetAge
{
private get
{
if(_getAge == null)
_getAge = getAge;
return _getAge;
}
set
{
if(value == null)
_getAge = getAge;
else
_getAge = value;
}
}
private int getAge ( int clientId )
{
return 10;
}
}
//assume we are in main
var cl = new Agecalculator();
var client = new Client(1,"theOne");
var client2 = new Client(2,"#2");
cl.SetAge(client); //set 10
cl.GetAge = getAge;
cl.SetAge(client); //set 5
cl.SetAge(client2); //set 5

Is this a correct implementation of the Strategy pattern with the FizzBuzz exercise?

I've recently had a real world use for the Strategy pattern. I find myself with hammer/nail syndrome where this pattern is my hammer and everything else is a nail. For kicks, I decided to try implementing FizzBuzz via the strategy pattern. Now, I know this is complete over kill. I've seen various Enterprise implementations of it, but this is my own implementation.
To my surprise and delight, this exercise turned up an interesting question: is there a standard or another pattern that works in conjunction with strategies to help you select which one to use? In my FizzBuzzStrategySelector class below, I put this logic in the Format function.
Obviously this implementation is not practical...but it might be if these Format methods actually had some real world logic to break down.
My basic question here is this: am I using the Strategy pattern correctly here?
class Program
{
static void Main(string[] args)
{
FizzBuzzStrategySelector fizzBuzzFormatter = new FizzBuzzStrategySelector();
for (int i = 1; i < 100; i++)
{
fizzBuzzFormatter.Format(i);
}
Console.ReadLine();
}
}
public interface IOutputFormatter
{
string FormatOutput(int value);
}
public class FizzBuzzStrategySelector
{
public IOutputFormatter formatStrategy;
public FizzBuzzStrategySelector() : this(new GeneralFormatter()) { }
public FizzBuzzStrategySelector(IOutputFormatter fizzBuzzFormatStrategy)
{
this.formatStrategy = fizzBuzzFormatStrategy;
}
public void Format(int value)
{
//THIS SEEMS LIKE A CODE SMELL. NOT SURE HOW TO WORK
//AROUND IT.
if(value % 15 == 0)
this.formatStrategy = new FizzBuzzFormatter();
else if(value % 3 == 0 )
this.formatStrategy = new FizzFormatter();
else if(value % 5 == 0)
this.formatStrategy = new BuzzFormatter();
else
this.formatStrategy = new GeneralFormatter();
Console.WriteLine(this.formatStrategy.FormatOutput(value));
}
}
public class GeneralFormatter : IOutputFormatter
{
public string FormatOutput(int value)
{
return value.ToString();
}
}
public class FizzBuzzFormatter : IOutputFormatter
{
public string FormatOutput(int value)
{
return "FizzBuzz";
}
}
public class BuzzFormatter : IOutputFormatter
{
public string FormatOutput(int value)
{
return "Buzz";
}
}
public class FizzFormatter : IOutputFormatter
{
public string FormatOutput(int value)
{
return "Fizz";;
}
}
Since (as you are aware) the Strategy Pattern is overkill for this problem, it is hard to say what would be "good" or "bad" design. However, my gut reaction would be to move the strategy selection logic into the strategies themselves, like so:
class FizzBuzzFormatter : IOutputFormatter
{
public bool Handles(int value) { return value.IsDivisibleBy(15); }
public string Handle(int value) { return "FizzBuzz"; }
}
This might be a little better in terms of composability, but you still need to make sure you have a list of IOutputFormatters in the correct order. With a problem this small, you can get away with anything. With a larger problem, you need to think about it and decide for yourself.
the different output formatters are part of the strategy pattern. typically there would be an object which requires the formatter. then you can call the formatter.
class Foo
{
public IOutputFormatter Formatter {get;set;}
}
var foo = new Foo();
foo.Formatter = new GeneralFormatter();
Console.WriteLine(foo.formatter.FormatValue("one");
foo.Formatter = new FizzBuzzFormatter();
Console.WriteLine(foo.formatter.FormatValue("one");
How the formatter is set, or which formatter is set can be the responsibility of another object.

Doing a fuse with a boolean

I have a lot of pieces of code which has to be run one time during initialization.
I have to use a boolean flag this way because it is in an event
bool _fuse;
void PerformLayout()
{
Size size;
if (!_fuse)
{
size = _InitialContainerSize;
_fuse = true;
}
else
size = parent.Size;
// ...
}
Because it happens often, I did something to make this boolean variable to look like a fuse :
So I did this:
bool _fuse;
void PerformLayout()
{
Size size;
if (!Burnt(ref _fuse))
size = _InitialContainerSize;
else
size = parent.Size;
// ...
}
If it is initialized to false, the result of the query returns false once, make the switch to true, and successive calls return true.
public static bool Burnt(ref bool value)
{
if (!value)
{
value = true;
return false;
}
else
return true;
}
Of course, it works, but I am only moderately satisfied and I am sure there is more elegant solutions. What would be yours ?
I think the general thrust in avoiding repetition here is right (even if the repetition is very small … but still). Just encapsulate it and name it properly:
struct InitializerGuard {
private bool hasRun;
public bool HasRun() {
if (hasRun)
return true;
hasRun = true;
return false;
}
}
Usage:
InitializerGuard sizeInitializer;
void PerformLayout()
{
Size size;
if (!sizeInitializer.HasRun())
size = _InitialContainerSize;
else
size = parent.Size;
// ...
}
But if you find yourself using this pattern very often this might indicate that a refactoring is in order. Maybe just assign default values to some variables? Why aren’t they initialised, anyway?
There are many ways of achieving this. You can create a complex state machine performing your logic (fastest) but for many cases, that will be overkill. Alternatively, you can keep track of an boolean which holds the state of your instance just like you have now. You can also decide to combine both solutions into a simple state machine with methods like (moderatly fast):
public class TestClass
{
private Action performLayoutAction;
public TestClass()
{
// initial state
performLayoutAction = InitializePeformLayout;
}
public void PerformLayout()
{
performLayoutAction();
}
private void InitializePeformLayout()
{
// whatever
performLayoutAction = ContiniousPerformLayout;
}
private void ContiniousPerformLayout()
{
// whatever
}
}
You can use nullable types and the null coalescing operator to declare a Size property:
Size? _containerSize;
Size ContainerSize {
get {
return (_containerSize ?? (_containerSize = _InitialContainerSize)).Value;
}
}
You can then use it like this:
void PerformLayout() {
var size = ContainerSize;
// ...
}
If the type you want to lazy initialize is a reference type it becomes even simpler.
Another option is to use the Lazy<T> type. This can used in multi-threading scenarios where the above code can break:
Lazy<Size> _containerSize = new Lazy<Size>(() => _InitialContainerSize);
void PerformLayout() {
var size = _containerSize.Value;
// ...
}

Categories

Resources