CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Raymond Lewallen

Framework Design, Agile Coach, President Oklahoma City Developers Group, Microsoft MVP C#, TDD, Continuous Integration, Patterns and Practices, Domain Driven Design, Speaker, VB.Net, C# and Sql Server

May 2006 - Posts

  • Sahil Malik presenting to OKC Developers Group on June 5th

     
    Our next meeting is coming up on Monday, June 5th, and we will be hosted by LSG at OSU-OKC for lunch and TEK Systems at the Downtown Library for our evening meeting. Thanks to INETA, Pizza and drinks will be FREE at both meetings so please be sure to RSVP! Also, if you are bringing guests, please be sure to have them register as well so we have an accurate count for the pizza!
     
    Speaker: Sahil Malik

    Microsoft MVP [C#], Author of Bestselling ADO.NET 2.0 book, ADO.NET trainer for Keystonelearning.com, telerik Evangelist. Sahil Malik is a Consultant, Trainer and Mentor in various Microsoft Technologies. He has worked for many large clients across the globe including a good deal of Fortune 100 companies and US government organizations. He is currently leading the office of Emerging Technologies at a prominent government office where he is in charge of reviewing, assessing and recommending various technologies to support the organization. Malik frequently speaks on a variety of .NET related topics at local user group meetings and industry events. For his community involvement and contribution, he has been awarded the Microsoft MVP award.
     

     

    Topic: Transactions
    Raise your hand if you want write bad code. Raise your hand if your boss every gave you a raise because you wrote a terrible unreliable system that corrupted the organization's data. If you haven't raised your hand yet, then come and dive deep into one of the most important computing topics. This talk dives into a theory on transactions, and then moves on to practical applications in databases, ADO.NET, SQLCLR, System .Transactions and other such related topics.

    Bring a Buddy Program

    For our June 2005 meeting, each person who brings a brand new person to the user group, the new person and the person that brought them gets their choice of an MS Press Book (while supplies last).   Just in case we need to clarify, only one book per person ☺.

    • Microsoft ASP.NET 2.0 Step By Step (MS Press)
    • Microsoft Visual Basic 2005 Step by Step (MS Press)
    • Visual Web Developer 2005 Express Edition Resource Kit
    • Introducing Microsoft ASP.NET 2.0 (MS Press)
    • Microsoft ASP.NET Programming with Microsoft Visual C# .NET Version 2 (MS Press)
    • Programming Microsoft ASP.NET 2.0 Core Reference (MS Press)
    • Web Service Security: Scenarios, Patterns, and Implementation Guidance (MS Press)
    • Microsoft ADO.NET 2.0 Step by Step (MS Press)
    • Programming Microsoft ADO.NET 2.0 Applications: Advanced Topics (MS Press)
    • Programming Microsoft ASP.NET 2.0 Core Reference (MS Press)
  • Presenting at CodeCamp in Wichita, KS on June 3rd.

    I’ll be presenting 2 sessions at the Wichita Developer’s CodeCamp this coming Saturday, June 3rd.

    The first session will cover building a strongly-typed session wrapper class.  Session has always been an issue with me, because for one, its not strongly-typed, and secondly, you have to worry about developers just stuffing things into it and bloating it badly.  With a wrapper class, you can use strongly-typed properties and store the entire class itself in session, thus only have a single key-value pair session variable for your users.  You also enforce the use of the wrapper so that your session doesn’t get out of control.  Also, for those rare occassions when you might want to, your session wrapper class can also be serialized.  If you are in the Wichita, Kansas area this Saturday, come see how to do this.  I will also cover creating wrapper classes for cache and viewstate.

    The second session will cover Continious Integration.  In this session, we will do an entire walkthough on setting up a continuous integration server.  Tools that will be covered are Subversion, NDepend, FxCop, NCover, NUnit (from TestDriven.Net), NAnt and CruiseControl.Net.  Come check out the session and walk away with an integration server running on your laptop, including all the tools listed.

  • Why do some programmers hate the thought of using a managed framework?

    I have this discussion with various .Net non-believers, and maybe its just me, but I can’t imagine why they just don’t understand what I’m telling them.  The arguments against moving to a managed framework mostly come from the hardcore C and C++ developers I talk to.

    Writing software is about delivering business value.  Period.  The person who signs your paycheck doesn’t care near as much about what language or framework you are using as much as they care about the fact that you are hitting deliverable deadlines within budget on a constant basis.  Being a good software developer lies in part in being a value to the business.

    The main argument I hear is “I like to be in total control over everthing that’s going on”.  "I don’t trust the managed framework".  "I don’t like how it works".  In reality, they don’t understand it.  They don’t want to understand it.  They think the managed framework can’t do a better job than they can when it comes to memory management and resource management.  This is total BS in my opinion.

    The managed framework does a damned fine job of handling memory and resources, and the only way you can out-do it, is to spend 3 times the amount of hours and money to accomplish the same task that a managed framework developer is going to do.  Even then, you’ll just *barely*, if at all, outperform the managed framework in the majority of these special cases.  Even so, in rare cases where you do need to do some resource management or some memory management on your own, the managed framework allows for this to a certain degree, which in most cases is all the control you need.

    So if you are continuously costing your company 3 times as much (probably more, as C++ developers demand more money) to produce the same value as a managed framework developer, with negligable or no noticable performance difference, how does that reflect back to the customer?  Badly is the answer.

    After explaining that your customer doesn’t care how you do it, your customer cares about value, I had one guy give me this argument: “Well, I want to do my own consulting and write my own software someday, so I want to know how all of that stuff works and do it myself.”  OMG.  Now he’s given me an even better example for him to move to a managed framework.  Now this person wants to manage their own business, which is going to suck up a lot of time that could be spent writing software.  Moving over to a managed framework has become even more imperative to him at this point so that he can focus on the logic and design of the application without spending the tedious time on finding memory leaks and manually managing resources.

    Am I saying that all C++ programmers should switch completely to a managed framework?  Certainly not!  We must have these machine level programmers.  They have been and will continue to be a vital and necessary skill set in the world of software development.  Should you be writing your customers inventory management system in C++?  Probably not.  You are too easily replaced with a managed code programmer, who can deliver the product faster, with less cost, and most likely with less bugs.

    Take a look at your development and business environment.  You can tell whether you should be using a managed framework or not.  It the vast majority of cases, a managed framework is your solution to saving time and money for your customer, which is the goal of any good developer.

  • Before you telecommute, know why telecommuting is hard

    The following explains why I never telecommute anymore, and why telecommuters may not get as much work done as us office dwellers.  I used to telecommute, and this is what my day was like:



    I decide its time to start working. 
     
    As I start toward the office, I notice that there is mail on the hall table. 
     
    I decide to go through the mail before I log on. 
     
    I set my PDA down on the table, put the junk mail in the trash can under the table, and notice that the trash can is full. 
     
    So, I decide to put the bills back on the table and take out the trash first. 
     
    But then I think, since I'm going to be near the mailbox when I take out the trash anyway, I may as well pay the bills first. 
     
    I take my checkbook off the table, and see that there is only one check left 
     
    My extra checks are in my desk in the study, so I go to my desk where I find the can of soda that I had been drinking. 
     
    I'm going to look for my checks, but first I need to push the soda aside so that I don't accidentally knock it over. 
     
    I see that the sodea is getting warm, and I decide I should put it in the refrigerator to keep it cold. 
     
    As I head toward the kitchen with the soda a vase of flowers on the counter catches my eye--they need to be watered. 
     
    I set the soda down on the counter, and I discover my reading glasses that I've been searching for all morning. 
     
    I decide I better put them back on my desk, but first I'm going to water the flowers. 
     
    I set the glasses back down on the counter, fill a container with water and suddenly I spot the TV remote.  Someone left it on the kitchen table. 
     
    I realize that tonight when we go to watch TV, I will be looking for the remote, but I won't remember that it's on the kitchen table, so I decide to put it back in the den where it belongs, but first I'll water the flowers. 
     
    I splash some water on the flowers, but most of it spills on the floor. 
     
    So, I set the remote back down on the table, get some towels and wipe up the spill. 
     
    Then I head down the hall trying to remember what I was planning to do. 
     
    At the end of the day: No work got done, the bills aren't paid, there is a warm can of soda sitting on the counter, the flowers aren't watered, there is still only one check in my checkbook, I can't find the remote, I can't find my glasses, and I don't remember what I did with my PDA. 
     
    Then when I try to figure out why nothing got done today, I'm really baffled because I know I was busy all day long, and I'm really tired.



  • Avoid breaking your API - pay attention to your constructors.

    I was playing with a document coverter API a few months ago to do some PDF to Word conversions.  I had some code already built into a console app to use that version and it was working fine.  Last night I went and downloaded their latest version, and wouldn’t you know, it commited one of the major crimes of APIs: it broke my code.

    The culprit?  The constructor to a class.  It used to work as follows:

    Converter fileConverter = new Converter();
    fileConverter.Path = “c:\myfiles\test.pdf”;

    Now, for whatever reason, they decided to change the functionality so that you pass the file path into the constructor like so:

    Converter fileConverter = new Converter(filePath);

    Now, there is nothing wrong with this, except for one major thing they overlooked.  On a class, if you have a parameterized contructor, the comiler WILL NOT emit a default parameterless constructor.  Only when the class is void of any constructor at all will the compiler emit a default parameterless constructor.  When they created the parameterized constructor, they should have put in another constructor so that breaking changes wouldn’t occur:

    public Converter() {}

    The Path property is still read/write, so simply adding the parameterless constructor would have left my code working fine.  Please, avoid the same mistake.  This would have avoided them shipping their API with breaking changes and help them to avoid some pissed off customers who rely on their product.

  • Communication is key - why I was misunderstood

    Maybe you live in a cubicle.  You love your privacy, your personal space, your segregation from the rest of the office.  You have it decorated how you want and its your home away from home.  You have email and instant messengers at your fingertips to communicate with your co-workers.  What a wonderful world will live in, right?  You get to do all your work, communicate with your team and never have to leave the comfort of your private little “home”.

    While this is all nice, it has a certain negative impact on your team’s ability to communicate and effectivly solve problems in a timely and cost-efficient manner.  For those of you who have knowledge of agile methodologies, XP in particular, you’re aware of the war room.  A war room is a large room where everybody on your team can sit together, see eachother, quickly and easily talk to eachother, have constant face to face communication and be a more effective team.

    Face to face.  That is the key idea here.  Let me give you an example.  Check out this blog post and its responses.  I can guarantee, with absolute certainty, that none of the misunderstandings would have occurred, and this was have been a simple, easy discussion had we all been in the same room and able to communicate face to face.  When I finished writing the post, I re-read it to make sure I was communication my thoughts and purposes effectivly, and was satisfied with what I had.  Judging from a couple of the initial responses, I certainly failed to communicate my goals properly.  Had I taken Jeffrey’s initial advice, not only would this have not solved my problem effectively or achieved my overall goal, it may very well add complexity to the system (in my opinion) that doesn’t necessarily need to be there for that piece of the code to serve its function properly.  The same goes for Matt’s comment.  While its a fine way to create a private function to handle the logic of equating the dates, it serves little purpose to the overall goal I was trying to achieve.

    Too many people think that emails, IM’s and blog posts with responses are an effective way to communicate.  While its convenient, its certainly not as effective as face to face communication.  Facial expressions and the ability to interject into a conversation can make all the difference in avoiding miscommunication and misunderstandings.

    Get out of your cube, walk over, and have face to face conversations and ditch that internal IM and email crutch.  Its a crutch that will keep your communication efforts limping until you give it up.

  • Asking for your ideas regarding refactoring a design smell

    Logic can certainly destroy your code reuse, and produce quasi-design smells that you’d really like to do something about because it aggrevates you, but you can’t really change.  What if I told you that I had 9 different functions that determine if a date is one calendar year from today’s date?  You’d probably gasp, and wonder why in the heck I would need 9 different functions for that.  I’ll tell you.  In my business domain, 1 calendar year means the following:

    Given today is 5/8/2006, 1 calendar year can mean, depending on the context:

    5/1/2006 00:00 – 4/30/2007 23:59
    5/1/2006 00:00 – 5/8/2007 23:59
    5/1/2006 00:00 – 5/31/2007 23:59
    5/8/2006 00:00 – 4/30/2007 23:59
    5/8/2006 00:00 – 5/8/2007 23:59
    5/8/2006 00:00 – 5/31/2007 23:59
    6/1/2006 00:00 – 4/30/2007 23:59
    6/1/2006 00:00 – 5/8/2007 23:59
    6/1/2006 00:00 – 5/31/2007 23:59

    Now, which functions gets used depends on the context in which it applies, so puting the functions in a stateful object doesn’t make sense, cause then I’d have actual line for line code resuse because the functions are used throughout different scenarios.  Right now, each function exists as a boolean function of a static class.  Each function has the following public signature:

    public boolean IsWithinValidCalendarYearX(date value)

    where X is a some sort of horrible naming convention particular to each function.

    Clearly, this is a case for redesign.  These functions have been added over time, and I never went back and refactored the logic into something better.  Now its time to do so.  I could have a private function like:

    private boolean IsWithingValidCalendarYear(date startDate, date endDate, date givenDate)

    but there is still some work that has to be done in the public function to calculate what the start and end dates are, and an additional parameter to tell it which set of rules to apply, and that possibly makes the API more confusing, unless I used and enum as the 2nd parameter to the public function, which would reduce the confusion.  In the end, even though I’ve reduced the number of functions from 10 to 2, the same amount of code still exists, but with less duplicate lines.  I could really just have 1 public function, passing in the given date and the enum value and just do all the work right there, because I’m still going to have this mess of conditions and checks regardless of whether I have the private function call or not.  At least right now, my cyclomatic complexity is low for each method, but the API itself is ugly.

    So where is the trade off?  Where does the line lie between ugly API and better code design?  Create a nicer API at the expense of more complex code, or leave a complex API at the benefit of less complex methods?  What are your thoughts and ideas around this?  How would you approach this?  The solution to this refactoring will also get applied to similar code smells in the logic that follow the same bad problem.

  • Common patterns posters to decorate with

    Once again, while just browsing through my harddrive, I came across 2 nice posters that I thought I would share with you.  They are 2 posters that show common patterns used on object-oriented design.  The patterns grouped by color and cover:

    • Creational
      • Singleton
      • Factory
    • Structural
      • Facade
      • Decorator
      • Adapter
      • Proxy
    • Behavioral
      • Template
      • Strategy
      • State
      • Command
      • Observer
    • Architectural
      • Pipes/Filters

    Quite a handy little guide to have if you or some coworkers don’t know them and want them readily available.

    These are not full size so that they don’t take up much room.  Each one is actually 1556 x 1080 in size when you get it downloaded.  Click on each one to take you to the full size pic.

     

  • Learn from my mistakes - refactoring and fixing design smells using common patterns

    So I’m working in a maintenance release right now.  Very little added functionality.  My current release at work is primarily to adjust to domain logic changes.  This starts by adjusting the unit tests to accomodate the changed logic, and then fixing the code to fix the tests.  Still, due to the nature of the changes, a lot of regression testing will still be involved.

    This release also gives me an opportunity to go back and fix some serious design errors that I have lazily let make their way into the code.  I want to cover a few these now, tell you why they are design mistakes, and how to fix them.  Feel free to leave nasty comments here and add me to your wall of coding shame for some of these.  For the most part, I was being lazy, but recognizing these mistakes and fixing them as soon as I have the opportunity should award me back some brownie points, right?

    Poor use of some static classes

    Static classes are something that you usually don’t find too often in a framework, and rightly so.  They are there to only support the instance classes of the rest of your framework, but there is a right way and wrong way to do that.  Of the several static classes I have, the majority are designed correctly, but two of them are not.

    Here’s the design mistake: I have 2 static classes that are a catch-all for miscellaneous methods that support the framework.  Let’s say you have an application for tracking car sales.  To mimic the design mistake, I have a static class such as the following:

    Static Class GlobalMethods
         GenerateNewCarId() : Int32 // generates a new Car ID
         GenerateNewCustomerId() : Int32 // generates a new Customer ID
         VerifyEmail(email)  : Boolean // verifies a customer email address using RegEx
         Age(dateOfBirth) : Int32 // returns a Customers Age

    Now, each of these are fine being static methods, but they are for the most part, unrelated.  Better organization needs to occur here.  I should create a new static class in the namespace for the Cars and another in the namespace for the Customers, and move each Id method to its corresponding static class so its coupled with the rest of its entities.  The Age function can be moved to the Customer instance class itself, where the dateOfBirth is already stored as part of the state of the object and we can remove the parameter from the function.  VerifyEmail can perhaps be made a private method inside the Customer instance class, and be called when we load the object state, or simply {get} the Email property.  How to handle the logic if the VerifyEmail fails is dependant upon your particular situation.  My actual code isn’t this blatently bad, but you get the idea.

    Reducing If/Then and Switch logic

    I could talk about this, but Jeremy has an excellent post on using the Strategy Pattern, which is I need to implement into some code that has become bloated and overly complex.

    These next few pieces of design problems are all coupled together to reach a common goal.

    Unify Interfaces

    The idea around unifying classes (the actual refactoring applied here is referred to as Unify interface) revolves around evolving subclasses without evolving your interfaces or superclass.  As my application has evolved, so has a number of classes that either implement an interface or inherit a superclass.  The added methods to the subclasses don’t exist in the superclass, such as the following:

    Public Class Vehicle
         NumberOfWheels : Int32
         Doors : Int32
         Color : ColorEnum
         Weight : Int32

    Public Class Car : Vehicle
         ToHtml() : String
         NumberOfWheels : Int32
         Doors : Int32
         Color : ColorEnum
         Weight : Int32

    As you can see, my subclass contains a method, ToHtml, that returns a description value to display on a webpage, that doesn’t exist in the superclass.  To unify the interfaces of both, I need to copy the missing methods to the superclass.  Now my superclass Vehicle looks like this:

    Public Class Vehicle
         ToHtml() : String
         NumberOfWheels : Int32
         Doors : Int32
         Color : ColorEnum
         Weight : Int32

    Now my subclass and my superclass share a common set of functionality, i.e. a common interface.

    Extract Interfaces

    Now that this is done, I’m ready for another refactoring to take place: Extract Interface.  So now I’m left with the following:

    Public Inteface IVehicle
         ToHtml() : String
         NumberOfWheels : Int32
         Doors : Int32
         Color : ColorEnum
         Weight : Int32

    Public Class Vehicle : IVehicle
         ToHtml() : String
         NumberOfWheels : Int32
         Doors : Int32
         Color : ColorEnum
         Weight : Int32

    Public Class Car : Vehicle
         ToHtml() : String
         NumberOfWheels : Int32
         Doors : Int32
         Color : ColorEnum
         Weight : Int32

    Now I’m much closer to a better design than what I started with for this set of classes.

    Make unit testing easier

    To take it one step further, imagine a class that relies on the Car object to do its work.  And let’s also say we have a unit test on this class, but in order for the test to work, we have to have a connection to the database.  Well, we don’t like that very much, so a good way to remove that database layer is to use dependency injection.  Take the following class:

    class Ticket

        {

            private Car _car;

            private Int32 _carId;

     

            public Ticket() {}

     

            public Ticket(Int32 carId)

            {

                _carId = carId;

            }

     

            public void Load()

            {

                // do something to load the car

                // object using the carid, if it

                // is > 0

            }

        }

    In order to test this class and its methods (that I didn't bother adding for the examples, but there are other methods on the class we need to test), we must have a Car object, but the only way we can get it right now is to load one from the database after calling the constuctor that takes a carId parameter.  Not very good.  Big design mistake on my part, and I have plenty of places where this needs to be fixed in my code.  Take time to curse me under your breathe right now.

    How do we fix it?  If you read the above link, and you should have, you know the answer.  We implement dependency injection into the equation.  We are going to use a mock Car object, give that object to the Ticket class, and use that mock object to do our unit testing, rather than requiring a connection to the database.  When we’re done, and again, you know how all this ties in because you read the above link, we end up with this:

    class Ticket

        {

            private IVehicle _car;

            private Int32 _carId;

     

            public Ticket() {}

     

            public Ticket(Int32 carId)

            {

                _carId = carId;

            }

     

            public Ticket(IVehicle car)

            {

                _car = car;

            }

     

            public void Load()

            {

                // do something to load the car

                // object using the carid, if it

                // is > 0

            }

        }

    Now we can just give the Ticket class a Car to use to do its testing.  This wouldn’t have been possible if I hadn’t gone through the above Unify Interfaces and Extract Interface refactorings first.

    So there are the major design smells that I’m going to be fixing over the next two months.  I hope you read this, learn from my design laziness and mistakes so that you don’t have to have a maintenance release.  The people signing your paycheck really, really hate maintenance releases, because they are paying you for ZERO or minimal functionality for that release.  Its best to avoid these mistakes altogether, but incase you need to sneak in a few similar fixes, hopefully my above roadmap will help you out.

More Posts

Our Sponsors

Free Tech Publications