Archive

Archive for the ‘Extreme Programming’ Category

Var is Better

June 18, 2013 Leave a comment
Ken
June 18th, 2013 | Ken Payson

Var is Better

In .NET 3.0 Microsoft introduced the var keyword. The primary reason for introducing the var keyword was to support anonymous types, but there are numerous benefits to using the var key word. I find that developers often still default to declaring variable types on the both the left and right side. Most of us have been writing code long before C# 3.0 and old habits are hard to break. But, there are reasons beyond habit that developers do not use the var keyword. Developers want their code to be readable and sometimes they believe that having the variable type visible on the start of the line helps the reader understand how the code works. I say that this shouldn’t be the case. There are situations that you cannot use the var key word. You cannot use it if you need to declare an out parameter. You cannot use it if you need the variable to be of an interface or a base class. You cannot use it for class variables. Other than these situations –

I say that using the var keyword is just better:
• Declaring variables with the type on the left hand side ex Widget myWidget = new Wiget() is repetitive. The compiler knows what the type of the variable is from the right hand side. (if you use the wrong type on the left you get a compilation error).
• With intellisense, you can always hover over the variable to see the type.
• It’s necessary to use var if you want to return an anonymous type.
• The var keyword makes your code look really neat with all your variable names lining up.
• The variable name, and the name of the function returning the value should tell you what you need know about the variable. You can use the extra space that you get by eliminating the type to give a more descriptive variable name.
• Using var makes it easier to refactor and maintain the code. Fewer things break when using var. If the right hand side changes. You don’t have to have to fix the left hand side also.
• You cannot say var foo = null because null is not a type. Using var makes it impossible to do the unnecessary initialization of variables to null. Now you have to set variables only when you have the correct value for them which is what you should do.

Ken Payson is a Software Engineer at LogicBoost an Agile consulting firm based in Washington DC.

Eliminating the Null Checks

June 18, 2013 Leave a comment
null
June 18th, 2013 | Ken Payson

Eliminating the Null Checks

Sometimes it feels like half the code in an application is concerned with checking if variables are null and yet still bugs come up as a result of null reference exceptions. What can we do about this? Is there a way to spend less lines of code worrying about null and more time worrying about the core logic of your functions? Yes there is and it’s simple – stop coding using null!
Stop assigning null to variables

Never “initialize” a variable to null. Only assign a value to a variable after computing what its value should be. Properties on objects can be null. Declared variables need not ever be null. If there is no value, there is nothing to be done with the variable.

Stop writing functions that accept and work with null values.

Null is not a value of any type. It is pointer. C# objects are reference types and are passed by reference. Value types can be made into nullable types, but unfortunately, it is not possible to take a reference type and say it cannot be null. This is a weakness of the type system. If you have a function that takes a string and you pass in an int, you get a compile time exception because there is a type mismatch. If you take the same function and pass in null it will compile. Why? It should be a type violation because null is not a string.

It is the responsibility of the caller to make sure that it is giving a function data. If the caller does not have a value needed by the function, it should not be calling the function at all.

The called function needs to know it has values to work with before proceeding with the core of its logic. If the developer cannot guarantee that the function will be called with good data (maybe because it is public api method) then the function should validate the input at the top of the function and throw an exception if the input values are null. If you are using .NET 4, the code contracts with contract preconditions work well for this. If you are below .NET 4 you’ll have to settle for writing if(myObject == null) { throw new ArgumentException();} If on the other hand, you can guarantee that your function will be called correctly, you may ignore the null checks all together.

Sometimes functions are written to take optional parameters. If the optional value is not supplied it is null. The function branches on whether or not the value is null in order to perform some additional piece of work. Functions written this way tend to grow and grow as new requirements come and more optional parameters and branching logic are added to the function. The better approach is to have overloaded versions of the function. Private auxiliary methods should hold common logic used by the over loaded methods to eliminate any code duplication. Now in the calling scope, we do not need to pass null into any method. We can call the version of the function that does exactly what we need.

Stop writing functions that return null values

The flip side of not taking in nulls, is not returning nulls.
If a function is supposed to return a list of things and there are no items to return, then return an empty list.
If a function is supposed to return a single item from some source, a database, cache, etc. and it is expected that the item will be found but it is not, then throw and exception. For example, if you are searching for an item by id, then in normal workflow, you will have a valid id and a match should be found. If a match is not found this is an exceptional case.
If a method might reasonably fail to be able to return a value then implement a TryGet version of the method that takes an out parameter and returns true or false. This is analogous to TryParse for integers or TryGet for dictionaries. In the calling scope, you will have something like this:

Widget widget;
If(TryGetWidget(someSearchString, out widget) {
//The widget will have a value. Do something with the widget
}
Else {
//The search didn’t find anything
}

Conclusion

It really is that easy to greatly reduce null checks and null exceptions from your code. Don’t assign null to variables and don’t write functions to take in or return nulls.
In general, it is the responsibility of a function to communicate its requirements and throw an exception if the requirements are not met. The calling scope has the responsibility of making sure that is passing acceptable values into a function and handle any exceptions that are thrown.

The ultimate goal would be to eliminate possible null from the entire call chain. If function A calls, function B, which calls function C and we know that function A never returns null, then we don’t need to check the values originating from A and going into C. Of course, in any real world system, there will be many places where methods you call may return a null. Don’t just pass these values along into the next function call. Stop the null chain.

Ken Payson is a Software Engineer at LogicBoost an Agile consulting firm based in Washington DC.

Working with XML Namespaces and LINQ

October 11, 2010 3 comments

Ben XML Namespaces

October 11th 2010 | Ben Yoder

Working with XML Namespaces and LINQ

While working on a project using LINQ to XML to parse a web response, I ran into an issue whereby my calls to get an entity’s Descendants or Elements were returning no results. It turned out that the specified response included a namespace. In this case you can’t use the common element name—you must get the fully qualified XName.

For example, given the following XML and LINQ Query:

    string xml = @"<Employees>
      <Employee>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
        <Id>1</Id>
      </Employee>
    </Employees>";

        XElement employee = XElement.Parse(xml);

    var employees = from e in employee.Descendants("Employee")
                        select new
                        {
                            Id = e.Element("Id").Value,
                            FirstName = e.Element("FirstName").Value,
                            LastName = e.Element("LastName").Value
                        };

The query works and the employees object contains John Smith. However if the XML changes, the query returns nothing:

    <h:Employees xmlns:h="http://www.w3.org">
      <h:Employee>
        <h:FirstName>John</h:FirstName>
        <h:LastName>Smith</h:LastName>
        <h:Id>1</h:Id>
      </h:Employee>
    </h:Employees>

After browsing through some MSDN documentation, I learned that I have to include the namespace in the query. I got the full name using XName.Get()

    XName root = XName.Get("Employee", "http://www.w3.org");
    XName firstName = XName.Get("FirstName", "http://www.w3.org");
    XName lastName = XName.Get("LastName", "http://www.w3.org");
    XName id = XName.Get("Id", "http://www.w3.org");

Replace the names in the LINQ query and it returns the correct results. Of course, there are other ways to accomplish this. You could create an XNamespace object based on the namespace string and prepend it to each element name in the query. Creating an individual XName object for each query parameter gets kind of verbose, so for more complex LINQ this is probably not the preferred way.

Ben Yoder is a Senior .NET developer at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

Code Challenge Results

September 16, 2010 4 comments

Thank you to all to those that submitted code solutions. We will be running another code contest in a few weeks. Check back soon to enter our next contest. Congratulations to our contest winner: Rob Howarth

See the bottom of this page for an example solution

Others who submitted correct solutions

  • Rob Howarth
  • Scott Monnig
  • Eric Haddan
  • Thomas Eyde
  • Imran Baloch
  • Marc Chu
  • Cesar Neves
  • Jaider Ariza
  • Kenneth Hall
  • Teymur Mammadov
  • Cam Luc
  • Peter Burrell
  • Anthony Clayton
  • Mark Lindell
  • Steve Smith
  • Chris McKenzie
  • Amit Parikh
  • David White
  • Ron Warholic
  • Josh Clark
  • James Baker
  • Richard Deeming
  • Erik Jõgi
  • MORRIS CRISTOPHER
  • Scott Holodak
  • James Curran
  • Marius Ene
  • Matt Crouse
  • Michel Grootjans
  • Daniel Griffie
  • Xiu
  • Mordechai Sandhaus
  • Stuart Cam
  • Raj Rao
  • Rafik Ramtoolah
  • Ali Derman
  • Eric King

Sample Solution

        public class Converter
        {
                public string Convert(int number)
                {
                        StringBuilder buffer = new StringBuilder();
                        int quotient = number;
                        int remainder = -1;
                        while (quotient != 0)
                        {
                                remainder = quotient % BaseNumber;
                                quotient = quotient / BaseNumber;
                                buffer.Insert(0, ConvertSingleBaseNumber(remainder));
                        }
                        return buffer.ToString();
                }

                protected virtual string ValidCharacters
                {
                        get { return "0123456789xyz"; }
                }
               
                private string ConvertSingleBaseNumber(int remainder)
                {
                        return ValidCharacters[remainder].ToString();
                }
               
                private int BaseNumber
                {
                        get
                        {
                                return ValidCharacters.Length;
                        }      
                }
        }

        public class BinaryConverter : Converter
        {
                protected override string ValidCharacters
                {
                        get
                        {
                                return "01";
                        }
                }
        }

        public class OctalConverter : Converter
        {
                protected override string ValidCharacters
                {
                        get
                        {
                                return "01234567";
                        }
                }
        }

        public class HexConverter : Converter
        {
                protected override string ValidCharacters
                {
                        get
                        {
                                return "0123456789abcdef";
                        }
                }
        }

Did you like this challenge? Maybe you found it easy? Were always looking for talented people to join our growing team. Take a look at what we do at http://www.thycoticsolutions.com/careers.html If you feel you have what it takes to work at Thycotic – submit a cover letter, resume, and solution to this problem to tddjobs@thycotic.com

Warm Turkey

July 22, 2010 3 comments

July 22th 2010 | Jimmy Bosse

Warm Turkey

In a recent post, “Cold Turkey”, my colleague Kevin Jones challenged developers to “try writing code for a day, even an hour, using notepad. Not Notepad2 or notepad++. Though you can cheat and use MSBuild to compile your solution. It might just change your idea of what good code is.”

I say poppycock!

Imagine being a patient about to go into surgery when your doctor explains that he will be removing your appendix without anesthesia or a scalpel. Instead, he’ll be getting back to his roots and will be using a knife and some leeches to demonstrate what good surgery is. Utter nonsense.

Tools like IntelliSense do not write good or bad code—they are used by good or bad developers. Should I be aware of the methods of the System.IO.File class? Absolutely. Should I be able to recall each of its 56 methods on demand? Absolutely not. Can I tell you the parameter types of each of the three overloaded signatures for its Open method? Nope again. Knowing this information by rote does not make me a better developer. It’s also a waste of my time, and to our clients (if you are a consultant like many of us developers) time is money.

Tools like IntelliSense are about efficiency, and to argue that it rots the brain is to argue that we should launch the space shuttle on the minds of brilliant engineers who insist on using the abacus.

Tools help good programmers deliver good software faster. I couldn’t write a post about essential tools without discussing ReSharper. I have on more than one occasion stated that, “I will never use Visual Studio again without ReSharper, ever.” I stand by that statement. I even saw a recent tweet by someone stating that they could do more coding with one hand and ReSharper than with two hands without it.

True, if you’re a bad developer, the tools are going to make you better—at writing bad code. There’s not much I can do about that.

Jimmy Bosse is a Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product. On Twitter? Follow Jimmy

Cold Turkey

March 23, 2010 8 comments

Cold Turkey

March 23rd | 2010

Cold Turkey

Recently I went on vacation. Being the developer that I am, this didn’t keep me away from doing a little coding. I was “forbidden” from bringing a work laptop, but I brought my personal netbook which had Office, Windows, iTunes, and a messaging client. One day I was asked to write a system tray application for someone who was moving from Windows XP to Windows 7, which was missing a feature from XP. It was easy enough to write, but I didn’t have my normal tool belt with me. All I was armed with was notepad, and the Visual Basic .NET Compiler. I’d be writing an application without my faithful tools. Cold Turkey.

The first thing I did was build a mini IDE: basically, a batch script that would compile my file and add all the assembly references. My only reference was MSDN which is rather slow in Belarus. I eventually ended up writing another program that used reflection to dump the classes of namespaces and the public members of classes.

This lead me to a blog post I read more than a year ago, “Intellisense rots the brain”. That got me thinking: Code quality should not be determined by your toolset. I thought back to my post on extension methods . My argument against extension methods was that you can’t tell the difference between an extension method and an instance method without the help of an IDE. Now the argument might be, “Kevin, you were using no tools at all. Isn’t that an unlikely case? I’ll always have my tools.” But then why strive to write good code at all? A tool shouldn’t be telling you how to write code.

So, I propose a challenge. Try writing code for a day, even an hour, using notepad. Not Notepad2 or notepad++. Though you can cheat and use MSBuild to compile your solution. It might just change your idea of what good code is.

Kevin Jones is a Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

Categories: Extreme Programming

The Danger of Single Responsibility in Programming Continued

November 19, 2009 6 comments

The Danger of Single Responsibility in Programming Cont.

October 16th 2009 | David Cooksey

The Dangers of Single Responsibility in Programming Continued

The Dangers of Single Responsibility, Cont.

Doug Rohrer responded to my initial post on this topic with a good refactoring of the classes involved in a manner similar to the Strategy pattern. I agree with many of his points—the hypothetical developer certainly chose the wrong responsibilities; misunderstood the Single Responsibility Principle; and generally made the code a mess. That said, I believe that SRP is most definitely dangerous, not because of what happens when it is used correctly, but because of how easy it is to get it wrong. Misapplying the SRP can result in code that makes God objects look easy to maintain.

For clarity’s sake, I’ll go one step further—it is easy to misunderstand the sentence “A class should have only one reason to change” as a literal commandment to be applied at the line or method level. This results in disaster. One common example of how the SRP is misunderstood can be seen in this thread, where the poster asks if the SRP means that each class can have only one method. Luckily the poster received a good informative answer, but that is not the case for all developers learning about the SRP.

Here is an example of code modifications I have seen motivated by a desire to apply the SRP.

BEFORE

public class Check
    {
        private readonly IDataProvider _dataProvider;

        public Check(IDataProvider dataProvider)
        {
            _dataProvider = dataProvider;
        }

        public bool Run()
        {
            IBusinessObject data = _dataProvider.Get();

            if (data.Condition1 && data.Condition2)
            {
                string message = string.Format("Check failed, {0} {1}", data.Property1, data.Property2);
                throw new Exception(message);
            }
            return data.Property3 != data.Property4;
        }
    }

AFTER

public class Class
    {
        private readonly IDataProvider _dataProvider;
        private readonly ICheckErrorMessageProvider _checkErrorMessageProvider;

        public Check(IDataProvider dataProvider, ICheckErrorMessageProvider checkErrorMessageProvider)
        {
            _dataProvider = dataProvider;
            _checkErrorMessageProvider = checkErrorMessageProvider;
        }

        public bool Run()
        {
            IBusinessObject data = _dataProvider.Get();

            if (data.Condition1 && data.Condition2)
            {
                string message = _checkErrorMessageProvider.GetErrorMessage(data);
                throw new Exception(message);
            }
            return data.Property3 != data.Property4;
        }
    }
public class CheckErrorMessageProvider : ICheckErrorMessageProvider
    {
        public string GetErrorMessage(IBusinessObject data)
        {
            return string.Format("Check failed, {0} {1}", data.Property1, data.Property2);
        }
    }

Here, the developer asked the SRP question “Does this class have only one reason to change?” and got the answer “No, it could change because the formatted text could change, or because the logic could change”, and refactored the String.format out into its own provider. While harmless on the surface, this artificial separation of concerns does not add any value. The new class is so specific that it cannot be used anywhere else. In addition, the developer is likely to forget the CheckErrorMessageProvider name almost immediately, so if a text change is required he will most likely go to the Check class first, and then go the extra level down into the string provider in order to make the text change. In other words, the complexity of the code was increased for no benefit.

I believe that after correctness, simplicity is the most important programming principle. Simpler code is easier to understand when first read; easier to remember; easier to test; easier to refactor; and easier to add features to. Anything that adds complexity makes all of these tasks harder, especially on larger projects with many non-trivial sub-systems. Applying single responsibility at the line or method level diffuses business logic into a cloud of tiny classes that do next-to-nothing individually, and thoroughly obscure the logic they represent.

In conclusion, yes, the SRP is not dangerous when applied correctly. But then, most things are dangerous because of what happens when they are misused, and the Single Responsibility Principle is no exception. Handle with care!

David Cooksey is a Senior .NET Consultant at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.