Corey Coogan

Python, .Net, C#, ASP.NET MVC, Architecture and Design

  • Subscribe

  • Archives

  • Blog Stats

    • 52,385 hits
  • Meta

Archive for September, 2010

Is Developing Software Hard Work?

Posted by coreycoogan on September 24, 2010

I got to thinking about this a couple months ago as I sat in my chair pondering what a pain it was to accomplish some task I was working on.  There was a lot to do and I thought briefly to myself, “this is hard work”.  It was brief because I immediately sat back and enjoyed a small chuckle.  Can I honestly say that developing software is “hard” work?

Working Hard for Real

Many of friends from back home are in the trades – carpenters, electricians, plumbers, landscapers.  If they heard me describe anything I do in my profession as hard work, I’d probably get punched in the teeth, perhaps deservedly so.  When one of these guys has a day of hard work, it means breaking their back, spending thousands of calories, excreting gallons of sweat.  Sometimes they work so hard they even hurt themselves, but pick up the pieces and come back for more the next day.

My Kind of Working Hard

Now compare that to what I do.  When I am really working hard, would anyone be able to tell?  Could someone stop by my cube one day when I’m doing something easy and another day when I’m doing something hard and be able to tell the difference?  Would they be able to comment at the water cooler, “I just stopped by Corey’s cube and he is working really hard”.  I think not.

Often times working hard in the software profession is associated with the number of hours being worked.  I would agree, that this can be very difficult and the signs of this kind of hard work can certainly be visible to the naked eye.  For the purpose of this post, I’m talking about a regular 8 hours work day.

Thinking is Work

Back to my friends in the trades for a moment.  They would find it hysterical to hear me come home and tell the wife, “I’m tired…I worked very hard today.  Will you rub my fingers?”. Worked hard doing what?  Sitting on my ass?  Pushing buttons?  Wiggling my mouse around?  The truth is, yes, all of the above.  Hard work is a relative term.

For starters, let’s look at the definition of work:

sustained physical or mental effort to overcome obstacles and achieve an objective or result

Notice the word mental?  So we’re covered from a semantics standpoint.  Thinking actually is work – by definition!  If we go a little further, we find that there’s science that shows our brains consume quite a bit of energy.  The more we think, the more energy our brain needs.  This is confirmed by the fact that when we as humans stimulate our brains, we even get very hungry (which explains a lot about the typical IT break room and our physique as an industry).  If we’re consuming more energy and getting hungry, it must be hard work.

What does this Mean?

Great, so I now I know the harder I think, the harder I work.  What does this mean?  Do we as software developers ever take the easy way out because the alternative is so exhausting?  Probably not.  My gut tells me it’s more likely due to laziness than anything else. Sure, sometimes the situation demands that we cut corners, but other times there’s no real good excuse.

It was Vince Lombardi who said:

The only place success comes before work is in the dictionary.

I say we embrace hard work.  If we are going to sit on our butts for eight hours pushing buttons, we might as well make them count.

Posted in Developer Life | Tagged: , | Leave a Comment »

Good Developers Know When to Write Bad Code

Posted by coreycoogan on September 22, 2010

I read a blog post last week that stated plainly if you “knowingly create a bad design or write bad code”, then you are a bad developer. The post went on to list 4 criteria that must be followed if you break this rule that would save an offender from earning the “Bad Developer” badge of shame.  (UPDATE: I misquoted.  The post actually said “one or more of the following)

  1. Get upset because they know they are writing less than perfect code/design.
  2. Leave a comment stating why the code/design was done in this factor.
  3. Add a ToDo for refactoring later.
  4. Will do the imperfect code/design in such a way that the refactoring effort will require less effort.

I read this post and had to disagree with such a dogmatic, black-and-white view. So here’s my take on the whole thing, breaking it down as simply as possible.

  • Time is finite.
  • Resources are finite.
  • Requirements are seemingly infinite.
  • Deadlines exist, sometimes arbitrarily and other times for real reasons like market pressures or legal diligence.
  • To meet deadlines when you are in the hole there are 2 options:
    - Cut features and scope.
    - Cut corners.
  • Sometimes features and scope can’t be cut (see Deadlines).
  • Some tasks require commodity code – simple crud forms for updating contact information for example.
  • Some tasks require specialization code – getting to the meat of the domain to add real value.
  • Many clients, who are paying the bills, don’t care about the commodity code’s design principles as much as they care about their deadlines and commitments.
  • Refactoring takes time, and given that time is finite, must be prioritized from highest ROI to lowest ROI.
  • When commodity code is poorly written but works just fine and causes zero friction, choosing to refactor it over specialty code can come with a hefty opportunity cost

Given this information, I say that a person can still be a good developer even if they knowingly write bad code. To me, a good developer knows when to write bad code and where to focus their time and energy.  In a perfect world, this would never happen – we would always do things the best way.  Obviously this isn’t reality and sometimes sacrifices have to be made. I believe that the good developer understands this and knows to sacrifice that which offers little value for that which offers great value.

Nobody is going to lose in the market because their “contact us” form is saving to the database in the code-behind. But choosing to devote an hour “doing it right” that could be spent refining the domain model or refactoring real friction points that cause actual pain can come at a high price. Like the old saying goes – Good, Fast or Cheap… pick any two.

Posted in Business, Developer Life | 5 Comments »

Using NHibernate from a Batch Program

Posted by coreycoogan on September 17, 2010

I use Batch Programs, aka Batch Jobs, all the time for tasks that aren’t necessarily time-critical. In most organizations, there are many of these things running on servers all over the place.   I recently had to write a batch job that did a bunch of database updates using NHibernate.  The job updates two tables in a foreach loop.  Within each loop, an NH transaction is started, committed or rolled back and disposed of.  I usually don’t write all my code into the default program.cs file, but opt for writing some service to do the heavy lifting.  I recently wrote one that had ran into some problems.

I wrote the service as I usually would.  I setup my constructor to take everything it would need and made a StructureMap registry to bootstrap all my dependencies so I could work with the existing components.

Here’s my original batch service constructor:

public ProfileUpdateService(
ISession session, //for managing transactions
IProfileRepository repo //for getting/saving
)
{
    //set private vars
}

My StructureMap registry was pretty basic.  It takes an ISessionFactory instance in the constructor and uses it to setup the ISession resolution.  The repository happens with a scanner’s default conventions:

For<ISession>()
   .Use(() => _sessionFactory.OpenSession()); //use the lambda to ensure my factory is configured when this is actually accessed

Here’s what my original code looked like (sort of):

var records = _repo.GetAll();

if(!records .Any())
    return;

try
{

    foreach (var record in records)
    {

        try
        {
           
            _transaction = _session.BeginTransaction();
           
            var otherRecord = _repo.GetOtherThing(record.Something);
 
            //do some processing first then save
            _repo.DoFirstThing(record);
            
           //do some processing first, then save
            _repo.DoSecondThing(otherRecord);

            _transaction.Commit();
        }
        catch(Exception ex)
        {
            //log it
            //rollback
            _transaction.Rollback();
        }
        finally
        {
            if(_transaction != null)
                _transaction.Dispose();
        }
    }
    
}
finally
{
    _session.Dispose();
}

During testing, some edge cases emerged that caused an exception while committing my changes.  Since my use of NHibernate has followed the Session/Request pattern in web and WCF environments, I never really had to deal with exceptions and their impact on the NHibernate Session.  But this case was different.  There was no single Request to contain my Unit of Work and I soon found out that the exception being thrown was hosing up my Session.  RTFM, right Corey?

Here’s what the NH reference doc has to say about it:

If the ISession throws an exception you should immediately rollback the transaction, call ISession.Close()
and discard the ISession instance. Certain methods of ISession will not leave the session in a consistent state.

I had to make some obvious changes.  My batch service needs to be able to create an instance of an ISession and since my repository class takes an ISession in its constructor, I need to be able to create a new IProfileRepository instance as well.  Since I wanted to maintain testability, I used the mighty Func<> as a factory.

Here’s what my constructor looks like now:

public ProfileUpdateService(
ISessionFactory sessionFactory,
Func<ISession,IProfileRepository> repoFactory
)
{
    //set private vars
}

Now I had to change StructureMap to know how to resolve those dependencies.  Using the Lambda in the Use() method gives me deferred execution, so I don’t have to worry about premature invocation of my ISessionFactory.

For<ISessionFactory>()
                .Use(() => _factory);

For<Func<ISession, IProfileRepository>>()
                .Use((session) => new ProfileRepository(session));

Finally, I had to restructure the code to better handle the exceptions.  When one happens, I want to close and dispose of the ISession instance being used.  I would also want to use a new Repository object since the current one will be using the damaged ISession object.  To handle this, I relied on properties and lazy initialization.  (note: this code may not be the most efficient, but it’s a batch job after all, so give me a break)

//use the lazy initialized repo
var records = ProfileRepository.GetAll();

if(!records .Any())
    return;

try
{

    foreach (var record in records)
    {

        try
        {
          
            _transaction = Session.BeginTransaction();
           
            var otherRecord = ProfileRepository.GetOtherThing(record.Something);
 
            //do some processing first then save
            ProfileRepository.DoFirstThing(record);
            
           //do some processing first, then save
            ProfileRepository.DoSecondThing(otherRecord);

            _transaction.Commit();

        }
        catch(Exception ex)
        {
            //log it
            //rollback
            _transaction.Rollback();
            
            _session.Dispose();
            _session = null;
            _profileRepository = null;
        }
        finally
        {
            if(_transaction != null)
                _transaction.Dispose();
        }
    }
   
}
finally
{
    _session.Dispose();
}


//Using lazy initialization so I don't have to worry about these being destroyed
IProfileRepository ProfileRepository 
{
    get
    {
        if (_profileRepository == null)
            _profileRepository = _profileRepositoryFactory(Session);

        return _profileRepository;
    }
}

ISession Session
{
    get
    {
        if (_session == null)
            _session = _sessionFactory.OpenSession();

        return _session;
    }
}   

This really isn’t rocket science, but it’s a different way of thinking for those of us using NHibernate from the Web.

Posted in C#, IoC, NHibernate, StructureMap | Tagged: , , , , | Leave a Comment »

How to Give Advice Online

Posted by coreycoogan on September 16, 2010

We’ve all be there – stuck with some problem and the solution won’t reveal itself no matter how much we search.  It’s at this point that I turn my sights towards forums and user groups to try and get advice from the online community.  This can be Stack Overflow, a topic specific Google Group or a well known blog or forum site like Microsoft Social.

Side Note

It’s laughable to see how many people actually turn to the community for help before even attempting to figure things out themselves.  Ayende wrote about his frustrations on the topic, so please don’t be that person.  I digress…

I try to write my question to be as complete as possible.  I want to include everything I think someone would need to help me, fearing that if I leave something out the person who has the answer and was just willing to share it with me is now gone forever, helping someone else who wrote a more complete question.  The key is not to put too much information in the question.  I don’t want to scare anyone away by showing them 5000 lines of code when they open that sucker up.  So I try and find just the right balance and give disclaimers that some things are left out.

Enough setup, now for the crux of this post – "How to Give Advice Online", which could have also been titled "Don’t be a Dick when Giving Advice Online".  So often, the people that choose to answer questions commit one or more of the following dick behaviors:

  • Nitpick at unimportant details, like “you should close your connection” or “you should catch that exception”.
  • Make assumptions about the code that’s left out or the entire context of the problem, usually supporting the preconceived notion that they are smart and you are stupid.
  • Belittle, make fun and/or talk down to you during every exchange.
  • Give short, one-line solutions with no detail that are of little or no use and most certainly leave many a solution seeker more confused then they were when they started.  If you are going to throw someone a bone, spend the extra 60 seconds and at least make it complete enough to get the reader started in the right direction.

When I get these types of responses, I really try to remain patient.  It’s hard to resist the urge to stoop to their level and let things turn into a cat fight.  That’s just a waste of time and it’s unprofessional.  Not to mention there will be a permanent record of your childish behavior available for anyone who searches your name for all eternity.

I’ve read that people don’t act this way in the Ruby community, but it runs rampant in the .NET developer community.  Are .NET developers so arrogant and full of themselves that they believe they can treat people like crap?  What created this culture?  Very perplexing indeed.  The best I can do is try not to perpetuate this behavior and keep the stereotype going.

If you wish to donate some of your time and give free advice online, do it for the right reasons.  Don’t use it as an opportunity to make people feel stupid so you can feel superior.  Just be patient and share what you know.  Everybody needs help at some point, so think about how you’d you’d feel if you were given the response you’re writing.  If a question seems exceedingly stupid or you have a beef with the person asking it, move on. Like an offensive television or radio program – you can always turn the channel.  Put simply, don’t be a dick.

Posted in Developer Life | Tagged: , , | 2 Comments »

Reviewing “Getting Real” and “REWORK” by 37 Signals

Posted by coreycoogan on September 15, 2010

NoMojo I’ve recently been in a funk.  I felt as though a big part of my Mojo was missing.  I’ve been in a bit of a dead-end gig lately where the work brings me little to no joy, so that could have something to do with it.  On the other hand, I have a fun side project that I’m trying to get off the ground, but it’s been almost impossible to get motivated in the last several months.  Part of this is due to the side work I do at night, but mostly it’s as simple as a loss of Mojo.

I’m fascinated with 37 Signals (highly recommend their blog). Not only from a technical perspective, but also from a UI Design and business standpoint as well.  I have been poking around the free eBook version of Getting Real for while.  One day, while wallowing in my funk, I decided to buy Getting Real and REWORK from Amazon and search for some inspiration.

Inspiration

I found my lost Mojo!  Reading these books helped revive my passion for software development.  They got me excited about the side project again – so much so that I removed the half completed features and deployed what I have so I could launch the blog to start building relevance and begin driving traffic.

Getting Real

Getting Real says it’s about building “a successful web application “, but it’s about so much more.  It covers a wide range of business concepts as well and was really fun to read.  This book emphasizes simplicity.  Keep things simple and deploy.  Don’t get bogged down in analysis paralysis.  That’s what happened to me with RoomParentsOnline.com.  I got so consumed with the “simplest” way of making the classroom portion self governing, yet safe and secure for the students, that I ended up conceiving a solution that was so complex and difficult to start, my brain just shut down and found excuses not to work on the project.

After reading Getting Real, my whole thought process of handling features changed.  I reevaluated what I was doing and found a solution that is 1000 times simpler and probably just as effective.  It also helped get things in perspective about how cheap and easy it is to try something and deploy.  Get people using your product.  If it sucks, change it.  In many cases, the details we obsess over are meaningless to the end user.  I’ve always tried to follow the Agile mantra of “Simplest Solution that could Possibly Work”, but I somehow drifted.

I highly recommend this book for anyone doing web development or involved in web development.  It’s an eye opener and a breath of fresh air.

REWORK

This is another amazing book.  Unlike Getting Real, REWORK is not specifically about developing web applications, but about business and succeeding in it.  The back cover says a lot of what this book is all about:

ASAP is poison
Underdo the competition
Meetings are toxic
Fire the workaholics / emulate drug dealers
Pick a fight
Planning is guessing
Inspiration is perishable

Before reading the book, I subscribed to most of these ideas.  I hate wasting time in meetings and nothing drives me more insane than documentation for the sake of documentation.  BDUF is a proven failure, yet it continues to dominate big Corporate America.  After reading REWORK, I was so happy to hear that breaking away from this mentality can work – and there’s proof.

A fair amount of content from Getting Real is repeated in REWORK, but not enough for me to recommend one book over the other.  Since reading it, I’ve been recommending it all over the place.  This book is a must-read and I wish I could send every client, every partner and every consultant I work with a fresh new copy.

The theme is the same as Getting Real.  Do things simple and do them fast.  Say NO to new features until they come up again and again – then you know they have real value.  The authors do a great job of citing their own successes, as well as those of other companies.  They also use simple metaphors that are easy to understand and fun to read.  I strongly encourage anyone reading this blog to get your copy immediately and read it.

Conclusion

Getting Real and REWORK are fast and easy reads and I found the casual writing style felt like I was a conversation with the authors.  Both books are phenomenal and capable of being real game changers when read with an open mind.  So please, when you do read them, be open.  Don’t hold on to your old way of thinking.  Do yourself the favor of entertaining the ideas in these books so you can appreciate the true merit.

Posted in Business, Review | Tagged: , , | Leave a Comment »

Initializing NHProf in MSTest

Posted by coreycoogan on September 4, 2010

Alternate title for this post could be Running initialization code before an MSTest Test Run

I’m not at all a fan of MSTest for various reasons. My preference is NUnit, however xUnit, mbUnit or any other framework is just as well. There are often cases when a client wants to use MSTest, usually for its Visual Studio integration. This is a compelling argument for a shop new TDD or unit testing, that wants the least amount of friction and doesn’t want to invest in TestDriven.Net or R#.

Integration tests written with MSTest are a great place to profile your NHibernate data access and catch any gotchas early in the development cycle. When the client is willing to pay for it, there’s no better tool than Ayende’s NHProf for this. NHProf can be easily initialized in code, but this should be done only once per test run, as you would bootstrap NHibernate itself only once. This led me on a search in MSTest for how to initialize once per test run. There’s widely known attributes for executing setup code when a test class fires and also whenever a test fires, but the answer to my requirement was found in the lesser known [AssemblyInitialize] attribute.

Just throw that attribute on a static void method that takes a TestContext argument and it will execute once before each test run. The class that houses the initialization method must also be decorated with the [TestClass] attribute.

[TestClass]
    public class AssemblyInit
    {
   
        [AssemblyInitialize]
        public static void Init(TestContext testContext)
        {
             HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
        }
    }

Posted in Architecture and Design, C#, NHibernate, TDD | Tagged: , , | Leave a Comment »

The Singleton and Composition/Testability

Posted by coreycoogan on September 3, 2010

I read this post from Kellabyte which got me thinking about solutions I’ve used in the past.  There’s ways to live with Singletons, at least from a composition and testability standpoint.  This can come in especially handy when working with a legacy code base.

The first thing, is that your property/method that returns the instance of the Singleton should return an interface, not a concrete.

public static ILog Instance
{
     get{ return _logger;}
}

I assume when talking about composition, we are all using an IoC container of some kind.  My favorite is StructureMap.  Most containers have the ability to configure a type resolution through a factory method.

In SM, it might look like this:

ForSingletonOf<ILog>()
.Use(() => Logger.Instance)

Now any requests from your container that require an ILog instance can come from the Singleton in production, but resolve to a mock or anything else in test scenarios.

//example of Dependency Injection via constructor
public class SoSomethingService(ISomethingRepository repo, ILog logger)
{
//set to instance vars
}

Posted in C#, Design Patterns, IoC, StructureMap | Tagged: , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.