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
- Looking For A Career In Tech? Whats Best For You?
- Video: Fight Code with Code using Code Contracts
- New Course: Code Contracts
- Get The Windows 7 Privileges Your Code Deserves!
- Code Simply
- New course: Entity Framework 4.1 – Code First
- Get Fast Access to 3500+ Code Samples
- Deploying iPads in the Enterprise: Your Questions Answered
- Video: Questions Asked and Answered on LinkedIn