ASP.NET MVC Unleashed (1)

第1章 - ASP.NET MVC简介

“除了变化外,没有什么是永久的。 ” -赫拉克利特

In this chapter, you are provided with an overview and introduction to the Microsoft ASP.NET MVC framework. The goal of this chapter is to explain why you should want to build web applications using ASP.NET MVC.
Because the ASP.NET MVC framework was designed to enable you to write good software applications, the first part of this chapter is devoted to a discussion of the nature of good software. You learn about the software design principles and patterns that enable you to build software that is resilient to change.
Finally, we discuss the architecture of an ASP.NET MVC application and how this architecture enables you to write good software applications. You are provided with an overview of the different parts of an MVC application including Models, Views, and Controllers. You also are introduced to the sample application created when you create a new ASP.NET MVC project.
在本章中将为您简要介绍Microsoft ASP.NET的MVC框架。本章的目标是向您解释,为什么应当使用ASP.NET MVC去创建Web应用程序。
ASP.NET的MVC框架的设计目标就是为了使您能够编写出优良的应用软件;本章第一部分专门讨论优秀的软件的特性,您将了解到软件的设计原则和模式,它们有助于帮助您创建出适应变化的软件。
最后,我们讨论ASP.NET MVC应用程序的架构,讨论改架构如何使您写出很好的应用软件。 将向您展示一个MVC应用程序的各个部分,包括模型,视图和控制器( Models, Views, Controllers),同时也向您介绍创建一个新的ASP.NET MVC项目时(Visual Studio项目模板)生成的示例程序。

A Story with a Moral
I still remember the day that my manager came to my office and asked me to build the Single Button Application. He explained that he needed a simple call manager application to help interviewers dial phone numbers while conducting a health survey. The call manager application would load a list of phone numbers and dial each number one-by-one when you hit a button. What could be simpler?
I said, with great earnestness and confidence, that I would have the call manager application done that very same afternoon. I closed my office door, put on my cowboy hat, turned up the music, and pounded out some code. By the end of the day, I had completed the application. My manager was happy and I went home that night with the happy thought that I had done a good day of work.
The next morning, my manager appeared again at my office door. Worried, I asked if there was a problem with the call manager application. He reassured me that the application worked fine. In fact, he liked it so much that he wanted me to add another feature. He wanted the call manager application to display a survey form. when a number is dialed. That way, survey answers could be stored in the database.
With heroic determination, I once again spent the day knocking out code. By the end of the day, I had finished updating the call manager and I proudly presented the finished application to my manager.
I won’t continue this story, because anyone who builds software for a living knows how this story ends. The story never ends. Once a software project is brought to life, it is almost impossible to kill it. A software application needs to be continuously fed with new features, bug fixes, and performance enhancements.
一个故事的教训
我依然能记得,有一天我的经理来到我的办公室,要求我开发"一键通"应用程序(Single Button Application)。他解释说,他需要一个简单的呼叫管理器软件,能够在做健康调查的同时,帮助面试人员拨通电话。 当您按下按钮时,呼叫管理器将加载一个电话号码清单,并逐一进行拨号。还有什么能比此(工作方式)更简单?
我认真并且自信地告诉他,我下午便能将呼叫管理器软件交给他。我关起办公室的门,挂起牛仔帽,打开音乐,并”敲出“部分代码。在当天结束前,软件就写好了。我的经理很开心,我也由于高质量完成一天工作而心情愉悦地回了家。
第二天早上,我的经理再次来到我的办公室。我忐忑地问是不是软件存在问题,他确认说软件运行一切正常;事实上,他很喜欢这个软件,并且希望我能加入另一个功能。 他希望呼叫管理器能够在拨号后,显示一个调查表。 这样,调查的结果可以存储在数据库中。
带着英雄般的决心,我又敲了一天的代码,在当天结束前完成了软件的修改,并自豪地将它交到了经理手中。
我不会继续将这个故事说下去,因为所有以软件开发谋生的人都会知道这个故事的结局- 永远都不会结束。 一个软件项目一旦投入使用,结束它几乎是不可能的。应用软件需要不断地增加新特性、修复bug、以及增强性能等。

Being asked to change software that you have created is a compliment. Only useless software goes stagnant. When people care about software, when software is actively used, it undergoes constant change.
I no longer work at the company where I created the call manager application (I am currently sitting in an office at Microsoft). But, I still have friends at the company and every once in a while I get a report on how the application has changed. Needless to say, it has turned into a massively complex application that supports different time zones, complicated calling rules, and advanced reporting with charts. It can no longer be described as the Single Button Application.
被要求修改软件,这是您的一种荣幸;只有无用的软件才会停滞不前。 当人们关心这个软件,当软件正被积极使用,它必将经历不断的变化。
我已不在这家我曾开发出呼叫管理器的公司工作(现在我正坐在微软的一间办公室里)。 但是,我仍然有朋友在该公司工作,并且每隔一段时间我都会收到关于对这个呼叫管理软件所做更新的报告,毫无疑问,它已变成一个大型复杂的应用,支持不同的时区,复杂的呼叫规则,以及先进的报告与图表。 它再也不能被称为”一键通”。

What is Good Software?
I dropped out of graduate school at MIT to launch an Internet startup in the very earliest days of the web. At that time, building a website was very difficult. This was before technologies such as Active Server Pages or ASP.NET existed (we only had stone knives). Being able to save the contents of an HTML form. to a database table was a major accomplishment. Blinking text was the height of cool.
When I first started writing software, simply getting the software to do what I wanted was the goal. Adding as many features to a website in the shortest amount of time was the key to survival in the ferociously competitive startup world of the 90’s. I used to sleep in my office under my desk.
During my startup phase, I would define good software like this:
Good software is software that works as you intended.
If I was feeling particularly ambitious, I would worry about performance. And, maybe, just maybe, if I had extra time, I would add a comment or two to my code. But really, at the end of the day, my criterion for success was simply that the software worked.
For the past eight years, I’ve provided training and consulting to large companies and organizations such as Boeing, NASA, Lockheed Martin, and the National Science Foundation. Large organizations are not startups. In a large organization, the focus is not on building software applications as fast as possible; the focus is on building software applications that can be easily maintained over time.
Over the years, my definition of good software has shifted substantially. As I have been faced with the scary prospect of maintaining my own monsters, I’ve changed my definition of good software to this:
什么是优秀的软件?
本人放弃了在麻省理工学院研究生院的学习,在互联网发展的最早期开了一家互联网公司。 在那个时候,建设一个网站是非常困难的,没有诸如ASP或ASP.NET之类的技术可用(我们只有原始的石制刀)。 能够将HTML表单的内容保存到数据库表中是很了不起的成就;耍酷的最高境界只是页面上闪烁的文本。
当我第一次开始编写软件时,我的目标只是让软件像我所期望的那样工作。在最短的时间内向网站添加尽可能多的特性,对于90年代的一个具备强劲竞争力的创业公司来说是最关键的。 我经常睡在我的办公桌下。
优秀的软件对于在创业阶段的我来说是这样的:
优秀的软件就是按您预期方式工作的软件。
如果我正雄心勃勃,我才会担心性能方面的问题。也许,只是也许,如果我有更多的时间,我会往代码中添加一两条注释。但实际上,在一天结束的时候,我判断成功的标准只不过是“软件能够工作”这么简单。
在过去八年中,我已经为一些大公司和机构,如波音,美国航天局,洛克希德马丁公司,以及美国国家科学基金会等,提供培训和咨询。 大型的机构不像创业公司那样,在一个大型机构中,重点不是尽快地创建应用软,而是创建易于维护的应用软件。
多年来,我对优秀软件的定义已发生很大的转变。 每当我不得不面对维护自己那堆庞大丑陋的应用软件的骇人场景时,我将自己对优秀软件的定义修改为:

Good software is software that works as you intended and that is easy to change.
There are many reasons that software changes over time. Michael Feathers, in his excellent book Working Effectively with Legacy Code offers the following reasons:
1) You might need to add a new feature to existing software
2) You might need to fix a bug in existing software
3) You might need to optimize existing software
4) You might need to improve the design of existing software
For example, you might need to add new a feature to an application. The contact manager application started as a Single Button Application. However, each day, more and more features were added to the application.
You also need to change software when you discover a bug in the software. For instance, in the case of the contact manager, we discovered that it did not calculate daylight savings time correctly (it was waking some people up in the morning!). We rushed to change the broken code.
You also might need to modify a software application to make the application run faster. At one point, the contact manager application took as long as 12 seconds to dial a new phone number. The business rules were getting very complex. We had to rewrite the code to get the phone number retrieval time down to the millisecond range.
Finally, you might need to modify software to improve its design. In other words, you might need to take badly written code and convert it into good code. You might need to make your code more resilient to change.
优秀的软件就是按您预期的方式工作并且易于修改。
有许多理由能够说明软件会随时间的推移发生改变。 Michael Feathers在他那本出色的《Working Effectively with Legacy Code》一书中给出了以下一些理由:
1 )您可能需要往现有软件中添加新的功能
2 )您可能需要修正现有软件中的漏洞
3 )您可能需要优化现有的软件
4 )您可能需要改善现有软件的设计
例如,您可能需要往现有软件中增加新的功能。 那个联系人管理应用软件一开始是一个“一键通”。 然而,此后每天都有越来越多的功能被添加到该应用程序。
当您发现软件中的漏洞时也会对其进行修改。 拿那个联系人管理应用软件打比方,我们发现,它没有正确计算夏令时(它会在早晨吵醒一些人!)。 我们是飞奔过去修改这段错误的代码的。
您还可能想让应用软件运行的更快些而去修改它。那个联系人管理应用软件在某个时点上拨一个新号会花掉12秒。业务规则变得越来越复杂,以至于我们不得不重写代码,从而将电话号码的检索时间降到毫秒级。
最后,您可能需要修改软件,以改进其设计。 换句话说,你可能需要把写得很差的代码转换成好的代码。您可能需要让您的代码更适应变化。

Avoiding Code Smells
Unless you are careful, a software application very quickly becomes difficult to change. We all have had the experience of inheriting an application that someone else has written and being asked to modify it. Think of the fear that strikes your heart just before you make your first change.
In the game of Pick-up Sticks, you must remove stick after stick from a pile of sticks without disturbing the other sticks. The slightest mistake and the whole pile of sticks might scatter.
Modifying an existing software application is very similar to the game of Pick-up Sticks. You bump the wrong piece of code and you introduce a bug.
Bad software is software that is difficult to change. Robert and Micah Martin describe the markers of bad software as code smells. The following code smells indicate that software is badly written:

• Rigidity – Rigid software is software that requires a cascade of changes when you make a change in one place.
• Fragility – Fragile software is software that breaks in multiple places when you make a change.
• Needless Complexity – Needlessly complex software is software that is overdesigned to handle any possible change.
• Needless Repetition – Needlessly repetitious software contains duplicate code.
• Opacity – Opaque software is difficult to understand.
These code smells are described by Micah and Robert Martin in their book Agile Principles, Patterns, and Practices in C# on page 104. This book is strongly recommended!
Notice that these code smells are all related to change. Each of these code smells are a barrier to change.
避免代码质量下降
除非你非常小心,否则一个应用软件会很快变得难以修改。我们都有过这样的经历:要求你来接手去修改他人编写的应用程序。 可以想象,在您做第一次修改时的那种紧张和害怕。
在拾筷子游戏里,您必须逐一将筷子从堆叠在一起的筷子中移除而不能弄乱堆中的其他筷子;稍有不慎,堆叠在一起的筷子就可能塌倒。
修改现有应用软件的情形与拾筷子游戏非常相似:您改错了的代码,你就会将新的bug带入其中。
差的软件是难以修改的。罗伯特和麦克马丁将差软件的不妥之处描述为有异味的代码 。 下面这些“代码有异味”的情形表明软件写得很差:
刚性 - 刚性的软件就是当您修改软件的某一处时,需要修改一串其他地方。
脆弱性 - 脆弱的软件就是当您在一处做修改时,会引发多处错误。
不必要的复杂性 – 过于复杂的软件是设计过度,对任何“可能”发生的修改都做了预计的软件。
不必要的重复 – 包含不必要重复的软件是指软件中包含有重复的代码。
不透明 - 不透明的软件是很难理解的。
这些有关“代码气味”的描述,在米卡和罗伯特马丁所著的《敏捷原则,模式和实践:C#》一书中的第104页。 强烈推荐读者阅读这本书!
请注意,所有这些“散发异味的代码”都与变化有关,都是妨碍变化之处。

Software Design Principles
Software does not have to be badly written. A software application can be designed from the very beginning to survive change.
The best strategy for making software easy to change is to make the components of the application loosely coupled. In a loosely coupled application, you can make a change to one component of an application without making changes to other parts.
Over the years, several principles have emerged for writing good software. These principles enable you to reduce the dependencies between different parts of an application. These software principles have been collected together in the work of Robert Martin (AKA Uncle Bob).
Robert Martin did not invent all of the principles. However, he was the first one to gather the principles into a single list. Here is his list of Software Design Principles:
• SRP – Single Responsibility Principle
• OCP – Open Closed Principle
• LSP – Liskov Substitution Principle
• ISP – Interface Segregation Principle
• DIP – Dependency Inversion Principle
This collection of principles is collectively known by the acronym SOLID (Yes, SOLID is an acronym of acronyms).
There are other lists of software design principles. For example, the Head First Design Patterns book has a very nice list.
For example, according to the Single Responsibility Principle, a class should have one, and only one, reason to change. Here’s a concrete example of how this principle is applied: if you know that you might need to modify your application’s validation logic separately from its data access logic, then you should not mix validation and data access logic in the same class.
软件设计原则
软件不应当被写得很糟;应用软件可以从一开始便设计为能够适应未来的变化。
开发易于修改软件的最佳策略是,使应用软件的构件之间低耦合 。 在一个低耦合的应用软件中,您可以修改其中一个构件而无需改变其他构件。
这些年来,逐渐形成了编写优秀软件的一些原则, 这些原则能够使您降低应用系统不同构件间的耦合性。 这些原则已被罗伯特马丁(又名鲍勃大叔)收集在他的作品中。
罗伯特马丁并没有发明所有这些原则; 然而,他是第一个将这些原则整理成一个列表的人。 以下是他列出的软件设计原则:
SRP – Single Responsibility Principle单一责任原则
OCP – Open Closed Principle开闭包原则
LSP – Liskov Substitution Principle (Liskov代换原则)
ISP – Interface Segregation Principle 接口分离原则
DIP – Dependency Inversion Principle依赖反置原则
这个清单统称为SOLID缩写(不错,SOLID是缩写的缩写) 。
例如,根据单一责任原则,一个类应仅仅为单一的原因而修改。 下面是这一原则的具体例子:如果您知道,您可能会需要修改您的应用程序,将验证输入的逻辑与数据访问逻辑相分离,那么您不应该将验证和数据访问逻辑混合在同一个类中。
还有其他的软件设计原则的清单。例如, 《Head First Design Patterns》一书中有一个非常好的清单。

Software Design Patterns
Software Design Patterns represent strategies for applying Software Design Principles. In other words, a Software Design Principle is a good idea and a Software Design Pattern is the tool that you use to implement the good idea (It’s the hammer).
The idea behind Software Design Patterns was originally promoted by the book Design Patterns: Elements of Reusable Object-Oriented Software (This book is known as the Gang of Four book). This book has inspired many other books that describe Software Design Patterns.
The Head First Design Pattern book provides a more user-friendly introduction to the design patterns from the Gang of Four book. The Head First Design book devotes chapters to 14 patterns with names like Observer, Façade, Singleton and Adaptor.
Another influential book on Software Design Patterns is Martin Fowler’s book Patterns of Enterprise Application Architecture. This book has a companion website which lists the patterns from the book at:
http://www.martinfowler.com/eaaCatalog/
Software Design Patterns provide you with patterns for making your code more resilient to change. For example, in many places in this book, we’ll be taking advantage of a Software Design Pattern named the Repository Pattern. Eric Evans, in his book Domain-Driven Design, describes the Repository pattern like this:
A REPOSITORY represents all objects of a certain type as a conceptual set (usually emulated). It acts like a collection, except with more elaborate querying capability. Objects of the appropriate type are added and removed, and the machinery behind the REPOSITORY inserts them or deletes them from the database. (see page 151)
According to Evans, one of the major benefits of the Repository pattern is that it enables you to “decouple application and domain design from persistence technology, multiple database strategies, or even multiple data sources.” (ibid) In other words, the Repository pattern enables you to shield your application from changes in how you perform. database access.
For example, when we write our forums application at the end of this book, we’ll take advantage of the Repository pattern in order to isolate our forums application from a particular persistence technology. The forums application will be designed in such a way that we could switch between different data access technologies such as LINQ to SQL, the Entity Framework, or even NHibernate.
软件设计模式
软件设计模式代表的是软件设计原则的具体应用。换句话说,软件的设计原则是好的概念,而软件设计模式则是实现这些好主意的工具(它是锤子)。
软件设计模式背后的深邃思想因《设计模式:构建可复用的面向对象软件》 一书而广泛流传(这本书被称为四人帮之书)。 这本书引发了更多的描述软件设计模式的著作。
《Head First Design Patterns》一书以更简单易用的方式向读者介绍了《设计模式:构建可复用的面向对象软件》书中的设计模式,该书用以模式的名称,如Observer, Façade, Singleton and Adaptor等,描述了14种设计模式。
另一本有影响的软件设计模式书籍是是马丁福勒《企业级应用体系结构模式》 。 这本书有一个对应的网站,列出了书中描述的模式:
http://www.martinfowler.com/eaaCatalog/
软件设计模式提供了使您的代码更具变化弹性的模式。 例如,在本书的许多地方,我们将利用一个称为仓储(Repository)模式的设计模式。 埃里克埃文斯在其《领域驱动设计》著作中,将仓储模式描述为:
一个REPOSITORY将同一类型的对象表示为一个概念集(通常指模仿)。其行为类似于一个具备复杂查询能力的集合。满足该集合限定类型的对象实例被添加到其中,从中删除,而REPOSITORY的内部机制自动控制数据库的插入或删除。 (见151 页)
Evans指出,使用REPOSITORY模式的主要好处之一是,它使您能够“将应用领域设计与持久化技术、多数据库、甚至多数据源策略相分离。 ” ( 同上 )换言之,REPOSITORY模式能够让您在修改数据访问代码时,做到应用的其他部分不受影响。
例如,我们在本书最后写一个论坛应用程序时,我们将充分利用Repository模式,将我们的论坛应用程序与特定的持久化技术相分离。 该论坛将被设计为能够切换使用不同的数据访问技术,如LINQ to SQL,实体框架(Entity Framework),甚至NHibernate 。

Writing Unit Tests for Your Code
By taking advantage of Software Design Principles and Patterns, you can build software that is more resilient to change. Software Design Patterns are architectural patterns. They focus on the gross architecture of your application.
If you want to make your applications more change proof on a more granular level, then you can build unit tests for your application. A unit test enables you to verify whether a particular method in your application works as you intend it to work.
There are many benefits that result from writing unit tests for your code:
1) Building tests for your code provides you with a safety net for change.
2) Building tests for your code forces you to write loosely coupled code.
3) Building tests for your code forces you to take a user perspective on the code.
First, unit tests provide you with a safety net for change. This is a point that Michael Feathers emphasizes again and again in his book Working Effectively with Legacy Code. In fact, he defines legacy code as “simply code without tests” (see xvi).
When your application code is covered by unit tests, you can modify the code without the fear that the modifications will break the functionality of your code. Unit tests make your code safe to refactor. If you can refactor, then you can modify your code using Software Design Patterns which results in better code that is more resilient to change.
Refactoring is the process of modifying code without changing the functionality of the code.
Second, writing unit tests for your code forces you to write code in a particular way. Testable code tends to be loosely coupled code. A unit test performs a test on a unit of code in isolation. In order to build your application so that it is testable, you need to build the application in such a way that it has isolatable components.
One class is loosely coupled to a second class when you can change the first class without changing the second class. Test-driven development often forces you to write very loosely coupled code. Loosely coupled code is resistant to change.
Finally, writing unit tests forces you to take a user’s perspective on the code. When writing a unit test, you take on the same perspective as a developer who will use your code in the future. Since writing tests forces you to think about how a developer (perhaps, your future self) will use your code, the code tends to be better designed.
为您的代码编写单元测试
利用软件设计原则和模式,您可以创建更有弹性、适应变化的软件。 软件设计模式是体系结构模式,它们着重于您应用系统的总体架构。
如果您想对您的应用程序做更细粒度级别的修改,那么您可以为您的应用程序建立单元测试。 单元测试可以让您验证某一个特定的方法是按照您的预期工作的。
为您的代码编写单元测试有许多好处:
1 )为您的代码编写测试用例,使您所做的修改更加安全。
2 )为您的代码编写测试用例,会迫使您去编写低耦合的代码。
3 )为您的代码编写测试用例,会迫使您从用户的角度去审视您的代码。
首先,单元测试为您提供修改应用的一个安全网,对此,Michael Feathers在《Working Effectively with Legacy Code》一书中多次反复地加以强调。 事实上,他将遗留代码定义为“没有测试代码的代码” (见xvi)。
当您应用程序的代码被单元测试所覆盖时,您可以修改代码而无需担心这些修改会破坏代码所实现的功能。单元测试使您能够安全地重构代码。如果您可以重构,那么您可以利用软件设计模式来修改您的代码,使之更有弹性、更适应变化。
重构是指在修改代码过程的同时,不改变代码实现的功能。
其次,为您的代码编写单元测试将迫使您以一种特殊的方式编写代码;可测试的代码往往是松散耦合的代码。一个单元测试对单个代码段独立进行测试。为了创建可测试的应用程序,您就必须以这种方式来构建:应用程序的各个部分是可分离的组件。
一个类与另一个类是松散耦合关系,表明您可以变更其中一个类而无需改变另一个。测试驱动的开发过程常常迫使您编写非常松耦合的代码。低耦合的代码是有弹性的、易于改变的代码。
最后,编写单元测试将迫使您从用户的角度去审视代码。 当编写一个单元测试时,您将会站在一个将来可能使用您的代码的开发者的角度来思考。既然编写测试会迫使您从一个开发者角度(如何利用您的代码)考虑(也许就是您自己),设计出的代码往往是会设计的更好。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/740297/viewspace-557787/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/740297/viewspace-557787/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值