Using delegate Types vs methods - c#

I see increasing use of the delegate types offered in the System namespace (Action<T>; Predicate<T> etc). As these are delegates, my understanding is that they should be used where we have traditionally used delegates in the past (asynchronous calls; starting threads, event handling etc). Is it just preference or is it considered practice to use these delegate types in scenarios such as the below; rather than using calls to methods we have declared (or anonymous methods):
public void MyMethod()
{
Action<string> action = delegate(string userName
{
try
{
XmlDocument profile = DataHelper.GetProfile(userName);
UpdateMember(profile);
}
catch (Exception exception)
{
if (_log.IsErrorEnabled) _log.ErrorFormat(exception.Message);
throw (exception);
}
};
GetUsers().ForEach(action);
}
At first, I found the code less intuitive to follow than using declared or anonymous methods. I am starting to code this way, and wonder what the view are in this regard. The example above is all within a method. Is this delegate overuse?

For a simple foreach loop, I would prefer the normal language construct - see this blog post for Eric Lippert's view. I think the use of a delegate here is somewhat gratuitous.
In other cases - particularly with LINQ - it makes a lot of sense.
Delegates are a nice way of allowing specialization without the overhead of declaring and implementing an interface or deriving from a type in order to override methods... but everything in moderation, of course. If you've got several methods to implement (and you really want to specify behaviour for all of them) then an interface makes more sense. If you're genuinely creating a specialized type then deriving and overriding make sense. If you're wanting a strategy pattern, however, then delegates work very neatly.

Related

Using 'dynamic' in C# to implement Visitor Pattern

I have an application where I am performing an operation on a series of elements and the exact nature of the operation depends on the type of the element being operated upon. For reasons of encapsulation, it's not appropriate for the element to implement the operation; this means it can't be a virtual method on the element type and so 'standard' polymorphism doesn't work. I posed a previous question related to this and was informed that this was known as the Visitor Pattern.
I had previously always implemented this using an if/elseif dispatcher method based on the type of the object, then calling an appropriate implementation. Recently, however, I noticed that the same thing could be accomplishing using the dynamic keyword, like this:
private void ReconcileTips()
{
foreach (var step in _definition.Steps)
{
ReconcileTips((dynamic)step);
}
}
private void ReconcileTips(IBulkDispenseDefinition bulkDispense)
{
bulkDispense.TipType = ReconcileTip(bulkDispense.TipType);
}
private void ReconcileTips(ImportScreenDefinition importScreen)
{
foreach (var usage in importScreen.ReagentUsages)
usage.TipType = ReconcileTip(usage.TipType);
}
private void ReconcileTips(BuildScreenDefinition buildScreen)
{
foreach (var function in buildScreen.Functions)
function.TipType = ReconcileTip(function.TipType);
}
A similar pattern could be used for other operations parallel to the class structure, like creating view models for each element of _definition.Steps. The thought is that the compiler basically transforms this into the same if/elseif logic I wrote before, saving me the effort. So, a few questions:
Are there any gotchas with the dynamic dispatching that I haven't considered? I believe this is equivalent to performing a series of if (x is TypeA) Do((TypeA)x) else..., but I could be wrong.
Is this actually cleaner and easier to understand than a long if/elseif method?
Are there any gotchas with the dynamic dispatching that I haven't considered? I believe this is equivalent to performing a series of if (x is TypeA) Do((TypeA)x) else..., but I could be wrong.
The main gotcha would be if a type implements more than one interface in your visitor pattern - the compiler will probably pick the one you want, but it may not be the same choice you'd make if you use if (x is TypeA)/else if (x is TypeB) logic, as you'd control the order the checks occur.
Is this actually cleaner and easier to understand than a long if/elseif method?
I personally think so. This provides a very clean, fairly decently performing dispatch determined by the runtime type, and "just works." Hard to beat simple, short, clean code. Just make sure to (potentially) handle the case where you get a runtime error from the wrong type being passed in.
Yes, I was considering this approach, but decided against it for a more traditional approach. I derive each visitor from an interface that has Visit methods for each type I want to implement the operation for.
If you have a number of different operations you want to implement as visitors, eg. Save and Load operations, and you might want to add more in the future; with the dynamic approach you don't get compilation errors if you forget to implement your operation for one of the types you need to handle. You'll only find out when the program crashes and burns at runtime.
I want to be sure at compile time that any operation has been implemented for all of the possible types.

Have practices regarding on the use of extension methods changed or are there two schools of thought?

When I first learned about extension methods I read this:
In general, we recommend that you implement extension methods
sparingly and only when you have to. Whenever possible, client code
that must extend an existing type should do so by creating a new type
derived from the existing type.
However, I have numerious times seen a very liberal use of extension methods in various production code bases.
Granted, my experience is not representative of the majority but I would like to know if there's a shift in the guidelines, an alternate design philosophy, or if I just happened to see enough code that ignored the guidlines to make me think so?
NOTE: I am not trying to spark a debate (which will promptly lead to this question closing) - I've honestly been wondering about this for a while and feel my best chance at getting an answer is here on SO.
I think all this highlights is the usual difference between theory and practice. In theory we should use them sparingly but in practice we don't. In theory we should do a lot of things that we don't in practice do, in life in general, not only programming.
Polymorphism does not work with extension methods as they are bound in compile time.
ParentClass parentClass = new ParentClass();
ParentClass derivedClass = new DerivedClass();
If both of these classes have an extention method called ExtensionMethod() (I have defintely seen extension methods attempting to mimick virtual/overriden methods), both of these calls would call the parent class's extension method:
parentClass.ExtensionMethod();
derivedClass.ExtensionMethod();
In order to actually use the derived extension method, you would have to call:
((DerivedClass)derivedClass).ExtensionMethod();
Extending class is good approach, but often it is not available for code that uses third party libraries (which is common case for production code unlike in education/sample code). So derive new class if it makes sense, but feel free to use extension methods when they make code more readable.
There are multiple reasons why there are a lot of extension methods:
often you can't extend a class to add methods that would make your product code to be more readable. I.e. value types like String or some base classes in hierarchies like Stream.
extension methods is valuable way to add methods to interfaces without polluting the interface. LINQ is good example how it produces more readable code.
some frameworks recommend to use extension methods in particular cases. I.e. for MVC it is recommended to add extensions to HtmlHelper.
I think that there is pros and cons about using the extension methods.
Pros: The extension methods could be regarded as the visitor pattern(GoF). So, it takes advantage of the pattern, which is, without modifying code, we can extend some features.
Cons: Despite the advantage , why the MSDN tells using the extension methods sparingly is that, IMO, the extension methods would cause problem at some point. First, if the object for extension methods has different namespace from the extension, we should know where it is. It causes that sometimes we cannot use some important features from the extension. Moreover, I saw lot of code with extension abuse. Since extension is based on Type, sometime an object of that Type really do not need the extension, but when coding, we should see lots of extension method.
[update]
IMO, abuse about the extension methods
using so general type for extension method, like object: if there is lots of extension methods with object type and that extension is only focused on few types, it'll annoy us, as every object is linked with the methods.
broken linking with dot operator or misconception: Let me show an example. There is the code like below and we should call the Read and then Write method in order. However, we can call the methods in opposite order.
public static string Read(this string message)
{
//do something
return message;
}
public static string Write(this string message)
{
//do something
return message;
}
public static void Method()
{
"message".Read().Write();
"message".Write().Read(); // this is problem!
}

In Ruby, what is the equivalent to an interface in C#?

I'm currently trying to learn Ruby and I'm trying to understand more about what it offers in terms of encapsulation and contracts.
In C# a contract can be defined using an interface. A class which implements the interface must fulfil the terms within the contract by providing an implementation for each method and property (and maybe other things) defined. The individual class that implements an interface can do whatever it needs within the scope of the methods defined by the contract, so long as it accepts the same types of arguments and returns the same type of result.
Is there a way to enforce this kind of thing in Ruby?
Thanks
A simple example of what I mean in C#:
interface IConsole
{
int MaxControllers {get;}
void PlayGame(IGame game);
}
class Xbox360 : IConsole
{
public int MaxControllers
{
get { return 4; }
}
public void PlayGame(IGame game)
{
InsertDisc(game);
NavigateToMenuItem();
Click();
}
}
class NES : IConsole
{
public int MaxControllers
{
get { return 2; }
}
public void PlayGame(IGame game)
{
InsertCartridge(game);
TurnOn();
}
}
There are no interfaces in ruby since ruby is a dynamically typed language. Interfaces are basically used to make different classes interchangeable without breaking type safety. Your code can work with every Console as long it behaves like a console which in C# means implements IConsole. "duck typing" is a keyword you can use to catch up with the dynamic languages way of dealing with this kind of problem.
Further you can and should write unit tests to verify the behavior of your code. Every object has a respond_to? method you can use in your assert.
Ruby has Interfaces just like any other language.
Note that you have to be careful not to conflate the concept of the Interface, which is an abstract specification of the responsibilities, guarantees and protocols of a unit with the concept of the interface which is a keyword in the Java, C# and VB.NET programming languages. In Ruby, we use the former all the time, but the latter simply doesn't exist.
It is very important to distinguish the two. What's important is the Interface, not the interface. The interface tells you pretty much nothing useful. Nothing demonstrates this better than the marker interfaces in Java, which are interfaces that have no members at all: just take a look at java.io.Serializable and java.lang.Cloneable; those two interfaces mean very different things, yet they have the exact same signature.
So, if two interfaces that mean different things, have the same signature, what exactly is the interface even guaranteeing you?
Another good example:
interface ICollection<T>: IEnumerable<T>, IEnumerable
{
void Add(T item);
}
What is the Interface of System.Collections.Generic.ICollection<T>.Add?
that the length of the collection does not decrease
that all the items that were in the collection before are still there
that item is in the collection
And which of those actually shows up in the interface? None! There is nothing in the interface that says that the Add method must even add at all, it might just as well remove an element from the collection.
This is a perfectly valid implementation of that interface:
class MyCollection<T>: ICollection<T>
{
void Add(T item)
{
Remove(item);
}
}
Another example: where in java.util.Set<E> does it actually say that it is, you know, a set? Nowhere! Or more precisely, in the documentation. In English.
In pretty much all cases of interfaces, both from Java and .NET, all the relevant information is actually in the docs, not in the types. So, if the types don't tell you anything interesting anyway, why keep them at all? Why not stick just to documentation? And that's exactly what Ruby does.
Note that there are other languages in which the Interface can actually be described in a meaningful way. However, those languages typically don't call the construct which describes the Interface "interface", they call it type. In a dependently-typed programming language, you can for example express the properties that a sort function returns a collection of the same length as the original, that every element which is in the original is also in the sorted collection and that no bigger element appears before a smaller element.
So, in short: Ruby does not have an equivalent to a Java interface. It does however have an equivalent to a Java Interface, and its exactly the same as in Java: documentation.
Also, just like in Java, Acceptance Tests can be used to specify Interfaces as well.
In particular, in Ruby, the Interface of an object is determined by what it can do, not what class is is, or what module it mixes in. Any object that has a << method can be appended to. This is very useful in unit tests, where you can simply pass in an Array or a String instead of a more complicated Logger, even though Array and Logger do not share an explicit interface apart from the fact that they both have a method called <<.
Another example is StringIO, which implements the same Interface as IO and thus a large portion of the Interface of File, but without sharing any common ancestor besides Object.
Interfaces are usually introduced to static typed OO languages in order to make up for lack of multiple inheritance. In other words, they are more of a necessary evil than something useful per se.
Ruby, on the other hand:
Is dynamically typed language with "duck typing", so if you want to call method foo on two objects, they don't need to neither inherit same ancestor class, nor implement the same interface.
Supports multiple inheritance through concept of mixins, again no need for interfaces here.
Ruby doesn't really have them; interfaces and contracts generally live more in the static world, rather than the dynamic.
There is a gem called Handshake that can implement informal contracts, if you really need it.
Ruby uses the concept of Modules as a stand-in (kinda) for interfaces. Design Patterns in Ruby has a lot of really great examples on the differences between the two concepts and why ruby chooses the more flexible alternative to interfaces.
http://www.amazon.com/Design-Patterns-Ruby-Russ-Olsen/dp/0321490452
Jorg has a good point, ruby has interfaces, just not the keyword. In reading some of the replies, I think this is a negative in dynamic languages. Instead of enforcing an interface through the language, you must create unit tests instead of having a compiler catch methods not being implemented. It also makes understanding method harder to reason about, as you have to hunt down what an object is when you are trying to call it.
Take as an example:
def my_func(options)
...
end
If you look at the function, you have no clue what options is and what methods or properties it should call, without hunting for the unit tests, other places it is called, and even look at the method. Worse yet, the method may not even use those options but pass it to further methods. Why write unit tests when this should have been caught by a compiler. The problem is you must write code differently to express this downside in dynamic languages.
There is one upside to this though, and that is dynamic programming languages are FAST to write a piece of code. I don't have to write any interface declaration and later I can new methods and parameters without going to the interface to expose it. The trade-offs are speed for maintenance.

Overloads vs generic arguments

I have a question. In the framework, that was largely written before the generics came, you often see a function with lots of overloads to do something with different types.
a)
Parse(int data)
Parse(long data)
Parse(string data)
..etc
That seems to be to be ok as it helps keeping code small for each method and so. On the other hand, now with generics you can do the following:
b)
Parse<T>(T data)
and then have some kind of ifs/switch statements with typeof() to try to infer what the types are and what to do with them.
What is best practise? Or what are the ideias that'd help me choose between a) and b)?
IMHO, if you need if/switch statements, you should better overload. Generics should be used where the implementation does not depend on the concrete type to still reuse it.
So as a general rule:
overload if there will be a separate implementation for each type
use generics if you can have a single implementation that works for all possible types.
Code Smell.
If you have "some kind of if/switch", that is a code smell that just screams polymorphism. It suggests that generics is not the solution to that problem. Generics should be used when the code does not depend on the concrete types you pass into it.
Watch this Google Tech Talks Video: "The Clean Code Talks -- Inheritance, Polymorphism, & Testing". It addresses specifically what you are talking about.
The pattern your describing where the use of generics results in a bunch of ifs/switch statements is an anti-pattern.
One solution to this is to implement a strategy pattern, which allows you to use generics, but at the same time isolating concerns of the Parse method from knowing how to deal with every different case.
Example:
class SomeParser
{
void Parse<T>(ParseStrategy<T> parseStrategy, T data)
{
//do some prep
parseStrategy.Parse(data);
//do something with the result;
}
}
class ParseStrategy<T>
{
abstract void Parse(T data);
}
class StringParser: ParseStrategy<String>
{
override void Parse(String data)
{
//do your String parsing.
}
}
class IntParser: ParseStrategy<int>
{
override void Parse(int data)
{
//do your int parsing.
}
}
//use it like so
[Test]
public void ParseTest()
{
var someParser = new SomeParser();
someParser.Parse(new StringParser(), "WHAT WILL THIS PARSE TO");
}
and then you would be able to pass in any of the strategies you develop. This would allow you to properly isolate your concerns across multiple classes and not violate SRP (single responsibility principle.
One issue here - if you're requiring if/switch statements to make generics work, you probably have a larger problem. In that situation, it is most likely that the generic argument won't work (correctly) for EVERY type, just a fixed set of types you are handling. In that case, you are much better off providing overloads to handle the specific types individually.
This has many advantages:
There is no chance of misuse - you're user cannot pass an invalid argument
There is more clarity in your API - it is very obvious which types are appropriate
Generic methods are more complicated to use, and not as obvious for beginning users
The use of a generic suggests that any type is valid - they really should work on every type
The generic method will likely be slower, performance wise
If your argument CAN work with any type, this becomes less clear. In that case, I'd often still consider including the overloads, plus a generic fallback method for types. This provides a performance boost when you're passing an "expected" type to the method, but you can still work with other, non-expected types.
While there's no one-size-fits-all rule on this, generics should be used when the specific type is irrelevant. That isn't to say that you can't constrain the type, but that specific type doesn't actually matter. In this case, the parsing method is entirely dependent on (and different for) each type. Generics don't seem like a good solution here.
My rule of thumb for this scenario. There is overlap and there are subtleties, but this gets you on the path:
Overloading methods/functions is concerned with handling types, and doesn't make assumptions about interfaces available on the types.
An overloaded function will deal specifically with a type passed to it, and whatever interface it implements. Example printObject(t) may need to extract a property from 't' and print it manually (e.g. print(t.name) or cout << t.name;)
Generics is concerned with handling the interface(s) implemented, but is not concerned about the type of object.
A generic function will handle any type passed to it, but expect a specific interface implemented (e.g. printObject(t) may just call t.toString() on the object, presuming it's implemented)

Best practices: When should I use a delegate in .NET? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Delegate Usage : Business Applications
Where do I use delegates?
Hi,
I'm new to the concept of a delegate in .NET - I haven't really used them yet and think they are probably there for a good reason - when should I be using a delegate?
Examples are very welcome.
Delegates provide a way for you to pass behavior as a parameter.
Common examples are Events and asynchronous programming where something other than your object is responsible for calling into your object. You provide that event with a delegate, and now it's able to run the behavior associated with that delegate.
This can also be a useful technique when implementing a general algorithm. There've been times where I'm writing multiple methods that are very similar. Perhaps they loop over the same set of data, but they perform slightly different tasks. I can pass in a delegate to a single function to perform that task, then call the delegate from inside the loop over the data. This way I don't have to implement the loop over the data multiple times, I only have to write new code that does new things-- the common behavior is all captured in a common way.
In response to the comment:
The difference between calling the delegate from within the loop and calling the method from within the loop is that the delegate is a parameter to the function that contains the loop. This means that that function could do anything, not just what's defined within a particular method. That flexibility can and has been leveraged to supply generic algorithms in libraries completely independent of the specifics of what the algorithms are working with. Linq is a fine example of the generality that is allowed via the flexibility of delegates.
Delegates are useful when you need to tell another piece of code how to do something. Events are the simplest example - separating the event (something happened) from how to handle it. Other examples are some common iterative operations, such as a custom find:
List<Foo> foos = new List<Foo>();
foos.Find(delegate(Foo foo)
{
if(foo.CustomProperty.Contains("special value"))
{
return false;
}
return true;
});
The above is a totally arbitrary example but makes the point that you can separate the what (iterating and running a "find" criteria) from the how (how to determine whether something is found).
Also, I would recommend using generic delegate types instead of creating your own. Examples below:
EventHandler< TEventArgs>
Func< TResult>
Func< T1, T2, TResult>
Func etc...
Action< T1>
Action< T1, T2>
Action etc...
Events use delegates behind the scenes.
If you use events you've used delegates but just with a nicer syntax.
Basically one use for them is for callbacks or event based programming.
Delegates are used for event driven programming. Best practices are often about decoupling code (or 'loose' coupling). Using delegates you can subscribe methods to events, instead of having X call Y if something happens, and then Y call Z under a certain condition and so forth.
Events and Callbacks in the .NET guidelines explains it well.
In summary, you should prefer events in simple APIs because there is strong IDE support and most developers are comfortable with events. However, if you need the user to provide code that will be executed, you should consider using delegates or virtual members. Callbacks are less performant, but if you use delegates like Action and Func you allow lambdas.
Example case: a single resource is being used by multiple objects. The resource needs an asynchronous callback to these objects, but the nature of the resource demands that only one request be active at a given time, and that request is tied to a particular object. Due to the architecture, I don't want to pass the objects into the resource, so instead, I send the resource a delegate from each object and store these delegates along with object identifiers. When a request is made, I can look up the corresponding object identifier and call its specific delegate.
I originally implemented this with an event, but since the event couldn't be 'aimed' at a particular object, I was having issues. I'm not sure this is best practice, but it seems to work well for me.

Categories