Nesting anonymous delegates in C# - how to make code maintainable and readable?

247 views Asked by At

I'm making a game, and it may have modal UI windows, like popover windows. I encapsulated all the fiddling into my class and I just call one method to show such window on screen, for example a method to show a list of characters:

ShowCharactersTable(List<Character>list, 
    Action<Character>didSelectCharacter, Action<bool>didCancel)

Example in use:

ShowCharactersTable(someList, delegate(Character selectedCharacter) {

// code that runs after you picked a character

, delegate(bool didCancel){

// code that runs after you cancelled selection

});

This is fine. Everything is transparent and easy to use. But I get into trouble as soon as I need to nest this. For example, on character list I have few buttons on each character cell, so I need to provide delegates for that. This gets complicated. I also might need to show another modal window on top of that, with a call like this:

ShowActivitySelector(List<Activity>activitiesToShow,
     Action<Activity>didSelectActivity,   
     Action<bool>didCancelPickingActivity);

And when I select activity I might need to show Alert if something goes wrong, like here:

ShowAlert(string alertText, Activity<bool>didAccept,
          Activity<bool>didCancel);

So now, to call a simple table of characters I need to write a 3 page long method with nested delegates. Does not sound like fun. How can I modularize this and make easier/more maintainable?

I don't want to couple my interface to my model, as I will need to show those lists, selectors and alerts from many different parts of my game with different parameters. How can this be fixed and what do I do about this?

0

There are 0 answers