ASP.NET MVC

How I misunderstood the MVC concept.

Someday I was tasked to create a web app for one of our departments. Sadly I had no experience in web development at that time. Due to tight schedule (and no knowledge about any other web frameworks) I have decided to use ASP.NET MVC. It seemed well supported, easy to learn and use.

Learning a new framework is like walking in the dark forest. If you are in hurry, it happen to hit a tree with your face. This is what I have learned from that project:

Don’t put application logic in the controller

According to Uncle Bob Martin, web application is only a delivery mechanism, just like console app or thick client app. It shouldn’t contain domain logic.

Controller, as a part of delivery mechanism, controls the web app. It takes incoming requests and transforms them into outgoing responses, prepares view models, validates data and user. That’s all. All operations related with domain should be in the model or some kind of service layer. Unfortunately, I made that mistake. I realized that something is wrong when I couldn’t reuse code from controllers.

It’s good to separate business logic from data source layer

In my first ASP.NET MVC project I mixed Entity Framework code with application logic. It looked messy and hard to understand. In the next project I have implemented a repository pattern. I noticed that it is clearer and easier to manage implementation when code responsible for querying the database is located somewhere else. All of this is related to single responsibility principle.

Don’t put logic in views if not needed

I know that using C# code in html using ASP.NET Razor is useful, however, view with to much c# code in can be hard to read and understand. I prefer to extract code into model methods. @User.GetNameWithTitle() is easier to understand than @{ if(condition) then { code } else { code }}.

Summary

If you are beginner in programming I suggest you to read “Clean Code” by Robert C. Martin or at least watch some of his speeches about clean code on YouTube. Great source of knowledge.

1
Leave a Reply

Please Login to comment
  Subscribe  
newest oldest most voted
Notify of
trackback

How I misunderstood the MVC concept. – mSzymczyk Blog

Dziękujemy za dodanie artykułu – Trackback z dotnetomaniak.pl