Archive for August, 2013

As a continuation to my recent rant about the differences between programmers and developers and how programmers love to code and … well, everything it is mentioned in that post, I felt like sharing a little bit of fun I had with this stackoverflow question.

Since it had already been answered and actually there was a little debate going on about the pros and cons of the accepted answer I was about to close it and look for something else when I decided to have a little bit of fun and make the solution generic.

Not like it was difficult, after a couple of minutes I had this:

    public class PropertyValidator
    {
        public bool Validate<T, TResult>(IEnumerable<T> list, Func<T, TResult> expression)
        {
            return list.Select(expression).Distinct().Count() <= 1;
        }
    }

But the fun didn’t end there, since this was not needed in what I was working on I had to demonstrate that it worked by other means, what could those means possibly be? You guessed it, unit tests!

    [TestClass]
    public class SameValueInPropertyValidatorTests
    {
        private PropertyValidator _validator;

        [TestInitialize]
        public void Initialize()
        {
            _validator = new PropertyValidator();
        }

        [TestMethod]
        public void ReturnsTrueIfListIsEmpty()
        {
            var list = new List<string>();
            Func<string, string> expression = x => x;

            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForStrings()
        {
            var list = new List<string> {"1", "1", "1", "1", "1", "1"};
            Func<string, string> expression = x => x;

            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForStrings()
        {
            var list = new List<string> { "1", "1", "2", "1", "1", "1" };
            Func<string, string> expression = x => x;

            var result = _validator.Validate(list, expression);

            Assert.IsFalse(result);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForKeyValuePair()
        {
            var list = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("any1", 1),
                new KeyValuePair<string, int>("any2", 1),
                new KeyValuePair<string, int>("any3", 1),
                new KeyValuePair<string, int>("any4", 1),
            };

            Func<KeyValuePair<string, int>, int> expression = x => x.Value;

            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForKeyValuePair()
        {
            var list = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("any1", 1),
                new KeyValuePair<string, int>("any2", 1),
                new KeyValuePair<string, int>("any3", 456),
                new KeyValuePair<string, int>("any4", 1),
            };

            Func<KeyValuePair<string, int>, int> expression = x => x.Value;

            var result = _validator.Validate(list, expression);

            Assert.IsFalse(result);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForEnumProperty()
        {
            var list = new List<Car>
            {
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
            };

            Func<Car, Colors> expression = x => x.Color;

            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForEnumProperty()
        {
            var list = new List<Car>
            {
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Black},
                new Car {Color = Colors.Red},
            };

            Func<Car, Colors> expression = x => x.Color;

            var result = _validator.Validate(list, expression);

            Assert.IsFalse(result);
        }

    }

And since we were on a roll, why not remove the duplication by creating generic methods to assert the results:

    [TestClass]
    public class SameValueInPropertyValidatorTests
    {
        private PropertyValidator _validator;

        [TestInitialize]
        public void Initialize()
        {
            _validator = new PropertyValidator();
        }

        [TestMethod]
        public void ReturnsTrueIfListIsEmpty()
        {
            var list = new List<string>();
            Func<string, string> expression = x => x;

            AssertIsTrue(list, expression);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForStrings()
        {
            var list = new List<string> { "1", "1", "1", "1", "1", "1" };
            Func<string, string> expression = x => x;

            AssertIsTrue(list, expression);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForStrings()
        {
            var list = new List<string> { "1", "1", "2", "1", "1", "1" };
            Func<string, string> expression = x => x;

            AssertIsFalse(list, expression);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForKeyValuePair()
        {
            var list = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("any1", 1),
                new KeyValuePair<string, int>("any2", 1),
                new KeyValuePair<string, int>("any3", 1),
                new KeyValuePair<string, int>("any4", 1),
            };

            Func<KeyValuePair<string, int>, int> expression = x => x.Value;

            AssertIsTrue(list, expression);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForKeyValuePair()
        {
            var list = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("any1", 1),
                new KeyValuePair<string, int>("any2", 1),
                new KeyValuePair<string, int>("any3", 456),
                new KeyValuePair<string, int>("any4", 1),
            };

            Func<KeyValuePair<string, int>, int> expression = x => x.Value;

            AssertIsFalse(list, expression);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForEnumProperty()
        {
            var list = new List<Car>
            {
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
            };

            Func<Car, Colors> expression = x => x.Color;

            AssertIsTrue(list, expression);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForEnumProperty()
        {
            var list = new List<Car>
            {
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Black},
                new Car {Color = Colors.Red},
            };

            Func<Car, Colors> expression = x => x.Color;

            AssertIsFalse(list, expression);
        }

        private void AssertIsTrue<T, TResult>(IEnumerable<T> list, Func<T, TResult> expression)
        {
            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }    

        private void AssertIsFalse<T, TResult>(IEnumerable<T> list, Func<T, TResult> expression)
        {
            var result = _validator.Validate(list, expression);

            Assert.IsFalse(result);
        }    
    }

Not exactly a break through discovery or even a coding kata but still it was a cute exercise for me to kill some time.

Would you like to share your favorite exercises or your sources of inspiration for coding research? I’d love to hear about them.

I dare say that the people who are kind enough to read this blog already know that I am a little freakily fanatic about unit testing. Believe it or not I do have a lot of experiences in which having unit tests in the code I was modifying saved me from doing very stupid and embarrassing mistakes and I want to share a very recent, although small, example.

For the past month I have been getting into Single Page Application development, better known as SPA and I find this book to be quite insightful. Anyway, when I read technical books I like to code all the examples and make sure they run as the book claims they do, I find I learn better that way. On the very first one, after coding a very large portion of JavaScript, I fired up the browser and … well nothing happened. I looked at the browser’s console and there were no errors whatsoever. To make a long story short I spent almost an hour reviewing and comparing the code to the book line by line, even with the downloaded code which worked. File comparing tools were not helping at all and it was a quite frustrating hour.

Finally I realized I had a typo in the following line:

var result = modal.$container.height === newConfig.heigt;

It was so subtle! Of course the newConfig object did not have a “heigt” property so its value was undefined, which of course is different that whatever value the height property in the container had and so the result was always false.

Of course I do not pretend that we should be writing unit tests for the code we copy from technical books. My point is that in a real project this kind of errors in a language like JavaScript could not only happen but cause to waste a lot of debugging time. All this time would be better spent writing a unit test that would immediately fail and point you in the right direction so the typo is found quickly and corrected, before it even reaches QA, UAT or, God forbids, production.

Because of what’s going on in the software development industry with things like mobile development and SPAs, JavaScript is gaining a lot of importance so we better start to get used to the idea, not only that we’ll be coding a lot more with this language but that we need to be concerned at unit testing that code too.

Recently I read a blog post that discusses the differences between a programmer and a developer. After reading the first couple of paragraphs my first reaction was to think that I consider myself to be a programmer but, because of all the “inherent characteristics” that programmers must have, according to this definition, this thought was very short lived.

The first characteristic that is discussed about programmers is that they love to write code. Well, this is something that it is very easy to feel identified with. Not very many people who write code for a living do so without loving it, and those who do usually move on to other things in a relatively short while. Personally I love to write code and I am never satisfied with the end result, no matter how much work I put into it, I always have this nagging feeling that there are ways to improve it. I will confess that sometimes after the writing is done I stare at the overall solution and marvel at a piece of code that is elegant, simple to understand, easy to maintain, fully testable and, to a reasonable extent, covered in unit tests. Even though that, I still get the feeling that I could improve the work further but that does not mean I sometimes do come up with code that is still beautiful, even if I say so myself, and these characteristics that have been mentioned are my definition of beautiful code. Up until this moment I still complied with this definition of programmer.

The second characteristic is that a programmer writes code just for the mere pleasure of it, even if that code does not fulfill any particular need other than programmer’s needs. Even this makes perfect sense to me since we, as programmers, by writing code just for the sake of it we keep sharp, enhance our skills, feed our curiosity and encourage the everlasting search of the best way to implement something. How often do you just happen to be writing some random code and realize that what you are implementing, or the way you are implementing it, could be used to improve some code you wrote a while back or that it solves the problem in which you are currently working on? I bet this has happen more than once to you. This overall idea still made sense in making me put myself in the “programmer club”.

The next trait that a programmer has, according to the author, is that she knows how her code works so she does not need to write tests at all since she knows where the code might break and she knows how to avoid it. Wait a second, WHAT?! Are you serious? Are you trying to tell me that this is a trait and something to be proud of? Hell, no! Of course any programmer, or coder for that matter, can write code without tests, just like any manufacturer of any product you can think of can manufacture said product without any kind of quality assurance process and still every single manufacturing plant in the world ensures that their products comply with a minimum quality standard. In my book, anybody who aspires to have the noble title of programmer should go out of her way to make sure her code has a minimum code coverage that ensures that said code does what she intends it to do. Even if it is just an exercise, a kata, research something or an excuse to hang out with the computer and forget about society for a while.

So I kept reading and I got to the part where, as a programmer, the author would rather be in his study coding day and night without talking to anybody and having nobody talking to him and be able not to attend any meetings. So he says that real programmers are like geeky theoretical physicist locked up in university labs and who alienate themselves from all human beings. Wait, I’ve seen this before, oh yeah, right! He thinks programmers should be like Sheldon Cooper from The Big Bang Theory! Jokes aside, there are quite a few things to say about this but that will be on a later post.

Honestly this kind of stereotypical description of what a programmer should be is so 1980’s that I am very concerned that there may be a lot of people out there who still believe it. People who think they are doing Agile but in reality they are still doing waterfall with daily stand up meetings, people who claim to be professional programmers and in reality are just cowboy coders putting a huge amount of spaghetti code together that only they can change, and even then they cause a lot of regression errors in the process which they solve by entangling the spaghetti even more. There even is still people who refuses to learn the necessary techniques to go into these kind of messes and start to improve them even though there is a lot of literature available that discusses which techniques are those and how to apply them like this one and this one.

Seriously if you want to be called a programmer instead of a developer like the author of this blog suggests that is fantastic, but embrace the modern definition of it, learn, acquire, and apply the right set of skills and, most importantly, develop the right attitude required for the job, forget about this old school mombo-jumbo and become a proud professional programmer.