Sunday, March 13, 2011

My coding rule for C# from functional programming

1. Use conditional operator than if statement.
The following code:
if (a == 1) {
obj.X = 10;
}
else {
obj.X = 20;
}

Rewrite following code:
obj.X = (a == 1 ? 10 : 20);

Assignment should be limited.

2. Use Func delegate for modifying the action.

The following code:
int func(int a)
{
return (a == 1 ? 10 : 20);
}

Rewrite following code:
int func(Func<bool> f)
{
return (f() ? 10 : 20);
}

If necessary, make the wrapper function.

ex:
int func(int a)
{
return func(() => a == 1);
}

No comments:

Post a Comment