I am filled with solutions

Weekly essays on testability, testing and being a tester.

Consider replacing strings with Enums in resource references.

Consider replacing strings with Enums in resource references.

I see code like this all the time in test and XNA and I really dislike it.

 

 

            MyCustomResourceClass resources = new MyCustomResourceClass();

            MyImageClass currentImage = resources["Image 1.jpg"];

 

 

I dislike because it’s nearly impossible to tell where the list of valid resources lives. You don’t want to put a comment on every reference to the resources class. Some /// documentations in the resources class might help, but you probably want to keep it generic.

 

I prefer a pattern that looks like this.

 

            //List of resources in the MyImages.XML file from the resources Directory.

            enum AvailableImages

            {

                Image1,

                Image2,

                Image3

            }

          

           MyImageClass nextImage = resources[AvailableImages.Image2];

 

You do incur overhead maintaining the enum, but it makes your code much clearer and promotes run time errors to compile time errors. Remember you can add descriptions to the enums if you have to do something like map to filenames with spaces in them. Then the resources class can have some intelligent code for looking up the file names.

Published Friday, November 21, 2008 11:53 PM by SaintD

Comments

No Comments
Anonymous comments are disabled

About SaintD

Dustin Andrews has been testing software at Microsoft since 2001. He currently programs primary in C# and has loved it ever since he learned it had a good regex class. He came from the industry where he has been an ISP unix admin, Perl and SQL developer, dev lead, help desk technician and manager. He has also waited tables, worked many long nights as a convenience store clerk disinfected shoes in a bowling alley and done other jobs he has blocked out of his memory. He is currently in the Unlimited Potential Group as a Server Test Lead.

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker