I was doing some code refactoring today and this is one of the things that fits nicely to remove those repetitive codes.
I have lines of code below as an example where I process some data based on certain key.
| private void ProcessData()                  theKey = key.KeyA;                  theKey = key.KeyB;                  theKey = key.KeyA + key.KeyB;              | 
This looks simple enough, but imagine what would happen if i replace “the processing data with key…” line with 20 real codes, they suddenly become 60 lines which are repetitive, doing the same thing using the key ;)
So this is what I came out with, create a delegate which receives Key object then create 3 new methods which have the same signature as the delegate and will have the logic to construct the key.
| private delegate string AssignKeyDelegate(Key key);              | 
By using this, I can process the data and construct the key based on the appropriate method which is specified in the parameter using the delegate.
| private void Run()              | 
I provided the sample code above as a basic example only, there are many solutions that may come out with this kind of code :) The purpose is only to describe another feature that we can do with delegate.
Hope this helps :)
 
 



1 comments:
Excellent Passing methods. The example given in the Article si really interesting. Thanks for sharing such nice example here in this site.