3

I have a DevelopmentConsole class. I am making functionality to register console commands for the subsystems. I don't want the console to know about them but also I don't want them to contain a debug code (like "Console.RegisterCommand...").

I think I should make an additional class hiearachy. For an example I have Player class.

IConsoleBuilder { 
    RegisterCommand(string command, Func<string[], string> action); 
}

PlayerConsoleBuilderClient : ConsoleBuilderClient { 
    readonly Player _player =  ?inject?

    public override void Visit(IConsoleBuilder builder) { 
        // builder.RegisterCommand("GetName", args => _player.Name) ; 
    }
}

Here I need to use Reflection to find all ConsoleBuilderClient subclasses. It's not a very good idea, is it?

Can you suggest how to do it in a better way?

  • Why is it not a good idea? Reflection is bad because it's slow and can be a bit unmaintainable. If you're just doing it at startup, the speed shouldn't matter. And this is simple enough that the unmaintainability is likely to not have a huge impact. – Telastyn Jan 4 '14 at 14:46
  • @Telastyn Because I should enumerate all types (possible in all appdomain assemblies) to find these subclasses. Too slow. – Vlad Jan 4 '14 at 15:39
  • @Vlad: why do you think its too slow (executed just once at the startup)? Did you measure it? – Doc Brown Jan 4 '14 at 15:41
  • @Vlad: when I understand your question correctly, you want your console to loop over all ConsoleBuilderClient subclasses, instantiate one object of that class and call the "Visit" method. Is that correct? If yes: in your example above, it looks as if there could be different objects of type PlayerConsoleBuilderClient, each object corresponds to a different command. How does that fit together? Looks for me like your are mixing objects and classes, but maybe I misunderstood something. – Doc Brown Jan 4 '14 at 15:45
  • @DocBrown "Is that correct?" - yes. "it looks as if there could be different objects of type" - no, I don't need a seperate class for every specific command but only for subsystem commands. I create only one instance of each BuilderClient subclass and use each of instance to register multple commands. It's to slow because I have to enumerate all types to compare BaseType property. I think ~200 ms. What if I have more than one system like this? – Vlad Jan 4 '14 at 16:47
1

There are only 2 options. You either explicitly define each client class in some kind of collection. Probably in some kind of topmost project. Or you use reflection to look for all subclasses of ConsoleBuilderClient in all loaded/available assemblies.

It is up to you to pick which one you prefer.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.