Tuesday, March 2, 2010
Quick introduction to SOLID
Thursday, February 4, 2010
Back to basics: Why should I use interfaces?
Me: What is this code with data access on the "OnClick" of your button? Him: Well it's the information I need to execute this command. Me: Do you know the Model-View-Presenter pattern? Because right now, you are mixing "Presentation", "Data Access" and "Business Logic" Him: I've used it before but it's been a while. How do you implement it?So after showing him the pattern and explaining the basic implementation (because there is a lot of different way to implement this pattern), he asked me the following question:
"Of course, you don't need to use interface everywhere, right?"But then I went on to explain testability and such but there is something different I wanted to bring to this small discussion and that I wanted to share a bit. When my class have dependencies injected through the constructor, I have 2 choices. Either I depend upon the implementation or the abstraction (interface/abstract). What's the difference and why is it so important?
MyClass depending upon the abstraction of "MyClassDataAccess"
When your class depend upon the abstraction, it can take any class that implement that abstraction (be it abstract class or interface). The implementation can easily be replaced by something else and that is essential in unit testing your logic.MyClass depending upon the implementation of "MyClassDataAccess"
When your class depend upon the implementation directly, the only that can be sent to this class is this specific implementation. Anything else must derive from this class. This implementation couple the Caller and the Callee really tightly.Why is it important ?
When you have a class that access services, slow resource (database, disk, etc.) or even a class that you haven't coded yet... an interface should be used. Of course it's not a law. You apply interface/abstract class when you need to decouple an implementation of a system from another system. That allows me to send mocked object and test my requirements/logic. This also bring another advantage that might not be evident at first. Customer changing his mind. When the customer change his mind and do not want to store information in an XML but instead want a database. Or when a customer say to not implement "this part of the system" because it will be available through a service. Etc Etc... Using interfaces and abstract class is the oil that makes the engine of your software turn smoothly and allow you to replace parts by better/different parts without hell breaking loose because of tightly coupled implementation.Sunday, June 28, 2009
The cost of Bad Code
Every developer writes code. Every developer works or has worked on a Brownfield project. Working on a Brownfield project often makes developer complain about the code being poorly written and hard to maintain. That surely sounds familiar, right?
This is basically a pledge to good code. Bad code makes things worse and cost business money.
How much are we talking about?
There is no scientific study about this. Primarily because most projects are private and won’t allow studies and there is still no clear metric that represent clean code. Mostly, metrics can’t represent bad code. So how much money can be saved? Well… bad code hinder maintenance, comprehension and scare programmers of changing a class that was working well before. I don’t think we can calculate now, but I think that Cyclomatic Complexity, LOC per functions and Code Coverage represent a big indicator of code that are hard to understand and difficult to make changes.
Code that have high cyclomatic complexity and huge LOC per functions scares programmers into making changes. Why? Because we all know that if we change something inside one of those method, the ripples of change will make something else break. This fear can be neutralized by high code coverage of those big methods and/or by splitting them up.
Time for totally unscientific numbers. I think that complex code will require more double the time to make modifications to. Why? Well… let’s say that the developer will have to spend a considerate amount of times in the debugger instead of running tests. Tests for a (big) module should take less than 10-15 seconds to run (including the test runner initialization). Debugging the same module to verify a behaviour will take normally a minute or two. Rinse and repeat at least a dozen times and you find yourself at 1 minutes for running the tests and 12 minutes for debugging an application. This is just the beginning. If there is no tests, a huge and complex method will take literally take at least 10 minutes to understand (depend of context). A test “infected” code base will allow for quick failure verification without having to spend hours in the debugger. Calculate as much as you want but… as Robert C. Martin said:
The only way to go fast is to go well.
So are you saving time in your company or are you costing your company money? I think we can all earn something from writing clean code. Companies will save on maintenance cost, programmer will improve their craft and become better programmer that are proud of what they do.
Monday, June 22, 2009
Improving code quality – 2 ways to go
I’ve been thinking about this for at least a week or two. In fact, it’s been since I started (and finished) reading the book “Clean Code” by Robert C. Martin. There is probably only two way to go.
Fix the bad code
This method is called refactoring and “cleaning” the code. This of course, you can’t truly know what code is bad without having a Static Analyser tool or programmers working on the code. The tool will allow you to spot piece of code that could bring bugs and/or be hard to work with. The problem, refactoring code or cleaning up code is really expensive on a business perspective. The trick is to fix it as you interact with the code. It is probably impossible to request time from your company to fix code that could cause bugs. If you ask your company to fix the code, you will probably receive this answer: “Why did you write it badly in the first place?”. Which brings us to the other way to improve the code quality.
Don’t write it
If you don’t write the bad code in the first place, you won’t have to fix it! That sounds simple to an experienced programmer that improved his craft with years but rookies will definitely leave bad code behind. Eventually, you will have to encounter this bad code. So how do you avoid the big refactoring of mistakes (not just rookies)? I believe that training might be a way to go. When I only had 1 year of experience in software development, I was writing WAY too many bad code. I still do. Not that I don’t see it go through. Sometimes, things must be rushed, I don’t understand fully the problem and some small abstraction mistakes gets in. I write way less bad code then when I started. However, this bad code is not just magically disappearing. It’s stays there.
What about training?
I think that training and/or mentoring might be the way to go. Mentoring might be hard to sell but training is definitely not that hard to sell. Most employees got an amount of money related to their name within a company that represent training expenses that can be spent on them. What I particularly recommend is some courses in Object-Oriented design or Advanced Object-Oriented Design. Hell, you might even consider an xDD course (and by xDD… I mean TDD, BDD, DDD, RDD, etc.). Any of those courses will improve your skill and bring you closer to identifying clean code from bad code. Other training that will form you specific framework (like ASP.NET MVC or Entity Framework) will only show you how to get things done with those framework. The latter can be learned on your own or through a good book.
So? What do you all thinks? Do you rather have a framework course or a “Clean Code” course?
Wednesday, February 25, 2009
We all produce code that we really aren’t proud of
Everyone produce code. Some peoples give birth to some beautiful, elegant and maintainable code sometime in their career. But pretty much all developers will one day or another give code that is so horrible, inelegant and un-maintainable.
I’m trying as much as possible to separate concerns inside my application so that I don’t have to care about problematic maintenance. I’ve recently had to review some code I did more than a month ago and… I’m not proud. I’m really not proud of the code I saw. It seems that every once in a while we write some code that we won’t be proud of.
Of course, we improve our coding skills every day and every time we encounter new technology and new idea. Hell, I like the SOLID principles and the TDD ideas. I love the concept of separation of concerns and modularization of an application. So how come I wrote this code?
I can’t remember exactly why honestly. Maybe I was rushed or I wanted to rush through it. How knows… what is important however is to know that the code that you wrote taste like a cheap wine. It’s important to take a note of it and make sure to “maintain your code garden”. This is at the moment that the title of my blog actually makes sense. Even with the best intention, code quality decay and if nothing is done, you finish with a half rotten application that nobody will care about.
So what to do about it? Make sure to improve the quality of existing code everyday. If we write bad code 10% of the time (number that I just picked from the top of my head) and good code 90% of the time, imagine if we take only a few hours per week to correct mistakes.
You probably won’t have the time to fix it. Who does? But there will be a day where you will finish an hour early and that you will wonder if you should start implementing a new feature or go home early. If you took note of those classes that need improvements, you could easily take this hour to maintain your code garden and be proud of the code that you did.
So, the first “time off” that I have will be used to fix this part of code that I’m not proud of.
Anyone else who wrote some shameful code?
Monday, February 23, 2009
Model View Presenter Revisited
The MVP pattern is a pattern that came into being in the early 1990s by Taligent. This pattern is mostly used inside WinForms and WebForms.
The View normally don’t do anything. The official implementation is described as the following.
The view instantiate the presenter with an instance of itself. The constructor parameter of the presenter must be an interface of the view. When events of the view happens, they must call the presenter without any parameter/return value. If the presenter need data, the presenter will get the data from the view interface without the view giving the data directly. Changes to the view must be done through the presenter.
Of course, this is a literal implementation from 1990. Of course, today we have more advanced paradigm that works quite nice. What is interesting is, with proper data binding, that we can change the value on the views without even calling methods of the view.
It is possible to add a databinding on a property of the presenter. Once the databinding is done, it’s possible to just change the presenter’s property to fire events on the view that will automatically updates the control.
It removes some implementation details of the MVP and make the pattern easier to implement.
Need a sample? Here it goes to implement an “auto-notify” property when it change inside a presenter:
public class MyPresenter : IPresenter, INotifyPropertyChanged { private readonly IView view; private int randomNumber; public int RandomNumber { get { return randomNumber; } set { if (randomNumber == value) return; randomNumber = value; RaiseEvent("RandomNumber"); } } #region Implementation of INotifyPropertyChanged // custom method to ease the change of event public void RaiseEvent(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged = delegate { }; #endregion public MyPresenter(IView view) { this.view = view; this.view.InitializeBindings(this); } public void GenerateRandomNumber() { Random rnd = new Random(DateTime.Now.Millisecond); RandomNumber = rnd.Next(0, 100); } }
This will raise an event every time that a DIFFERENT value will be assigned to the property RandomNumber or when the event is fired. Now for the view, it look like this:
public partial class frmMain : Form, IView { private readonly IPresenter presenter; public frmMain() { InitializeComponent(); presenter = new MyPresenter(this); } public void InitializeBindings(IPresenter currentPresenter) { textBox1.DataBindings.Add("Text", currentPresenter, "RandomNumber", false, DataSourceUpdateMode.Never); } private void button1_Click(object sender, EventArgs e) { presenter.GenerateRandomNumber(); } }
The method InitializeBindings is called in the constructor of the presenter and will ensure that the binding are made only once. This will NOT require additional methods inside the view to assign the generated number inside the TextBox. This implementation respect the model definition while using the latest binding technology of .NET.
This reduce the amount of useless method while keeping the framework in charge of the bindings.
Here is the resulting interfaces from the implementation:
public interface IPresenter { int RandomNumber { get; set; } void GenerateRandomNumber(); } public interface IView { void InitializeBindings(IPresenter currentPresenter); }
Monday, February 2, 2009
Stop using those stupid Model example
Stop using Circle/Square/Rectangle, People/Employee, Car/Model examples for models or example on how to use Object-Oriented Principles or any example at all.
There is plenty of "Open" model that you can use. Here's a simple list for those who needs inspiration:
- Blog (Posts, Comments, Authors, etc...)
- E-Commerce (Invoice, Order, Customer, Warehouse, Inventory, etc...)
- Auction (Auction, Seller, Buyer, Reputation, etc....)
- Bank (Account, Transactions, Customer, etc...)
- News site (Article, User, Approver, etc...)
- And so many more
Unless you are explaining what is OOP to total beginner that never did any of this, you should use more advanced model to explain practices, design patterns or anything else. Otherwise, we'll keep on babbling on stupid model how a Square is a Rectangle and so on.
The time has come to stop using 1st grade model to explain advanced concept. Most people should be able to easily pick one of the model I've shown above and display one element of the model to easily make it available to everyone.
Who's with me?
Sunday, January 11, 2009
Response on "A Rant on Professionalism"
Chad Myers' posted this post about making changes and trying to improve our profession. Here is my comments.
There was a time back then that blacksmith were forging metal to make tools, weapons, nails, etc. What the blacksmith was doing was not recorded anywhere and was true craft. What he learned, he passed this information back to his students. With time, it became a science with predictable results.
Building software is a little bit how blacksmith were doing tools 300 years ago. We do have some methodology but none are guaranteed to give a successful software. I've seen lot of developers who just code away the features until the software works. I also know developers who are proud of what they do and try to improve the way they build software.
I find it really sad that people try to kill a methodology that produced one mistake or a failed project. Each methodology have their own benefits and disadvantage. Waterfall development have their place (believe it or not) when the requirements are fixed an will probably never changed as it is often the case in code that will go inside hardware or into outer space (see this article about the NASA software development for the shuttle). Agile is mostly good inside business with requirements that change along the way (80% of all development?). But the methodology is not the only thing to blame. There is unskilled developers, inexperienced team leader, unrealistic promises/deadlines, salesmen that promised more than the team could deliver, etc. All those elements can bring down a project whatever the methodology you are using.
On the Usage of tools
Tools can get you so far as where you want to go. Tools can't help you decide on where you are going. That's why I believe in ALT.NET. I don't care where the tools come from. If it's not ready and reliable, I'm not using it. Entity Framework looks good but guess what? I'm not using it for production. Too early. LINQ? Solid enough. For data mapping, we use LINQ to SQL for simple scenarios but I've used LLBLGen Pro, CodeSmith NetTier, SubSonic (not NHibernate yet but I promise I'll give it a try). Notice something in this list? No tools from Microsoft beside LINQ to SQL. DataSet and DataAdapters were nice but were not flexible/extensible easily and hardly fitted inside your model.
Whatever is done, bad technology choice can also lead to a project failure. We are far away from a methodology choice.
Conclusion
I totally agree with Chad on this. Much is left to do. But before we can make our craft a science... we must keep on trying new methodology, gather success AND failure. We must learn from every choice we make.
Without this, we're only going backward.