Using Delegates, Func and Lambdas: A Tutorial With Soldiers
Join the DZone community and get the full member experience.Join For Free
in this tutorial, written for beginning programmers, i’d like to show a little demonstration on the usage of delegates and how we can go all crazy by refactoring and magically see all our duplicate code disappear.
imagine we are writing the next ultimate command&conquer spinoff which can run on any computer …in console-mode. now imagine that in the early phases of our prototype we create a soldier class: all soldiers should be able to simply “do their thing” when asked to do so. when they do, they should report on what they do, of course. typical “doyourthing” actions might include throwing a grenade, cowardly running away or going into full rambo-mode:
phase 1: oldschool coding
smart as a cookie , we create our soldier class:
look how smart. we made our doyourthing() method virtual, allowing us to create an over-the-top amount of soldier childclasses that all override the method with the specific action that soldier can do.
mmm…but all these inherited classes (grenadesoldier, rambosoldier, etc.) are blowing out of proportion and contain 99% duplicate code.
phase 1.2 or 1.1
depending on your train of thought, you might first have done this step or first the previous one and then this one. anyhow, let’s be a smarter cookie and don’t go for inheritance and simply write a switch:
again, we’ll ignore the obvious improvement of making this actionnumber into an enum , but as you might have guessed, this still ain’t the right way.
phase 2: on with the delegates
since this tutorial about moving methods around like objects, let’s try to refactor our code so that delegates start showing their worth.
it’d be much handier if we could keep the implementation of the different actions a soldier can do outside the soldier class itself. imagine that in a future update of your game you’d like to add new cool soldiers and/or their actions, if we keep the everything tightly bound (i.e. keep the actions inside the soldier) we’d have to recompile our entire soldier class. so, out with the soldier actions, in with delegates!
so we defined a new soldieraction delegate which we’ll use as our vehicle to ‘give’ the action-implementation to the soldier.notice that we basically changed the type of our actionnumber from int to the newly creates soldieraction delegate type (and gave it a slightly improved name).
imagine now that we moved the different actions to self-contained methods , outside the soldier class:
we now can create cute little rambo’s and other types that will d the actions they were made for:
notice that intellisense (or is it resharper?) is kind enough to point out that we could also write:
for all you lambda lovers out there: suppose every action will be totally different and writing a method for each action would be overhead, we ould also write:
phase 3: enter action<t>
in the previous refactor, we explicitly defined a new delegatetype:
thanks to the more generic func/action delegates, we can remove that line in it’s entirety. basically func and action are generic, parameterized delegates. their main reason of existence is simply to remove lines like the one just mentioned in which we explicitly define a new delegate.
first , let’s see what the main difference is between func and action :
- func delegates are used to encapsulate methods that return a value .
- action delegates are used to encapsulate method that return void .
now, being the lazy bum that i am: check out this excellent tutorial on the basics of both func and action delegates. i can’t explain it any better than they do, so hop to that site, read it all and come back here. i can wait.
since our soldier actions return void, we’ll go for the action<t> delegate. however, because no parameters are provided we can use the non-generic one. our refactored class becomes (and we delete the soldieraction delegate definition):
note that we don’t have to change anything in the way we need to instantiate new soldier objects.
phase 4: icing on the cake
with this done. we can now create vast armies of soldiers doing their thing:
immediately our duplicate code alarm goes into overdrive. now what? well, just for the sake of completeness. let’s try to make those 3 lines in which we add new soldiers shorter, because, be honest, they are 90% identical (don’t start calculating this percentage please).
let’s wrap the ‘action’ of creating new soldiers and putting them in our list into…you’ll never guess it….wait for it. ..yup, let’s wrap it into an action delegate! and for the sake of being ubercool (hey we are writing c&c after all) , we’ll add in some samba..i mean lambda flavor!
now, to be honest. this last example was mainly introduced to show how we can define generic delegates: we simply state what parameters the delegatemethods accept (string, action in our case) and we’re done; no need to define a new delegatetype first.
how could we use our new fastsoldiermaker delegate? imagine we have several barracks, each which creates a specific type of soldier. we could pass the fastsoldiermaker to each barrack when it is constructed: each created soldier will automatically be added to our full list soldiers:
i leave it up to you to create a nifty random name generator for each soldier.
next we can now do something like:
so, that’s it for now. hope you’ve felt a bit of ‘the force’ of using delegates and their more modern generic counterparts.
Opinions expressed by DZone contributors are their own.