Antipatterns: What’s Wrong With This Code? — Answered!By Paul Ballard
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.
- 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.
- No Initialization of the data Dictionary. This could cause various exceptions.
- 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
Paul Ballard 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.
- Looking For A Career In Tech? Whats Best For You?
- Video: Fight Code with Code using Code Contracts
- Get The Windows 7 Privileges Your Code Deserves!
- New Course: Code Contracts
- Code Simply
- Video: Questions Asked and Answered on LinkedIn
- Deploying iPads in the Enterprise: Your Questions Answered
- New course: Entity Framework 4.1 – Code First
- Get Fast Access to 3500+ Code Samples