分享
FoundationsOfProgramming.pdf
下载文档

ID:3041350

大小:1.27MB

页数:79页

格式:PDF

时间:2024-01-18

收藏 分享赚钱
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,汇文网负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
网站客服:3074922707
FoundationsOfProgramming
Foundations of Programming Building Better Software By Karl Seguin WWW.CODEBETTER.COM Foundations of Programming Copyright Karl Seguin 2 Foundations of Programming This page was intentionally left blank Foundations of Programming Copyright Karl Seguin 3 Foundations of Programming License The Foundations of Programming book is licensed under the Attribution-NonCommercial-Share-Alike 3.0 Unported license.You are basically free to copy,distribute and display the book.However,I ask that you always attribute the book to me,Karl Seguin,do not use it for commercial purposes and share any alterations you make under the same license.You can see the full text of the license at:http:/creativecommons.org/licenses/by-nc-sa/3.0/legalcode Downloadable Learning Application Reading about code is a good way to learn,but if youre anything like me,nothing beats a real application.Thats why I created the Canvas Learning Application-a simple(yet complete)ASP.NET MVC website which leverages many of the ideas and tools covered in this book.The application is a Visual Studio 2008 solution with helpful inline documentation meant to help you bridge the gap between theory and practice.The Canvas Application and this book are pretty independent,so you can approach this journey however you prefer.http:/ Acknowledgement There are countless of people who deserve thanks.This book is but a small contribution to the incalculable time donated and knowledge shared by the software community at large.Without the quality books,forums,newsgroup posts,blogs,libraries and open source projects,I would still be trying to figure out why my ASP script was timing-out while looping through a recordset(stupid MoveNext).Its no surprise that the software community has leveraged the openness of the internet more than any other profession in order to advance our cause.What is surprising is how the phenomenon appears to have gone unnoticed.Good!Of course,there is one special person without whom this couldnt have happened.To Wendy,People call me lucky for being with someone as beautiful and intelligent as you.They dont know the half of it.You are not only beautiful and intelligent,but you let me spend far too much time on my computer,either working,learning,writing or playing.Youre also more than happy to read over my stuff or listen to me blab on about nonsense.I dont appreciate you nearly as much as I should.Foundations of Programming Copyright Karl Seguin 4 Foundations of Programming Table of Contents About the Author.6 ALT.NET.7 Goals.8 Simplicity.8 YAGNI.8 Last Responsible Moment.9 DRY.9 Explicitness and Cohesion.9 Coupling.9 Unit Tests and Continuous Integration.9 In This Chapter.10 Domain Driven Design.11 Domain/Data Driven Design.11 Users,Clients and Stakeholders.12 The Domain Object.13 UI.15 Tricks and Tips.16 Factory Pattern.16 Access Modifiers.17 Interfaces.17 Information Hiding and Encapsulation.18 In This Chapter.19 Persistence.20 The Gap.20 DataMapper.20 We have a problem.23 Limitations.24 In This Chapter.25 Dependency Injection.26 Sneak Peak at Unit Testing.27 Dont avoid Coupling like the Plague.28 Dependency Injection.28 Constructor Injection.28 Frameworks.30 A Final Improvement.32 In This Chapter.33 Unit Testing.34 Why Wasnt I Unit Testing 3 Years Ago?.35 The Tools.36 nUnit.36 Foundations of Programming Copyright Karl Seguin 5 Foundations of Programming What is a Unit Test.38 Mocking.38 More on nUnit and RhinoMocks.41 UI and Database Testing.42 In This Chapter.42 Object Relational Mappers.43 Infamous Inline SQL vs.Stored Procedure Debate.43 NHibernate.46 Configuration.46 Relationships.49 Querying.50 Lazy Loading.51 Download.52 In This Chapter.52 Back to Basics:Memory.53 Memory Allocation.53 The Stack.53 The Heap.54 Pointers.55 Memory Model in Practice.57 Boxing.57 ByRef.58 Managed Memory Leaks.61 Fragmentation.61 Pinning.62 Setting things to null.63 Deterministic Finalization.63 In This Chapter.63 Back to Basics:Exceptions.64 Handling Exceptions.64 Logging.65 Cleaning Up.65 Throwing Exceptions.67 Throwing Mechanics.67 When To Throw Exceptions.68 Creating Custom Exceptions.69 In This Chapter.72 Back to Basics:Proxy This and Proxy That.73 Proxy Domain Pattern.74 Interception.75 In This Chapter.77 Wrapping It Up.78 Foundations of Programming Copyright Karl Seguin 6 Foundations of Programming About the Author Karl Seguin is a developer at Epocal Corporation,a former Microsoft MVP,a member of the influential CodeB community and an editor for DotNetSlackers.He has written numerous articles and is an active member of various Microsoft public newsgroups.He lives in Ottawa,Ontario Canada.His personal webpage is:http:/ blog,along with that of a number of distinguished professionals,is located at:http:/ of Programming Copyright Karl Seguin 7 Chapter 1-ALT.NET ALT.NET IF THERE IS DISSATISFACTION WITH THE STATUS QUO,GOOD.IF THERE IS FERMENT,SO MUCH THE BETTER.IF THERE IS RESTLESSNESS,I AM PLEASED.THEN LET THERE BE IDEAS,AND HARD THOUGHT,AND HARD WORK.IF MAN FEELS SMALL,LET MAN MAKE HIMSELF BIGGER.HUBERT H HUMPHREY few years ago I was fortunate enough to turn a corner in my programming career.The opportunity for solid mentoring presented itself,and I took full advantage of it.Within the space of a few months,my programming skills grew exponentially and over the last couple years,Ive continued to refine my art.Doubtless I still have much to learn,and five years from now Ill look back on the code I write today and feel embarrassed.I used to be confident in my programming skill,but only once I accepted that I knew very little,and likely always would,did I start to actually understand.My Foundations of Programming series is a collection of posts which focus on helping enthusiastic programmers help themselves.Throughout the series well look at a number of topics typically discussed in far too much depth to be of much use to anyone except those who already know about them.Ive always seen two dominant forces in the.NET world,one heavily driven by Microsoft as a natural progression of VB6 and classic ASP(commonly referred to as The MSDN Way)and the other heavily driven by core object oriented practices and influenced by some of the best Java projects/concepts(known as ALT.NET).In reality,the two arent really comparable.The MSDN Way loosely defines a specific way to build a system down to each individual method call(after all,isnt the API reference documentation the only reason any of us visit MSDN?)Whereas ALT.NET focuses on more abstract topics while providing specific implementation.As Jeremy Miller puts it:the.Net community has put too much focus on learning API and framework details and not enough emphasis on design and coding fundamentals.For a relevant and concrete example,The MSDN Way heavily favors the use of DataSets and DataTables for all database communication.ALT.NET however,focuses on discussions about persistence design patterns,object-relational impendence mismatch as well as specific implementations such as NHibernate(O/R Mapping),MonoRail(ActiveRecord)as well as DataSets and DataTables.In other words,despite what many people think,ALT.NET isnt about ALTernatives to The MSDN Way,but rather a belief that developers should know and understand alternative solutions and approaches of which The MSDN Way is part of.Of course,its plain from the above description that going the ALT.NET route requires a far greater commitment as well as a wider base of knowledge.The learning curve is steep and helpful resources are just now starting to emerge(which is the reason I decided to start this series).However,the rewards are worthwhile;for me,my professional success has resulted in greater personal happiness.A 1 Foundations of Programming Copyright Karl Seguin 8 Chapter 1-ALT.NET Goals Although simplistic,every programming decision I make is largely based on maintainability.Maintainability is the cornerstone of enterprise development.Frequent CodeBetter readers are likely sick of hearing about it,but theres a good reason we talk about maintainability so often its the key to being a great software developer.I can think of a couple reasons why its such an important design factor.First,both studies and firsthand experience tell us that systems spend a considerable amount of time(over 50%)in a maintenance state-be it changes,bug fixes or support.Second,the growing adoption of iterative development means that changes and features are continuously made to existing code(and even if you havent adopted iterative development such as Agile,your clients are likely still asking you to make all types of changes.)In short,a maintainable solution not only reduces your cost,but also increases the number and quality of features youll be able to deliver.Even if youre relatively new to programming,theres a good chance youve already started forming opinions about what is and isnt maintainable from your experience working with others,taking over someones application,or even trying to fix something you wrote a couple months ago.One of the most important things you can do is consciously take note when something doesnt seem quite right and google around for better solutions.For example,those of us who spent years programming in classic-ASP knew that the tight integration between code and HTML wasnt ideal.Creating maintainable code isnt the most trivial thing.As you get started,youll need to be extra diligent until things start to become more natural.As you might have suspected,we arent the firsts to put some thought into creating maintainable code.To this end,there are some sound ideologies you ought to familiarize yourself with.As we go through them,take time to consider each one in depth,google them for extra background and insight,and,most importantly,try to see how they might apply to a recent project you worked on.Simplicity The ultimate tool in making your code maintainable is to keep it as simple as possible.A common belief is that in order to be maintainable,a system needs to be engineered upfront to accommodate any possible change request.Ive seen systems built on meta-repositories(tables with a Key column and a Value column),or complex XML configurations,that are meant to handle any changes a client might throw at the team.Not only do these systems tend to have serious technical limitation(performance can be orders of magnitude slower),but they almost always fail in what they set out to do(well look at this more when we talk about YAGNI).In my experience,the true path to flexibility is to keep a system as simple as possible,so that you,or another developer,can easily read your code,understand it,and make the necessary change.Why build a configurable rules engine when all you want to do is check that a username is the correct length?In a later chapter,well see how Test Driven Development can help us achieve a high level of simplicity by making sure we focus on what our client is paying us to do.YAGNI You Arent Going to Need It is an Extreme Programming belief that you shouldnt build something now because you think youre going to need it in the future.Experience tells us that you probably wont actually need it,or youll need something slightly different.You can spend a month building an Foundations of Programming Copyright Karl Seguin 9 Chapter 1-ALT.NET amazingly flexible system just to have a simple 2 line email from a client make it totally useless.Just the other day I started working on an open-ended reporting engine to learn that I had misunderstood an email and what the client really wanted was a single daily report that ended up taking 15 minutes to build.Last Responsible Moment The idea behind Last Responsible Moment is that you defer building something until you absolutely have to.Admittedly,in some cases,the latest responsible moment is very early on in the development phase.This concept is tightly coupled with YAGNI,in that even if you really DO need it,you should still wait to write it until you cant wait any longer.This gives you,and your client,time to make sure you really DO need it after all,and hopefully reduces the number of changes youll have to make while and after development.DRY Code duplication can cause developers major headaches.They not only make it harder to change code(because you have to find all the places that do the same thing),but also have the potential to introduce serious bugs and make it unnecessarily hard for new developers to jump onboard.By following the Dont Repeat Yourself(DRY)principal throughout the lifetime of a system(user stories,design,code,unit tests and documentation)youll end up with cleaner and more maintainable code.Keep in mind that the concept goes beyond copy-and-paste and aims at eliminating duplicate functionality/behavior in all forms.Object encapsulation and highly cohesive code can help us reduce duplication.Explicitness and Cohesion It sounds straightforward,but its important to make sure that your code does exactly what it says its going to do.This means that functions and variables should be named appropriately and using standardized casing and,when necessary,adequate documentation be provided.A Producer class ought to do exactly what you,other developers in the team and your client think it should.Additionally,your classes and methods should be highly cohesive that is,they should have a singularity of purpose.If you find yourself writing a Customer class which is starting to manage order data,theres a good chance you need to create an Order class.Classes responsible for a multitude of distinct components quickly become unmanageable.In the next chapter,well look at object oriented programmings capabilities when it comes to creating explicit and cohesive code.Coupling Coupling occurs when two classes depend on each other.When possible,you want to reduce coupling in order to minimize the impact caused by changes,and increase your codes testability.Reducing or even removing coupling is actually easier than most people think;there are strategies and tools to help you.The trick is to be able to identify undesirable coupling.Well cover coupling,in detail,in a later chapter.Unit Tests and Continuous Integration Unit Testing and Continuous Integration(commonly referred to as CI)are yet another topic we have to defer for a later time.There are two things that are important for you to know beforehand.First,both Foundations of Programming Copyright Karl Seguin 10 Chapter 1-ALT.NET are paramount in order to achieve our goal of highly maintainable code.Unit tests empower developers with an unbelievable amount of confidence.The amount of refactoring and feature changes youre able/willing to make when you have safety net of hundreds or thousands of automated tests that validate you havent broken anything is unbelievable.Secondly,if you arent willing to adopt,or at least try,unit testing,youre wasting your time reading this.Much of what well cover is squarely aimed at improving the testability of our code.In This Chapter Even though this cha

此文档下载收益归作者所有

下载文档
你可能关注的文档
收起
展开