sfeldman.NET

.NET, code, personal thoughts

October 2008 - Posts

Lately I had an accident with my HP Pavilion laptop and wanted to share the HP service story with you. Hopefully it will save people time and money.

Less than a year ago I bought  a brand new HP Pavilion dv9000 17" laptop. The price was high, I was naive, and have decided to purchase an extended warranty provided by the store (Future Shop in my case).

11 months of a very  heavy usage, I happened to forget half a glass of Sprite beside the laptop. Boy that was a mistake. My 'little pup' (accelerate Golden Retreiver) waved his tail and boom! Sprite on the keyboard. The fact that I shut it down, removed the battery, and turned it up side down has helped. The only issue was with a keyboard. Because of the sugar (this is probably another blog entry) in Sprite, keyboard became sticky inside and typing was impossible.

What do you do? Try to claim the extended warranty. Nope. Future shop will cover anything, but not the real damage. So I called HP to have an idea what are my options. Man I was surprised.  Apparently, I could have warrant my laptop with HP for the same amount of money and have spillage and accidental drops covered. Like a mad bull I took the receipt to the Future Shop to claim my 'wasted' money back. Interestingly, they did not even try to argue and reimbursed the whole amount. Nice, as a customer I felt good. But still my laptop has an issue.

So I called HP customers service again, and told them the whole truth and truth only. They assured me that it's still under 1 year warranty, and I can safely ship it over for a fix. Cool, life is sweet. Not so fast. Later I am receiving a phone call from HP - "our technicians have discovered traces of a liquid spillage on the keyboard... spillage is not covered, so as a general test/fix it will cost you $650 or more."

WHAAAAT?! You gotta be kidding me. $650 for a keyboard replacement? And why did you have to "investigate" when I said it in plain English what happened when opened the support case. Hallo, are you insane?! No thank you, give it back to me and I will handle the situation. The technical support manager kindly agreed that as a person she understands me, but these are the rules. Also I was warned that if I plan to open the computer, the remaining warranty will be voided, and only HP certified technician should perform the replacement. Right. Keep the warning in mind, we'll get to it later.

Next step (besides cursing) - eBay. HP Pavilion dv96XX keyboard, $30 including shipping. Done. A week of waiting and it arrived.

Next step - Google. Quick search brought a few useful results, especially the one at http://www.insidemylaptop.com. Folks, thank you so much for putting all the information online.

Final step - quick (about 10 minutes with no rush) operation on laptop itself. Done. But wait a second, the screw holding the keyboard from beneath (mounting screw) is missing. Oh, now I get it, those were the HP certified technicians. Aaaa, now I see. You have to be HP certified to do some sloppy job and screw hardware. Clear as mud.

Morals of the story

  1. Extended warranties / service plans - don't get those from retailers, rather consider the one from manufacturer, and even then think twice
  2. If as a customer you get screwed, don't give up. Customer is always right, remember that
  3. Don't blindly assume that people that are suppose to know their job will necessarily do it proper, especially if you are going through layers on indirect communication
  4. Don't be afraid to experiment. A good saying tells "Who's not taking risks does not drink Champaign".    

(Some pictures of the patient before and after the surgery)

 301020080182810200801730102008020

Posted by Sean Feldman | with no comments
Filed under:

This is late news, but I really recommend listening to the podcast with Robert C. Martin on .NET Rocks! Decided to listen to this one as a result of the book have read a while ago, Agile Principles, Patterns, and Practices in C#. The guy who has spent over 30 years trying to figure out how to do software, has some ideas to inspire how you do things. Audience? Developers, managers, users. Anyone. This is a great content to listen to.

Posted by Sean Feldman | with no comments
Filed under:

Naming conventions is always brought up when a team is trying to standardize the way code is expressed. Tab size of 2 vs. size of 4, Camel case vs. Pascal case, blog opening on a new line vs. same line with expression, member fields prefixed vs. underscored vs. nothing, control names with Hungarian notation or without it. The list goes on and on. The truth is that this is really doesn't matter. I have learned to accept what team decides to go with and once you embrace the style it's all good. What really matters is the code being produces, not the size of the font it's printed in (well, probably not the best example, but you get the idea).

Testing is not an exception. Test code lives along with production code, yet we want to be able visually be able quickly identify it. Many individuals and team do it in various ways, but an interesting fact is that the influence of TDD/BDD has caused to be more "expressive". What I mean by "expressiveness" is the will to make it as close to the human language as possible to describe what are we testing and document it that way. I owe Mo a big one for giving me this insight and breaking it into small pieces so my tortoise brain could get it.

[Test]
public void ShouldGetTheNumberOfHoursFromDays() {//..}

The example is somewhat cryptic. Reading this think is painful, yet compliant with CLR naming standards. On the other hand, having underscores, spices up the name:

[Test]
public void should_get_the_number_of_hours_from_days() {//..}

Suddenly it's easier to read! Also the interesting part is that if we really wish, the test name now could be easily read by a home-grown utility and converted in some sort of documentation where underscores are omitted and readable sentences by human show up. Thanks to JP for entertaining with this idea during the course.

Now if we think about this, it makes even more sense to name this way test imageclasses (or specifications). Next screenshot makes it really easy to see the benefits of underscored naming convention for the testing purposes.

Note: I agree that seeing all when_* is a bit weird, but there are ways to get over it and make sure that the tested class footprint is left. TestsOnAttribute or custom ConcernAttribute would do it. I welcome any other suggestions that would be less configuration for the team and more of a convention.

Also it looks very natural to keep this type of style to the rest of the testing code. For your judgement:

result.should_be_equal_to(expected);

over

Assert.AreEqual(expected, result);

As our team goes through the adventure of maturing our own naming conventions, we are opened and welcoming any thoughtful advises you can share. What would you consider to be a good practice and solid way of doing things, what would be discouraged. We want to learn from your experience!

Posted by Sean Feldman | 2 comment(s)
Filed under:

As a team we have found ourselves in a very delicate situation where we had to make a group design decision and it was quiet an interesting experience. What happens if your opinion does not align with the decision? How do you express your opinion without suppressing others opinions, promoting your concepts without falling into the nasty habit of ignoring anything that is different?

You discus. Can't prove that what your idea is all about is the way to go, that means it's either not better or you haven't really tried to explain it to others so they would see the benefit and be convinced. Conclusion - take your time, step back, see what's going to happen, accept what the team has decided, and if you really thing that's not the way to march, start thinking of a better way to debate your case and have some solid proof of concept.

What's the noise about? Domain objects and contracts (aka interfaces) for those. As a team we have decided today to have contracts for all of our domain objects. Valid decision, that will keep consistency in our code, and tests (where the debate started). But why this was an issue, after all, isn't it a fact that contracts are good and promote healthy way of coding?

The answer is Absolutely. Yet why to have an artificial contract on something that is a contract on its own? Domain objects are contracts for the whole application from bones to skin. If any of these objects (contracts) is changing, it's not like swapping out a component that was coded to a contract, it's pretty much reviewing the whole application and touching the code. Naturally a doubt sneaks into your soul and the question bubbles up - then why do I have to have a contract for a contract?

As a team we run into mocking issue. Mocking would have required a solid object to have either a contract or methods/attributes defined as virtual to allow mocks proper creations (proxies), but due to the fact those were missing the virtual keyword, tests were really misbehaving. Using a simple Root Cause Analysis we've determined that it's the fault of the 'coding process' that allowed this whole issue to happen, and that having contracts in place would not let developers go the path of cracking what's wrong.

As a team we decided that despite the fact domain objects are de-facto the contracts, we still will use contracts to simplify the process of software development, and have conventions over configurations.

Posted by Sean Feldman | 2 comment(s)
Filed under: ,

I am extremely excited to be a part of a team that has deliberately decided to follow the Agile path and TDD way of producing results. Along with that I am learning myself tones.

As a team, the decision was made to use strict mocks to understand better what mocking is all about and how dependencies should be tested for interactions, but not the their state (i.e. don't test dependencies themselves within the tests that are exercising System Under Test). IMO while this is a valid and good way of grasping the concepts and wrap around the whole idea of mocking, this is not necessarily the best way to express tests. Once basic understanding is there, strict mocks should not be forced upon all the tests. Reasons? Personal reason for myself - it doesn't feel right. Once it doesn't feel right, question it, doubt it, dig for alternatives and a better answer.

After googleing for about 5 minutes and reading different types of posts and comments, I run into a post, where Scott Bellware commented in a few nicely formatted sentences what I was carrying inside as a doubt, but could not formulate and express as a stated fact:

image

Cannot disagree with the stated. The whole purpose of TDD is to drive out the design and behaviour of the tested subject prior to going into its' implementation details (intimacy). Strict mocking forces to plan ahead the internal process of achieving the final result, going into the needy greedy details of a concrete implementation. And if so, it's not much different from doing code first and later hacking a test to confirm what code is doing.

To play the devil's advocate role, we can say that by using the strict mode we "document" better what should be done. Are we? The only documentation we should really worry about is the behaviour of the component, final results, and the interaction with components it depends upon that contribute directly to the successful final result.

This may raise another question - maybe state base testing should be preferred to interaction based testing? With state based testing there's really no exposure of the intimate aspects of the SUT, therefore no coupling of test code to internal code design of the tested component and that's the way to go?

Either way, as a team we will have this resolved and get to the right answers. Would love to hear opinions, especially experiences from those that were in teams with heterogeneous unit testing / mocking skills.

Posted by Sean Feldman | 1 comment(s)
Filed under: ,

While reading Joshua Kerievsky book "Refactoring to Patterns" could not go silent about abuse of Singleton pattern he described. The question that was asked in the book "When is a Singleton unnecessary?" - "Most of the time". Honestly, I can recall at least a few times when I was sick with Singletonitis: different Utilities, Session related classes, Context related classes, Resources related classes, you name it.

From my own experience this is so true. While Singleton allows only one instance of a class (pro), it also makes testing virtually impossible, coupling components dependent upon Singleton to a concrete implementation (con).

Bragging about this would not be really pragmatic (and how a wise man has told me - be a bit more positive and thing will be great, so I am trying to do ;), so to make it more practical/optimistic, I am going to show how to keep the Singleton in place in order not to break the legacy code that cannot be refactored, yet allow the new code to break the hard-coded dependency and allow testing, using what I call a "Dynamic Singleton" (sorry, I do not remember the terminology from Michael Feathers book "Working Effectively with Legacy Code").

Lets assume we have a very simplistic application, that is leveraging a component to report the location of the hidden folder.

    static void Main(string[] args)
    {
      var component = new Component();
      Console.WriteLine(component.ReportWhereFilesAreHidden());
      Console.ReadLine();
    }

Component is dependent on a Singleton Utility that is used across the whole solution (all projects/layers).

  public class Component
  {
    public string ReportWhereFilesAreHidden()
    {
      return "location:" + Utility.GetHiddenFolderLocation();
    }
  }

Utility is a typical Singleton implemented the next way:

  public static class Utility
  {
    public static string GetHiddenFolderLocation()
    {
      return "somevalue";
    }
  }

What are the issues?

  1. No testing possible of Component due to tight coupling to Utility.
  2. Utility is not swap-able, i.e. hard-coded.
  3. Multiple locations depend on Utility and we are not going to refactor that code right away.

This is where I use "Dynamic Singleton". First, refactor the existing Utility and remove the static keyword from the class.

public static class Utility

None of the old code is affected by this change, due to the fact that the methods are still static. Next step is to "extract an interface from static part". This probably sounds stupid, since a tool like R# will not allow it, but pretend there would be an option like that, currently it's under ReSharper->DoItYourseld. Seriously, remove the static keyword from methods, and extract interface. Later undo static keyword removal from methods. The result is a contract:

  public interface IUtility
  {
    string GetHiddenFolderLocation();
  }

Utility can now have both static and non static versions of the methods, where non-static ones are enforced by the contract. The non-static version is going to be implicitly implemented.

  public class Utility : IUtility
  {
    public static string GetHiddenFolderLocation()
    {
      return "somevalue";
    }

    string IUtility.GetHiddenFolderLocation()
    {
      return GetHiddenFolderLocation();
    }
  }

First it looks like an issue, but it doesn't. If we use the instance of Utility as IUtility, then all the non-static are there (including Intellisense). The new code can use it either by direct instantiation and assignment to a variable of the contract type, or through some sort of container and dependency resolving mechanism (a better way of doing it).

  public class Component
  {
    public string ReportWhereFilesAreHidden()
    {
      IUtility utility = new Utility();
      return "location:" + utility.GetHiddenFolderLocation();
    }
  }

This code is ugly you might think. Agree! Lets make it a bit nicer (and sort-of ready for dependency resolving at the same time).

   1:    public class Component
   2:    {
   3:      private readonly IUtility utility;
   4:   
   5:      public Component() : this(new Utility()) {}
   6:   
   7:      public Component(IUtility utility)
   8:      {
   9:        this.utility = utility;
  10:      }
  11:   
  12:      public string ReportWhereFilesAreHidden()
  13:      {
  14:        return "location:" + utility.GetHiddenFolderLocation();
  15:      }
  16:    }

By adding a parameterized constructor we are allowing constructor dependency injection (aka DIP). Since we don't have a dependency resolver, a "poor man" version is going to fulfill that role.

So what do we have now? We have a static Utility that is used by the legacy that cannot be refactored due to different "political forces", and at the same time same utility being exposed as an implementation of a contract IUtility.

Another question that may raise is "what if I want the contract implementer to be a real Singleton, i.e. not to allocate resources or run expansive calculations more than once". Not sure why, but there are always things that are beyond current understanding of things, so lets do that as well.

Rather than instantiating a new Utility upon each default constructor call, we will leverage a static instance to do the work.

   1:    public class Utility : IUtility
   2:    {
   3:      public static readonly IUtility Instance = new Utility();
   4:   
   5:      public static string GetHiddenFolderLocation()
   6:      {
   7:        return "somevalue";
   8:      }
   9:   
  10:      string IUtility.GetHiddenFolderLocation()
  11:      {
  12:        return GetHiddenFolderLocation();
  13:      }
  14:    }

Line 3 is a new addition to Utility code.

   1:    public class Component
   2:    {
   3:      
   4:   
   5:      private readonly IUtility utility;
   6:   
   7:      public Component() : this(Utility.Instance) {}
   8:   
   9:      public Component(IUtility utility)
  10:      {
  11:        this.utility = utility;
  12:      }
  13:   
  14:      public string ReportWhereFilesAreHidden()
  15:      {
  16:        return "location:" + utility.GetHiddenFolderLocation();
  17:      }
  18:    }

Line 7 reflects the change.

Mission accomplished. Is it? I guess not until the soul can rest. And it will rest when the last usage of a static Singleton for Utility like classes will be removed.

And last, but not the least - was it worth to go through the troubles 'just-to-replace-a-Singleton'? Look at the code below and judge for yourself :)

    [Test]
    public void should_leverage_utility_to_retrive_the_answer()
    {
      using(mockery.Record())
      {
        Expect.Call(utility.GetHiddenFolderLocation())
          .Return("somevalue");
      }
      using(mockery.Playback())
      {
        var result = CreateSystemUnderTest().ReportWhereFilesAreHidden();
        Assert.AreEqual("somevalue", result);
      }
    }
Posted by Sean Feldman | 1 comment(s)
Filed under: , , ,

A good identifier for an entity is considered to be a number. A unique identifier for an entity, such as identifier that can be synchronized across multiple databases, is considered to be GUID. The only issue with a GUID is that it's generated on the DB side, and therefor has  a certain performance hit (an extra roundtrip to the DB to generate the GUID and let NHibernate know about it on insert of a new record). The alternative is to use a generator strategy guid.comb - a guid generated on the client side and as a result of that eliminate an extra roundtrip to the DB. The other benefit is that the value generated by this strategy is sequential, and therefore the GUID values are somewhat more traceable in terms of their order of creation.

A sample mapping file would look like this:

<?xml version="1.0"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
                   auto-import="true" 
                   assembly="Example.Domain" 
                   namespace="Example.Domain.Mappings">
  <class name="Message" table="Messages">
    <id name="Id" column="Id">
      <generator class="guid.comb" />
    </id>
    <property name="Text" />
  </class>
</hibernate-mapping>

Quick run generated these values:

2636fb13-a23d-4d2c-b5b5-9b2d016cb9b2    1st
81514f25-15c5-4a86-802d-9b2d016cb9b7    2nd
544746af-8749-4e4c-9b65-9b2d016cb9b7    3rd

Ideas on having a better strategy when dealing with IDs of GUID type?

Posted by Sean Feldman | with no comments
Filed under:

This post shows a good example of how to refactor your code to preserve Law of Demeter. Very clean and simple example. R# is there for the refactoring part, to make things less manual and friction free. As a reminder, Law of Demeter:

Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Or: Each unit should only talk to its friends; Don't talk to strangers.

Posted by Sean Feldman | with no comments

Enumerations are for enumeration. Obvious. Often, though, it's used also for some metadata knowledge. For example, an enumeration for gender might look like:

  public enum Gender
  {
    Male,
    Female
  }

Two options, simple. Now let's say I want to populate  a drop down list with these values and some meta data. It's simple when it's English (a proper enumeration value would mostly match the metadata, but not always), what about another language? Normally I would build a workaround this, to have a utility class that would get a gender value and based on it return the metadata for the required culture. Does the work, but leaves bad taste after.

This is where extension methods can make it nicer. I will not go for the cultures, but capital and lower cases, but culture solution should not be that different.

Gender is closed for changes, but we need to be able to 'extend' it's functionality without 're-opening' it. The next code snippet shows how to achieve the required functionality:

  public static class GenderExtensions
  {
    public static string ToNiceName(this Gender gender,
                              IGenderFormattingStrategy formattingStrategy)
    {
      return formattingStrategy.ToStringWithFormatting(gender);
    }
  }

In this case I used a strategy pattern for formatting. What is nice, is that now we can test the extension method, knowing that Gender is not something we should be testing at all, but the result of ToNiceName() method.

   1:    [Concern(typeof(GenderExtensions))]
   2:    [TestFixture]
   3:    public class when_converting_gender_to_string_with_strategy 
   4:                                      : SpecificationContext<Gender>
   5:    {
   6:      private string resultMaleCapitalized;
   7:      private string resultMaleLowered;
   8:      private IGenderFormattingStrategy capitalizedStrategy;
   9:      private IGenderFormattingStrategy loweredStrategy;
  10:   
  11:      protected override Gender EstablishContext()
  12:      {
  13:        capitalizedStrategy = Stub<IGenderFormattingStrategy>();
  14:        loweredStrategy = Stub<IGenderFormattingStrategy>();
  15:   
  16:        capitalizedStrategy.Expect(
  17:             strategy => strategy.ToStringWithFormatting(Gender.Male))
  18:              .Return("MALE");
  19:        loweredStrategy.Expect(
  20:             strategy => strategy.ToStringWithFormatting(Gender.Male))
  21:              .Return("male");
  22:   
  23:        return Gender.Male;
  24:      }
  25:   
  26:      protected override void BecauseOf()
  27:      {
  28:        resultMaleCapitalized = sut.ToNiceName(capitalizedStrategy);
  29:        resultMaleLowered = sut.ToNiceName(loweredStrategy);
  30:      }
  31:   
  32:      [Test]
  33:      public void should_return_string_formatted_according_to_strategy
                                                                   _rules()
  34:      {
  35:        resultMaleCapitalized.ShouldBeEqualTo("MALE");
  36:        resultMaleLowered.ShouldBeEqualTo("male");
  37:      }
  38:    }

I am still not sure how much this test actually tests the extension method, or more serves as documentation to what it should be doing, but personally find it a good way to make sure that tested only one thing, and the implementation of the rest get deferred to later. In this case strategies are dead simply:

  public class CapitalizedStrategy : IGenderFormattingStrategy
  {
    public string ToStringWithFormatting(Gender gender)
    {
      return gender.ToString().ToUpper();
    }
  }

So what it's good for besides the metadata? Allows OCP for enumerations, brings a cleaner syntax. If you happened to have another neat usages, welcome to share those.

Posted by Sean Feldman | 1 comment(s)
Filed under:

This is my goodbye post to Sunwapta, the company I spent 3 years with. Definitely, this was one of the most exciting experiences that have happened to me during my career as a software developer. People there have helped me to grow and mature, and for that I owe them my gratitude. I have learned tones. Thank you for keeping up with me and listening to all of the things I was bringing in. I hope when you run into code I had contribution to, it will bring up more of the positive thoughts and not the opposite. It is a bit sad to leave things not entirely finished, but I am more than confident that they will be done in the best way. After all, together we have done a long way and learned awesome things that not only made us better developers, but also taught that pounding in code is not everything that matters, but thinking, analyzing, constantly improving, and most of all, never settling on mediocre, always striving to better. 

I am stepping up to new challenges and moving to another company to gain more wisdom and hopefully contribute my knowledge. I can sense this is going to be an exciting journey packed with awesome challenges. So Cortex, here I come!

Posted by Sean Feldman | with no comments
Filed under:
More Posts