Simple Type Safe Coding in Microsoft’s C#

 

I often like to show programming tips around simple things.  Over the years, I’ve found that it is easy to get Lazy and do cutting and pasting type coding, however for reliability and maintainability, it’s important to stick to the principle of less is more.

Below is just a simple pattern I often use when doing something that requires processing over a set of images (or anything) multiple times.

foreach (var rec in imageDetails)
{
    const string imageTypeFull = "ImageTypeFull";
    const string imageTypeThumb = "ImageTypeThumb";
    foreach (var imageType in new List<string> {imageTypeFull, imageTypeThumb})
    {
        var bytes = imageType == imageTypeFull
                        ? db.DetailBytes.Where(a => a.Id == rec.Id).Select(b => b.DataBytes).
                                FirstOrDefault()
                        : db.DetailBytes.Where(a => a.Id == rec.Id).Select(b => b.DataBytes).
                                FirstOrDefault();

Basically, all through the foreach loop, I check for which imageType I am and do the appropriate thing.  Not a big hint, but something that is easy to forget to do.

HTH’s.

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. It’s tricky to say without seeing the full method but I would guess I would be injecting a dictionary of some sort into the method, keyed on image type and with values that contain delegates (probably lambdas if simple).

  2. Jim, What would you suggest for doing this? Do you still think Strategy Pattern? Strategy just seems too complex to me for something so simple.

  3. Even if the strategy pattern is overkill in this case, the above code isn’t ideal, as it breaks the open/closed principle.

  4. I would totally agree as long as there is justification for adding the complexity of the strategy pattern. For a simple case of two cases with relatively simple work, I think Strategy Pattern is too big a hammer.

    That said, I had not thought of it for this case but it is certainly worth considering. Thanks for pointing it out.

  5. Better to use strategy pattern.

Trackbacks

  1. [...] Simple Type Safe Coding in Microsoft’s C# – Peter Kellner [...]

Your Comments

*

Protected with IP Blacklist CloudIP Blacklist Cloud

Follow

Get every new post delivered to your Inbox

Join other followers: