Pluralsight blog Where devs, IT admins & creative pros go for news, tips, videos and more.
Pluralsight + Digital-Tutors - 3,000 tech & creative courses - starting at $29/month Get it now →
March 30, 2013

Antipatterns: What’s Wrong With This Code? — Answered!

By

The code excerpt below is a C# ASP.NET Web API controller that compiles and seems to run just fine.  Can you spot the problems in this code?  Hit the comment link and let us know what you think is wrong.  We’ll have the answer on Monday.

code

 

Answers:

  1. Use of a static field is not threadsafe.  ASP.NET Web APIs are inherently multi-threaded so using a static field is not a good idea.  There are several ways to fix this from using a SynchronizedDictionary to manually handling the locking via locks or semaphores.
  2. No Initialization of the data Dictionary.  This could cause various exceptions.
  3. Lack of defensive coding.  In several places there are assumptions being made about the content of the data dictionary that will cause exceptions at runtime.

We got lots of great answers, thanks everybody for their comments.  There were many answers given that may be technically correct but weren’t  necessarily the bugs we were hunting in this example.  Stay tuned for our next code puzzle, and rest assured we’ll work on making it more challenging.

About the Author

is a Chief Architect specializing in large scale distributed system development and enterprise software processes. Paul has more than twenty years of development experience including being a former Microsoft MVP, a speaker at technical conferences such as Microsoft Tech-Ed and VSLive, and a published author. Prior to working on the Windows platform, he built software using a vast array of technologies including Java, Unix, C, and even OS/2.


Discussion