Debug like a pro! Memory Dumps with WinDbg
September 30, 2010 Category: Blog, Technical No Comments »
Recently I was working with a client to debug an issue that they could only reproduce in production (I hate those). Unfortunately, this was the sort of error that was sporadic and unpredictable – so hooking up a debugger and waiting wasn’t much of an option. Fortunately, Microsoft’s Debug Diagnostic Tool can be used to automatically grab an IIS Memory Dump during certain scenarios (like crashes and hangs). Normally, memory dumps aren’t the kind of things that .NET developers go digging in to. Well never fear my .NET developer friend, let Tess from the Microsoft debugging team show you the way!
This is a great presentation that Tess Ferrandez gave at 0reDev last year on Debugging .NET Applications with WinDbg. After you’ve watched her presentation be sure to check out the rest of her full blog, especially her post on using CMDTree then go read John Robbin’s post on Debugger Markup Language (DML).
Now you are well on your way to being the Memory Dump Ninja that I always knew you were!
Using RhinoMocks to Test Model View Presenter Events with Lambdas and VB / C#
July 4, 2010 Category: Blog, Technical No Comments »
![]()
This week I had the privilege of leading a custom workshop for a team of developers in Fort Worth, TX. One of the topics that we covered was Writing Testable Code; specifically, we looked at the Model-View-Presenter (MVP) patterns, dependency injection and using RhinoMocks to pull it all together. The one catch was… this group of developers used Visual Basic.
I’ve never shied away from VB. In fact, VB6 with classic ASP is where I cut my programming teeth, and VB.NET was my first move to a true OO language. That being said, I work day in and day out with C#… I’m much more fluent there, and I realized that there were a ton of new features in VB that I wanted to cover that I wasn’t up to par with, fortunately I was able to call on my network of super smart friends and recruit/hire a fellow MVP’er to help me out for the day (thanks Cory for doing that 2 days after your wedding!)
One of the things that tripped me up was using Lambdas in VB. Lambdas are especially important if you are going to use a Mocking framework like RhinoMocks (which I do). Doing Lambdas in VB – especially when I was trying to raise an event from a mock – sort of tripped me up…
First – if you are working with Rhino Mocks, you should go have a look at the excellent Wiki. http://ayende.com/Wiki/Rhino+Mocks+3.5.ashx I find that a lot of people (read: I had) skip the “documentation” since RhinoMocks is so fluent and straight forward, but it’s definitely worth the read!
Second, if you’ve never raised an event in mock from your test in C# here’s the code:
viewMock.Raise(x => x.CalcShippingRequest += null, this, EventArgs.Empty);
and in VB:
view.Raise(Sub(x)AddHandler x.CalcShippingRequest, Nothing, Me, EventArgs.Empty)
It’s the “AddHandler” part that kept tripping me up.. that’s basically += in C#.
Let’s put it all together…
Here’s the IView interface that the aspx page implements. (notice the VB 10 automatic properties)
Public Interface IView Property UnitPrice As Decimal Property ShippingDistance As Decimal Sub DisplayShippingPrice(ByVal price As Decimal) Event CalcShippingRequest As EventHandler End Interface
The Presenter (providing the UI Logic)
Public Class ShippingCalcPresenter Dim view As IView Public Sub New(ByVal view As IView) Me.view = view AddHandler view.CalcShippingRequest, AddressOf HandleCalc End Sub
Private Sub HandleCalc(ByVal Sender As Object, ByVal E As EventArgs) Me.view.DisplayShippingPrice(view.ShippingDistance + view.UnitPrice) End Sub End Class
The logic here is simple and contrived… we calculate the Shipping cost based on the Unit price and the Shipping distance (we just add the two… like I said, simple and contrived). Also notice that it’s the event from the view (CalcShippingRequest) that causes the presenter to go in to action, namely, it calls DiplayShippingProce on the view. This could have just as easily been a writable property, but I went with a method instead.
Here is the whole test (VB) AAA Syntax using RhinoMocks
<TestClass()> Public Class ShippingCalcPresenterTest <TestMethod()> Public Sub ShippingCalcPresenterConstructorTest() '*** Assign *** 'view as a Mock object Dim view As IView =
MockRepository.GenerateMock(Of IView)() 'set View values (user input) view.Expect(Function(x) x.ShippingDistance)
.[Return](8).Repeat.Once() view.Expect(Function(x) x.UnitPrice)
.[Return](2).Repeat.Once() 'Expect Shipping price of 10 to get set in view ' -- Presenter Logic: Price = Distance + Price view.Expect(Sub(x) x.DisplayShippingPrice(10)).Repeat.Once() ' Inject view Mock in to Presenter Dim target As New ShippingCalcPresenter(view) '*** Action *** ' Raise event in view... normally this would be a
‘ user clicking on a button view.Raise(Sub(x) AddHandler x.CalcShippingRequest,
Nothing, Me, EventArgs.Empty) '*** Asserttions *** view.VerifyAllExpectations() End Sub End Class
and again, in C#
[TestClass()] public class ShippingCalcPresenterTest { [TestMethod()] public void ShippingCalcPresenterConstructorTest() { // *** Assign *** // view as a Mock object IView view =
MockRepository.GenerateMock<IView>(); // set view values - user input view.Expect(x => x.ShippingDistance).Return(8).Repeat.Once(); view.Expect(x => x.UnitPrice).Return(2).Repeat.Once(); // Expected Shipping price of 10 to get set in view // -- Presenter Logic: Price = Distance Price view.Expect(x => x.DisplayShippingPrice(10)).Repeat.Once(); // Inject view mock in to Presenter ShippingCalcPresenter target = new ShippingCalcPresenter(view); // *** Action *** // Raise event in view - normaly this would be a user // clicking on a button view.Raise(x => x.CalcShippingRequest += null,
this, EventArgs.Empty); // *** Assertion *** view.VerifyAllExpectations(); } }
First we set up the expectations from the view mock (Assign), then we stuff the view mock in to the presenter (system under test) and then we fire off the event (Act) in the view – this would normally come from a user clicking on something, but in our case, we are simulating the action with a mock. Then we use RhinoMocks VerifyAllExpectations() method to make all of the Assertions that we expected earlier. And there you have it!
Serve hot and enjoy! Happing coding (and testing)!
Editor’s Note:
This article is cross posted from Caleb’s personal blog – enjoy!
Photo Credit: Thomas Hawk ![]()
Bing 404 Plugin for WordPress
June 5, 2010 Category: Blog, Technical 2 Comments »
Yesterday Microsoft released a new plug-in for WordPress that uses Bing Search to improve your 404 pages. It works by grabbing keywords from the missing URL string and then uses the Bing API to search your site for those keywords.
Update: The creator of this plug-in just added a quick start video… go check it out!
So, your 404 page can go from this…
(boring WordPress Default 404)
To this…
and, with a little bit of PHP hacking on my part, to this…
(new and improved pimped out 404 page…)
Go see for your self (missing page) then go check out…
iPad + Velcro = good
June 4, 2010 Category: Blog, Thoughts 1 Comment »
I may not own an iPad… but thanks for Giovanni’s “help“, my wife now wants one, and I have to admit, after playing Plants vs Zombies on both an iPad and a PC.. the iPad touch is a much better PvZ experience. This video show some of the other things that you *could* to with an iPad… plus velcro. Enjoy!
iPad + Velcro from Jesse Rosten on Vimeo.
Practice Software Patterns – Component Patterns
March 10, 2010 Category: Blog, Technical 2 Comments »
This post is the 6th in a series that started with the 10 practices that every developer needs to start right now
The first time that someone taught me about Software Design Patterns it went something like this:
- Them: “… and so that is the pattern.”
- Me: “That’s it”
- Them: “Well, yeah.”
- Me: “But that’s how I’ve always done that.”
- Them: “Well, then you’ve always been following that pattern”
I find that is how a lot of people react when they first learn about patterns. “So a pattern is just giving a name to good software development” Well, yes and no. On the one hand – yes, a software pattern is recognizing common software challenges and the approaches that have worked in the past to over come those challenges – and naming it. On the other hand, don’t underestimate the power of giving something a name.
Vocabulary
There is power in a common vocabulary. Think about it, every profession has one. From the dentist that cleans your teeth to the short order cook at Denny’s; from the mechanic that works on your car to the contractor that built your house. Every profession has it’s own vocabulary that gives people a fast and efficient way to communicate.
So that instead of taking time to walk through all of the details of your architecture and application design, you can have a conversation that goes something like this “We’re writing a facade layer here, and utilizing a DI container to act as our Abstract Factory, accessing our persistence layer with a repository pattern utilizing Interception for logging and MVVM to composite all of our UI.”
OK, so I know that there were a lot of buzz words thrown in there, but I hope you’re getting the point – a lot can be communicated in a couple of sentences.
Patterns
Let’s face it – there is more to learn than any of us has time for. Patterns are like that. There’s a pattern for everything – like a bad Apple commercial, there’s a pattern for that. The important part is not learning every pattern under the sun – but learning the common patterns for the common challenges is where you’ll get the most bang for your buck.
Component Patterns
Strategy | Factory | Abstract Factory – all related.
Factory. The goal of a factory pattern is to conceal the creation of an object from the consumers of the object. This is especially important for complex objects that take a lot of dependencies or configurations when you create them. Instead of repeating the set up code through out your application you move it to one place (the factory) and then call that from your code.
take this (slightly contrived) code example…
SqlCommand cmd = new SqlCommand();
SqlParameter parm1 = new SqlParameter();
parm1.Direction = ParameterDirection.Input;
parm1.ParameterName = &amp;amp;amp;quot;Id&amp;amp;amp;quot;;
parm1.Value = 5;
cmd.Parameters.Add(parm1);
SqlParameter parm2 = new SqlParameter();
parm2.Direction = ParameterDirection.Input;
parm2.ParameterName = &amp;amp;amp;quot;State&amp;amp;amp;quot;;
parm2.Value = &amp;amp;amp;quot;TX&amp;amp;amp;quot;;
cmd.Parameters.Add(parm2);
// etc...
It would be much nicer to implement a reusable method as so…
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add(getInParm(&amp;amp;amp;quot;Id&amp;amp;amp;quot;, 5));
cmd.Parameters.Add(getInParm(&amp;amp;amp;quot;State&amp;amp;amp;quot;, &amp;amp;amp;quot;TX&amp;amp;amp;quot;));
// etc...
}
SqlParameter getInParm(string name, object value)
{
SqlParameter parm = new SqlParameter();
parm.Direction = ParameterDirection.Input;
parm.ParameterName = name;
parm.Value = value;
return parm;
}
This probably seems like an obvious and simple example (because it is), but the point is that not all patterns are ground breaking or earth shattering, just simple approaches to make your code more usable, maintainable and testable.
Abstract Factory. If you set up your factory to return an Interface instead of a concrete class then it is an abstract factory. This is especially useful when you want to return different implementations in different scenarios. For example, you might have an IDataLayer and in some cases you want to return a fake version for testing, or perhaps you need a local storage version for offline scenarios etc.. moving the creation of your data layer, it’s configuration and set up to a factory would make a lot of sense. By the way, this is also a text book definition of Object Oriented Polymorphism – the same interface with different behaviors with various implementations. And that brings us to the Strategy Pattern.
Take our example above, if we were to move that bit of code in to a shared data access helper class, we might want to consider a more generic approach.
IDbDataParameter getInParm(string name, object value)
Strategy Pattern. The original goal of the strategy pattern was the grouping various algorithms in to common interfaces. So, for example, working with DES, Triple DES or Blowfish encryption shouldn’t be any different than driving a V8 is different from driving a 4 cylinder car – what’s under the hood (the implementation) doesn’t matter as long as you know hot to use the steering wheel and pedals (Interface). No code examples here. Go take a look at encryption in .NET, or the common approaches that ADO uses for data access. Also, hang on, we’ll go in deeper to code examples in just a bit when we talk about composition over inheritance (which is closely related to Strategy Pattern)
Up next: UI Patterns for Testability, Maintainability and Extensibility!
(Followed by Composition over Inheritance)
Images Credit: http://www.flickr.com/photos/webtreatsetc/4229661317/sizes/o/
Thinking about games…
February 25, 2010 Category: Blog, Thoughts 1 Comment »
Stephen was the first person that really got me to think about game theory as it relates to general application design. Then my friends at Improving Enterprises introduced me to Luke Hohmann and his Innovation Games approach to product management and games like “buy a feature”. I’m certain that their is much more work that needs to be done in this field. Think about it. Game theory flips “traditional” usability on it heels. Every application that I’ve ever worked on “easy to use” was one of the requirements. In games, “too easy” is a negative. Challenging, engaging, rewarding and FUN are the goals the rule the day. This talk by Jesse Schell really drove this point home for me.
Carnegie Mellon University Professor, Jesse Schell, dives into a world of game development which will emerge from the popular “Facebook Games” era.
- Enjoy!
Secure Coding 101
February 10, 2010 Category: Blog, Technical 3 Comments »
This post is the 5th in a series that started with the 10 practices that every developer needs to start right now
When writing software, we often don’t think about the security implications of our actions. Probably because we write software to do something, we’re not always aware of what it shouldn’t do. Their are a lot of guidelines for writing secure code, and designing secure systems. Rather than going in to all of the areas, let me just hit on some of the especially important topics that I’ve come across…
In addition to this post, I’ve included a slide deck that I use when I give talks about writing secure code. A lot of the original slides I got from a talk that Ron Jacobs did at TechEd. I hope you enjoy both!
Buffer Overflows and Overruns
OK… so I’m mostly going to deal with issues that affect .NET developers. .NET prevents Buffer overflows by not giving your code direct access to memory addresses and instead by managing memory access for you and by making sure that everything is type safe.
Here’s my non-technical version of what a Buffer Overflow is. First, a Buffer overflow is something that affects unmanaged code (or unsafe C#). Let’s say that a memory address is designed to hold 9 bits of user input, and instead the user forces 10 bits a information in to it. Normally, the last bit of memory is a return address and tells the code where to go next. In a Buffer overflow attack, a different return address is forced in to that last slot so that the attack can control the flow of the code.
For example, the code might say something like, “If the user is not authorized return to login” and instead the attack forces a return code so that it ends up doing something like this “If the user is not authorized go to the bank account withdrawal screen”. By simply changing the flow of an application, and attacker can do really bad things.
Fixes:
- Use .NET (and get out of that unmanaged C++ code
) - Use safe libraries. Many of the C++ common libraries have been re-written to help prevent Buffer Overflow exposure. Make sure that you are using the updated libraries.
- Check out the “Banned.h” header file from Microsoft. It’s is a sanitizing resource which supports the SDL requirement to remove banned functions from a code. It lists all banned APIs Download.
- Use the /GS Compiler switch. This was introduced by Microsoft to automatically add safety checking to your code when it compiles.
XSS
XSS is an abbreviation for Cross Site Scripting attack. (I know, but CSS was already taken
) XSS attacks are something that has affected every major web site at one time or another.
Background: When you connect to a website, like amazon or ebay (or any other site that you log in to) it often uses a session cookie to know who you are, and what you are allowed to see (your account info for example). Cookies are not a problem in and of them selves, in fact, your browser makes sure that it only send cookies to the web site that it was issued from. See – your browser trusts the site that you are on.
What is it: In a XSS attack, a malicious user figures out how to load their JavaScript to a trusted site. So that when your browser sends them your cookie, the malicious JavaScript has access to your cookie and forwards it on to the attacker. Then the attacker can impersonate you and access your information.
How it works: Have you ever searched for a random product on a site, like foo, and received a response message that said something like “your search for foo was not found.”? Try searching for “<b>foo</b>”. What happened? If the message looks like this: “your search for foo was now found.”, then they are probably not sufficiently checking the user input. Now image searching for this:
If you get a pop up that say’s “oh noes!” then this site is definitely vulnerable. You see, as far as your browser is concerned, this JavaScript is coming from the server that is generating the result page. Now imagine sending someone an email with a link to go check out this great deal on a new bike http://newbikesforSale.com!
The link above looks legitimate, but it’s actually a link that contains JavaScript to open an simple alert box. You can trust it (it won’t hurt you I promise), but in a XSS attack an attacker uses HTML mixed with JavaScript to embed their JS code in an email link, or more likely on a comment thread, in a blog review, or any place that will let it in.
Fix: All user input is considered evil until proven otherwise. The problem is that we haven’t traditionally considered search forms and product reviews as user input in to our systems, but they are. You can scrub user input easily enough by doing something like string SafeToDisplay = Server.HTMLEncode(userInput); but really you should look at incorporating some of the libraries that are specifically designed to handle these scena rios. Check out Microsoft’s Anti-Cross Site Scripting Library, it’s very comprehensive and covers many more scenarios.
SQL Injection
All user input should be considered evil until proven otherwise. This has never been more true than it is with SQL Injection vulnerabilities.
How it works: Imagine that you have an application with a log in: User name and password.
Pretty simple so for huh? Now think about the SQL that you would write to validate a user… It *might* start off looking something like this:
So far so good… as long as everyone enters a user name and password in to the correct textbox on the screen this should validate them perfectly…
but what happens when you enter something unexpected in to one of the boxes..![]()
the problem here is that the text from the form is now being executed as part of the SQL statement itself. SQL injection just allowed this person to operate this application with the username BillG… I’m sure that wouldn’t be a problem!
Not just Log In Screens. Any place that user input is translated in to a query to the database is open to attack. Search fields are a notoriously overlooked place for SQL Injections, and not just for logging, at this point the attack can do anything that the application can do. Even worse, many application run as SA (Sql Administrator) just to make “life easy” on the developer. That opens up a whole new problem. Imagine a random user being able to log in to your system, add themselves as an administrator, shut down your server, rewrite your website, reformat your hard rive all from a search box. See the problem?
Fix: the fix is easy, don’t let user input run as SQL. You can prevent SQL Injection by moving away from concatenated string for building sql queries. if you need the flexibility of ad-hoc sql, then write your adhoc sql using parameterized SQL. Otherwise you can move to stored procedures or an ORM like Linq to SQL, Microsoft’s Entity Framework, or nHibernate that will automatically use parameterized sql for you.
White List vs Black List Principle
One thing that I want to call out at this point. It is very tempting to try and “sanitized” every user input instead of moving to one of the more robust solutions mentioned above. I had a friend (a very good developer) that was sanitizing all user input for “bad” words before he would process it. In his words, “we don’t have any products called drop, delete, execute… so I should be able to do a string.Replace on those words and then be fine.
Here’s the problem with that. In Security there is a concept of White List vs Black Lists. A white list approach says, here is what I will allow, and throw away anything else. A Black list take the approach that says, “here is what I won’t allow, I’ll let in anything else that’s not on this list.” The problem with the black list approach is that security is a moving target, there are vulnerabilities today that we didn’t know about yesterday, there will be more tomorrow that I don’t know about today. Just because something isn’t on my “bad” list today, doesn’t mean that it shouldn’t be.
I went to my friends bad word scrubber and entered this : ‘deldeleteete” do you see the word delete in there? What will happen after your scrubber removes it… you’ll be left with “delete”. He started using parameterized SQL.
Encryption
I once interviewed a really smart computer science guy that wanted to come work for our consulting company (primarily focus on business applications). Saying this guy was smart is an understatement. He was a Computer Science PhD candidate with cross disciplines in artificial intelligence and game theory. wow! The problem was that he had very little knowledge or experience writing actual applications. When I asked him about if we should write out own encryption for some application that we were working on, he got all excited and started to go in the details about what it would take to implement out own encryption. I’m pretty sure he had taken a class on this, wrote some thesis on it or something because he was really excited that I had asked him about this topic. Here the thing, never write your own encryption.
Getting encryption done right is hard.. like really hard. In fact, if you are good at it, maybe you should go work for the government, or a university, or RSA directly, but you have no business trying to do that for a business application. Use the tried and true, multiple encryption, publically available libraries to do it right.
3-Types of encryption.
Private Private Key, also known as a symmetrical encryption uses the same key to encrypt and unencrypt. Symmetrical encryption is very fast, so it’s great for encryption transmissions and it used for things like secure communication and SSL. the problem is that it’s less secure because you have to have a secure way to hand out the private key.
Public Private Key, also known as asymmetrical encryption uses two different keys. One key (the public key)
is used for encryption, the private key is used for decryption. The benefit here, is that you can yell out for the world to here your public key, but only the person with the private key can do the decrypting. The problem is that it’s very slow and computationally expensive.
So how can two computers talk securely to each other in an open environment like the Internet? The answer is a combination of the above. SSL, or secure socket layer uses a public key to securely transmit a “session” key that will be used for symmetrical encryption for the rest of the communication.
1-Way Hashes cannot be encrypted. How is that helpful? It’s very helpful. A hash can me used to make sure that two values are equal without actually knowing what the values are. For example, my application should never store plain text passwords. If they did it might be possible for those passwords to become compromised. By storing a 1-way hash instead the password cannot be retrieved even if the database (or a backup of the database) is compromised. How do I log user in to the system then? Simple, I take the password they give me, I has it using the same method and compare the two results.
Digital Certificates – Digital Certificate use a combination of the above concepts to support secure communication and identification. We’re just not going to go in to all of that now.
Least Privilege Principle
Reduce your Attack Surface – if you don’t need a service, turn it off. If your application doesn’t need permission to do something, don’t supply it. By limiting the scope of what can be done, you also limit what can be broken if and when things go bad.
Default to Fail – Here’s an example.
What’s wrong with this code? (ok, a lot
) But what we want to focus on is that if there is an exception along the way, it will default to the user being authenticated. The [valid] should have been set to false, until proven otherwise.
Don’t reveal more than is helpful to the user. Be helpful, but you don’t have to thrown up every SQL exception on your users.. log that stuff, let the debug team look at it, but knowing what version of SQL server you’re running or what the stack address is completely useless to your users… but bad people love that stuff.
I love this screen shot. Is that error helpful to you? It says “Error 0x80090022” but it means “No smart card inserted in reader.
Don’t give away your system internals, at the same time make sure that your user errors are helpful!
More resources…
OK.. as you can imagine there’s a lot more that we could cover, but instead take a look at some of these resources.
Threat Modeling Tool – Threat modeling is all about identifying assets, vulnerabilities, resolutions, evaluating a business value on assets, then balance the cost of a resolution with real business value.
SDL Process Template for Team System – SDL is the Security Development Lifecycle, it’s a set of practices and tools that help integrate secure development in to all aspects of SDLC (Software Development Life Cycle). This is Microsoft’s template to integrate SDL with Team Foundation Server (Microsoft’s Application Lifecycle Management Server).
SDL Process Tools – There’s a ton here, check it out.
MSDN Security – Read the blogs, latest news, and downloads regarding Microsoft security and development.
Happy Coding (securely)!
Images Credit: http://www.flickr.com/photos/carbonnyc/2294144289/
We don’t give 5’s… and other antiquated management techniques.
February 9, 2010 Category: Blog, Thoughts 3 Comments »
I was talking to a friend of mine last month that had just had mid-year reviews at his company. I received his permission to relay some of our conversation and my response to him here.
“So I walk in to sit with my manager for my mid-year review… we’re ranked on 12 different categories on a scale of 1 to 5, there are 9 of us that report to him”
Sounds normal, makes sense.
“First thing my manager says in going over my review is, just so you know, and I’ve told everyone this: I don’t give 5’s”
Wait what?! Um, if that’s the case then why not just have a scale that goes from 1 to 4? Let’s think about that for a minute. No really, let that sink in. Why call it 1 to 5, if it’s really 1 to 4?
A 5 does not mean perfect, only one person in history was ever perfect. Nor does a 5 mean that’s there’s no room for improvement, there is always some room for improvement.
A 5 (or whatever your top score is) means that the person that you are reviewing is awesome in that category. That they completely exceed your expectations on that metric, nothing more.
Also, rank is relative.
A 5 for a “fresh out of school” with a fresh out of school paycheck … might be the equivalent performance of a 3 for a more seasoned developer – because more is expected from the seasoned person.
“He went on to say that his boss… the senior VP of our group, told him that he automatically bumps 5’s down to 4’s anyways.”
Oh, so it’s a systemic problem with the culture of your company, not just one manager… good to know. One more thing on that, I would push back, because at least if your manager went to his boss and said, this person is excellent at this, then, even if the VP bumped it down to a 4, he still heard the praise from your boss first.
Here’s my thought, if you are a manager, and there’s not one person on your team that is awesome in any of those 12 categories, then you hired the wrong people.
That’s worth repeating…
If there’s not one person on your team that is awesome in at least one of those areas, then you hired the wrong people and it’s your fault.
Here’s a tip
if you want people to perform at their best, recognize what they are doing right, reward them for it, and they’ll want to do more of those things plus they’ll want to figure out how to excel in more areas. Nothing takes the wind out of your teams’ sails like effectively telling them, “no matter how hard you try, or how much work you put in, you’ll never be excellent, because I don’t give 5’s” Talk about demotivating!
I let my friend know that culture change at a company is not easy.. but it is a worth wile endeavor and can have huge payoffs.
Finally, I will leave you with this little gem that was posted on SlideShare
it’s worth the read.
Enjoy!
SOLID: Software that works.
February 9, 2010 Category: Blog, Technical 5 Comments »
This post is a part of a series that I started with "10 Practices that Every Developer Needs to Start Right Now".
Update: This post was picked up by DZone, go vote it up!
Ok, before you dig in to the post, let’s get two things out of the way first. 1.Go read the authority on SOLID principles from the man himself, Uncle Bob Martin. 2nd.Go get the very cool Inspirational SOLID images from the guys over at Los Techies. They released them under a Creative Commons License which I think is pretty cool! Alright, got that out of the way? Good. Let’s get started.
Few things have come a long OO history that resonate so well with so many developers than the SOLID principle. One of the reasons they resonate with so many developers is because they communicate several practices that many developers have been doing all along. The beauty and power of the SOLID principals in in there ability to communicate, what I call code architecture, in such a memorable and practical way.
Like any good thing, however, taken to an extreme can become a hindrance on any project. So, I’m going to tackle these principals like I tackle everything in this series… give you my take on it. So here you go: SOLID according to Caleb.
[SOLID Motivational Posters, by Derick Bailey, is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License. Get them here.]
S – Single Responsibility Principal #
"There should never be more than one reason for a class to change." — Robert Martin, SRP paper linked from The Principles of OOD
Abuse: I’ve seen this taken to an extreme. I’ve seen good clean readable code turned in to multiple classes (even multiple projects) to break up “responsibility”. The end result was much harder to maintain and even harder to read.
Applied: “One reason to change” does not mean that every class has one and only one thing (that would be called a method), it does mean that you should focus on the area (or areas) of responsibility that a class should have and then stick with those boundaries. Code bloat (overly large classes with overly large methods) is a real code smell that you need to watch out for. The more things that a class is responsible for, the more likely you’ll have to change it and the harder it will be to test.
Your code should be broken in to manageable pieces, reduce any unnecessary couplings… Practice writing Libraries not Frameworks.
O – Open Closed Principle #
"Software entities should be open for extension, but closed for modification." — Robert Martin paraphrasing Bertrand Meyer, OCP paper linked from The Principles of OOD
Abuses – I’ve worked on code bases that were so extensible, so configurable, so full of AOP indirection and configuration that following the flow of what they were actually doing was almost impossible.
Applied – Code is going to change, that’s a part of life. The Open Closed Principal is more about reducing how often you have to change your code and in how many places. In other words: Code to Interfaces and maintain your abstraction boundaries.
I recently worked with a Linq to SQL project where the Data Context object was being passed around through out all of the layers in the application. That meant that most of the application was impossible to unit test and if I were to change a column or table in the database I would have to go through the entire code base and find all of the places that broke. We fixed that by creating a specific data interface that all interactions had to go through, only passing domain objects (DTO Models). We kept the DB Context in the Data Layer implementation where it was super useful, but no longer forced us to recompile the entire source for simple data changes. I like how approach that Jeffery Palermo described and an Onion Architecture.
I also worked on another project where 8 layers of abstract classes were used to distinguish between three different types of physical devices… any change in the application behavior had to be propagated across all of the implementations. We fixed that by concealing the device differences behind a single command interface that was then injected in to the application “behaviors” via an abstract factory.
What did you just say?
So in other words… imagine having three different devices (blue, red, green) that all needed to be turned on (behavior), but the command to turn on each was different and defined by the manufacture… the code *might* look like this:
Now imagine that there were multiple points within your application where you were working with the devices… now, every time you need to support a new device you end up with this if/else statement being redone just about everywhere…
By externalizing the device differences behind a factory and encapsulating them in an Interface you now only have one place to change to add a new device. You could reduce that further using an extension manager like Microsoft MEF, but we won’t go in to that right now.
L – Liskov Substitution Principle #
"Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it." — Robert Martin, LSP paper linked from The Principles of OOD
Abuses: I like to think of this principle as “Use Interfaces”. I haven’t really seen abuses of this practice, but I have seen some bad implementations. The rough ones, are where developers rely on a base abstract class instead of an Interface also. The doesn’t sound like a problem until you start putting parameters in the constructor of the base class. Now any derived classed have to enforce those same dependencies even if you are creating an entirely different implementation.
Applied: Use Interfaces. If you find that a base class would meet some of your needs more closely, that’s fine, just make sure that you back that base class up with an Interface, and then code to the Interface.. you’ll thank me later.
Side Note: Their are different schools of thought around backing domain models with Interfaces. I do, the main reason is that even if I end up using an ORM (like Entity Framework, or LinqToSQL) that “forces*” me to a specific domain model implementation, I can save myself a lot of headache later and make my models more mobile if I connect those domain models to an Interface.
* – no toolkit should force your architecture or design, any implementation can be abstracted around, Domain Model Interfaces help move your DTO’s through layers of your application without carrying heavy dependencies with you.
I – Interface Segregation Principle #
"Clients should not be forced to depend upon interfaces that they do not use." — Robert Martin, ISP paper linked from The Principles of OOD
Let’s say you have a service class for working with Invoices, your IManageInvoices interface exposes three methods, Add(IInvoice), Delete(IInvoice) and Update(IInvoice). Because of deployment and security concerns you are going to create two different classes to implement this.
One, InvoiceCreator will implement the Add method and run in untrusted environments. The other class, InvoiceUpdater, will implement the other two methods and will only run in secure, verified and authenticated context. So what should each class do with the other methods?
Violated: One “option” would be to implement them, but then throw a “Not-Implemented Exception” or set up Void methods that don’t actually do anything, both of those options are ugly and bad choices.
Applied: The better option is to split your Interface, create a ICreateInvoices Interface with the Add method, and a IUpdateInvoices interface with the other methods. That way, you are actually implementing the methods of your interface, and are not hiding are making implementation decisions that break your abstraction and require special knowledge of the class.
D – Dependency Inversion Principle #
"(A) High level modules should not depend upon low level modules. Both should depend upon abstractions. (B) Abstractions should not depend upon details. Details should depend upon abstractions." — Robert Martin, DIP paper linked from The Principles of OOD
All code has dependencies, the question is how to you resolve those dependencies.
Example: my class will access a service, I could write it like this:
or like this:
Can you spot the difference? It’s subtle, yet very very powerful. In the first instance, you are using an Interface to define your Shipping Service (and that’s a good thing!), but then you are forcing your class to be dependent on the UPS shipping service… I don’t have anything again UPS, but I do know that company contracts are constantly changing, and just because we were using UPS when we designed and had the customer (business owner) sign off on the application, doesn’t mean that that’s who we are going to use when we go to production!
You might be tempted just to replace the “new UPS” instantiation with an Abstract Shipping Factory ( shipService = factory.getShippingService() )… that wouldn’t necessarily be a bad idea, except now you’ve shifted your code from a UPS dependency to a factory dependency.
Notice in the second option, we hand our class the imple mentation that we want to use through the constructor. That’s called constructor injection, we could have also used a property or method to set the shipping service. I like constructor injectors for anything that my class requires to operate. This allows us to define our IShipping service implementation completely independent of the class that’s consuming it.
This also makes are code much easier to test by allowing us to creating a mock (fake) version of our IShipping service for testing the main class. We might even use something like RhinoMocks to help our automated unit tests even more, but we’ll save that discussion for another time.
No Framework Required
You may have noticed that this dependency injection is not dependent on any special tooling or frameworks (so we’re not introducing new dependencies just to get rid of another!)
Dependency Injection or DI, is really a style of coding that makes your code more composable, testable and maintainable. DI Frameworks (or Containers) are specifically designed to be used in two stages.
Register, then Resolve
First, you register your Interface to Class mappings, then you can reference the container anytime and resolve an Interface to a concrete class. Containers can also provide other nice benefits like controlling the life cycle of an object (singelton, vs per thread, vs per request for example). Some DI frameworks also provide the ability register special handlers (or Interceptors) that get invoked whenever a method or a property is called. This in a concept known as AOP or Aspect Oriented Programming that is useful for cross-cutting concerns like automatic logging and security checks.
For more information on Dependency Injection and Inversion of control I suggest checking out my DI in Silverlight slide deck, as well as the Ninject, Castle, Microsoft Unity and Structure Map projects.
Enjoy!
Learning to Write (Software)
January 25, 2010 Category: Blog, Technical 4 Comments »
I received a message on Facebook last week from a friend of mine that asked this question:
I have recently decided that I would love to go to school to learn programming. I just wanted to know if you had any advice or suggestions that could help me out (I know it's a very open ended question)? Also I wanted to know if you had any suggestions on books to read regarding Design Patterns (particularly related to web development).
Great question. Let’s tackle those starting with the second part…
any suggestions on books to read regarding Design Patterns
(particularly related to web development).
Seriously, you can’t go wrong with the Head First Series.
I know that the covers are a little hard to take seriously, but I what I really like about these books is that they are designed for learnability.
They are not designed to be reference books or course curriculum. This is the same reason that I liked learning from WebMonkey (back in the day… when they had current and relevant articles)
OK, now for the first part of the question.
I would love to go to school to learn programming. I just wanted to know if you had any advice or suggestions that could help me out
Here’s the thing. I don’t think that I learned any of the really good practices that I use today in school. I find that most CS programs are geared for people that want their PhD in CS… or want to work for Intel developing the next CPU chip or want to right super fast machine code for networking drivers and pace makers. These are all good, but most of them miss the point and the sort of Software Engineering that is required for solid, maintainable, reliable business applications (98+ % of the consulting that I do)
I don’t know of a single school that teaches, TDD/BDD, CI, DI/IoC, SOLID… I DO think that you can learn the fundamentals of programming (syntax) and even some of the good OO principals (but even that usually goes overboard with too much theory and not enough tangible reality).
So it really depends on your goals.
If you want to work towards your PhD – go to a university and get your B.S.
If you want to develop web (UI) – I would look at the the offerings at most community colleges. I find that community colleges are often more agile to the market place with certification programs and other offerings than many Universities.
If you want to learn the really good practices for maintainable, testable software…
go listen to this HanselMinutes episode, find as many sources of quality content that you can latch on to and absorb them… plus. I’d go subscribe to the blog series that I’m writing on development practices.
What advice am I missing?
Take a second to answer this quick poll on where you learned to write software. I’ll post the answers when the poll closes on Feb 20th – last day of the upcoming Microsoft MVP Summit
Happy Coding!














