Brendan Enrick

Daily Software Development

What’s New in C# 6 - My Course on DevIQ

If you’re looking to improve your C# 6 code by taking advantage of the new features added into the language, I’ve got you covered. By using C# 6, you’ll be able to clean up your code, and make things more concise. This was one of the focuses in the design of C# 6. You can clean up and remove the clutter from your projects by taking advantage of C# 6. My C# 6 course on DevIQ will show you how to use these new features to improve the code you’re writing today. You already have the tools and capability, and now you can learn how to take advantage of it!

As a consultant, I’ve worked with developers in different companies, and I find that most organizations are barely using the features of C# 5 let alone using C# 6. When I talk at conferences, most people say they’re using C# 6, and they technically are using it. Their code is compiled using C# 6, but they’re not using all of the features or know how powerful they can be!

To help teams with this, I created a quick-start, What’s New in C# 6 course on DevIQ that will help you get started using C# 6!

What You Will Learn

In the course, you will learn about:

  • Property and Method Improvements
  • String Improvements
  • In-Line Code Improvements
  • Exception Improvements

 

Whats New In C# 6

There is no “ego” in “Agile Team”

Programmers are talented, smart, skilled professionals. We put in lots of our own effort to educate ourselves and stay up on current technologies. We work hard and we feel great satisfaction in our achievements. We donate our time to charities when the opportunity arises. We give back to our local communities. All things considered, there are a lot of really great programmers in the world.

I lead a team of software developers. Does that mean I am the “best” programmer on the team? Certainly not. It just means that I lead the team. As the leader of the team, it is my job to: inspire, encourage, trail blaze, and motivate my team to be the best they can be. So who is the best programmer on my team? I don’t know, and I don’t care. There shouldn’t really be a “best” programmer on the team. Everyone on the team is great and working hard.

A team that really meshes and works well together doesn’t let egos get in the way. It doesn’t matter if you’re a rock star developer. When you’re on the team, you’re part of the team. You might be the JavaScript expert, the master of SQL queries, or the guy who can refactor anything. When you’re part of the team, you should try to use your strength, but don’t let that interfere with the team’s flow.

WP_000518Sometimes it makes sense for a more experience developer to work with a less experienced developer. A common first instinct is that the senior person is mentoring the junior person, but it’s actually going both ways.

Each of the two developers is bringing a lot to the table. Their different experiences and views allow them to each approach the problems differently, ask different questions, and apply different, existing knowledge.

If either person’s ego gets in the way, it would prevent the 2-way knowledge transfer in addition to creating friction between them.

WP_000541One Developer and one Junior Developer can pair on a task and share knowledge. Does one act like the other one is just along for the ride? No.

Your pair partner, is watching your back, guiding the team, and keeping the pair honest. Which one does that job? Both. If you had one person drive the whole time, you’re not going to see the benefits of pair programming.

If you let your ego get in the way, you might not let the junior developer write any of the code. They may not know every library, every design pattern, or even the intricacies of the language they’re using, but those guys can write some great code.

I don’t know how the Junior Developers are on your team, but ours write great code and show a high level of professionalism in their work.

RichAndEricAnd sometimes you get a Junior Developer pairing with the Developer Intern. How the pairs split up doesn’t really matter. Who is working with whom doesn’t really matter. Each and every member of the team is bringing something to the table, and it is this interaction that is making the team as effective as it is. These two are as productive a team as any other pairing that we’ve got.

Someone is probably reading this and thinking I am crazy for letting a Junior Developer and a Developer Intern pair together. They’re good though, and they really get great stuff done.

We can accomplish a lot of stuff when our team works individually, however, we can accomplish a lot more as a group. You might be the “best developer” on your team, but if you keep thinking and acting that way, you’ll be missing out on a lot. I learn a lot when I pair with any member of my team. It doesn’t matter how much experience the person has. Everyone knows something I don’t, and no one approaches the problems exactly the same way I would.

There is no “Ego” in “Agile Team”, so don’t bring yours to an agile team and expect good results.

The Clean Coder Review

I recently read The Clean Coder: A Code of Conduct for Professional Programmers (Robert C. Martin Series), and it is one of the best books on software development that I’ve ever read. The book is a quick read from Uncle Bob Martin and is comparable in size to his similarly named, Clean Code: A Handbook of Agile Software Craftsmanship.

The book goes through many, many examples from the author’s development experiences. It has sample discussions between parties to explain points and really goes over professionalism in software development.

The Title

The impression I have about why the book is called “The Clean Coder” is mostly a play on professional developers wanting to have clean code. This doesn’t just mean the code, the code is included of course, but it also means that the whole coding experience and the whole project should be clean.

There are a lot of mistakes that developers can make, and the book is covering them and discussing how to keep things clean.

The Material

Without jumping into too much of the meat of the book, I will say that there are many things in the book that I’ve done before and don’t do anymore. There were some things mentioned that I’ve done recently, and I am going to make sure I never do again. There are some things in there that I’ve thankfully never done, and I hope I don’t ever do them.

The book focuses on a lot of bad situations, why these situations are bad, and how we should really be handling things.

Consider this book to be a guidebook of suggestions for how to act as a professional. For example, in the book’s discussion of estimation, instead of focusing on how to be more accurate with estimation, it covers how you should be estimating. This means that it tells you that you should be very clear about things being estimates, not to imply a commitment, and not to make commitments if you cannot meet them.

Controversial Points

The Clean Coder makes some recommendations that I am sure that plenty of people will disagree with, and the way some points are worded cause me to sometimes disagree as well, but I don’t think it really takes away from the value of the book.

One example of this type of suggestion is that you work 40 hours a week and then another 20 each week on improving your career, leaving 56 hours for sleeping and 52 hours for everything else. It’s presented as doing this makes you a professional and not doing it is not professional. What I disagree with is the definite amount of time. I think it’s important for people to work on their careers, but 20 hours is arbitrary here. Someone may get the same value out of 10 hours that requires me 30 hours. There also is no definitive line between professionalism and unprofessionalism. There are some gray areas, and I believe this would be one of them.

Some things in the book were kept clear that it’s how he works, and I took these as suggestions to learn how I work and make sure that I am evaluating a possible issue.

In this case, I am referring to a point on music. Some people listen to music lightly while programming. This is even true when pair programming. I sometimes like having a very light bit of background buzz from music while pairing. In this case, I keep it so quiet that we can still communicate easily. The book seems to be against music, since it distracts and changes the author’s thinking. For me, I think I don’t have this issue because my pairing partner prevents a change in thinking. I also try to listen to music with foreign lyrics or no lyrics at all. It also helps to not distract from the task at hand. The value here for me is that I should be evaluating and thinking about how I am doing things to make sure that something as seemingly inconsequential as music is not detracting from my work.

Meetings

One great suggestion made by Uncle Bob is that it’s OK to decline a meeting invite. I think that’s very important to understand. Unless you’re really needed in the meeting, you should try not to attend. Meetings take up time, and if it’s less important than your other work, you shouldn’t be attending.

I had a meeting I scheduled yesterday. I invited 8 people to that meeting. I made sure it was clear that if you had something to bring up, you should attend the meeting, otherwise your attendance was not required. We had 4 people in the meeting, and I think 1 of the attendees need not have been there anyway.

Trying

You should read the section on trying. It’s important not to try, and this book makes it very clear why. If you’re going to try, you’re making a commitment to try.

Mentoring

The first paragraph on the chapter on mentoring illustrates one of the biggest shortfalls of the software development industry. I owe a lot of my successes as a developer to the mentoring that I’ve received through books, blogs, and any other recorded sources of information I can get my hands on. I was also lucky enough to have a mentor and a role model to learn from as I became a better developer.

Summary

If you go in to this book expecting it to be a recipe for success, you will be mistaken. This book is fantastic, but it’s important to think and consider why it’s valuable. It is one developer’s experience as a developer.

From his own stories, he is a developer who has hit some pretty rough patches and made some terrible mistakes. That’s a good thing! It means that he has learned a lot!

While reading the book, I never felt like it was forcing his way of doing things onto me. It is presented in a great way to inspire changes in the developers who read the book. You don’t have to do the same things that he is doing, but try to consider what the right answer should be.

The examples are simplified for the book, and business are more complex than what is in the examples. The reader will need to adjust and make decisions, but that’s what you should be doing anyway. Think about being professional and doing what you should be doing.

This book has been on my intended reading list for a while, and now I am going to recommend it to other people.

Well done, Uncle Bob. Thank you for sharing your experience with everyone.

Combining Object Oriented Principles, Practices, and Patterns

Now that the dust has settled from the recent Software Engineering 101 event we put on in Cleveland, I figured I would repost some of the material I talked about. This means some of connections that I vocalized and supplement the material from the slides I used for Software Engineering 101.

Object Oriented Principles, Practices, and Patterns

My first talk of the day was on Object Oriented Principles, Practices, and Patterns in which I start by discussing some common principles of object oriented programming: abstraction, encapsulation, inheritance, polymorphism, and I added composition in for good measure, which of course isn’t on its own a principle, but I feel deserves to be mentioned as its own entity at that point.

I covered an assortment of good practices for software developers to follow. Since Steve Smith was following my talk with one on SOLID, so I didn’t take the opportunity to discuss the Open/Closed Principle, which states that your code should be open to extension and closed to modification. This means that you can add to the behavior of your code by adding new code and not modifying what you already have.

In my patterns section I covered two of my favorite design patterns: the Strategy Pattern and the Template Method Pattern. These two are great for discussing with people. They’re very similar yet very different; one encapsulates the structure of an algorithm and allows for modification of the details of the steps while the other focuses on allowing for different algorithms to be used interchangeably. Each uses polymorphism, abstraction, encapsulation, and inheritance. They’re simple to explain and demonstrate, and they’re also very powerful. This makes them great examples.

 

Combining Everything

When we combine these principles and some design patterns we can achieve some great things. The strategy pattern is one of my favorite patterns, because it is very useful and improves maintainability greatly. I use it often. It uses, abstraction, encapsulation, composition, polymorphism, and either inheritance or interface implementation. On top of that it also helps follow the Open/Closed Principle, increasing the ease for changing the behavior of an application when the requirements change.

In my talk I was asked a great question, “if I don’t know design patterns, how will I know what I don’t know.” In other words, how can you possibly select the correct design problem to solve a problem. I recommended reading learning plenty just so you’ll be more prepared. There are plenty of books, and you don’t always need “the best” solution. Usually a good solution to the problem is enough. Steve Smith chimed in with a great answer though, he suggested practicing coding katas, which will often solve problems using design patterns or at least good, worthwhile practices.

Expect Unique Exceptions

One too common programming practice that irks me when I find it in source code is throwing or catching non-specific exceptions. I believe firmly that it is important to fail fast, and exceptions are a great way to ensure fast-failing code. If you drag out a failure you can hide the initial issue or allow a process to continue after an error has happened. Using non-specific exceptions will also hide information. Failing quickly is important as is being able to respond correctly to an exception and track down the cause.

Steve Smith posted recently saying that one should not throw duplicate exceptions. He gave a great example of where people will check for two different cases and throw duplicate exceptions.

public void Foo(SomeClass someArgument)
{
if(someArgument == null)
{
throw new InvalidArgumentException("someArgument");
}
if(!someArgument.IsValid())
{
throw new InvalidArgumentException("someArgument");
}

// Do Real Work
}

Checking for null as well as custom validity is important, and you want them to be separate cases. The suggestion from Steve is that you give them unique messages or use a more specific exception to allow people to tell what caused the error.

public void Foo(SomeClass someArgument)
{
if(someArgument == null)
{
throw new ArgumentNullException("someArgument");
}
if(!someArgument.IsValid())
{
throw new InvalidArgumentException("someArgument");
}

// Do Real Work
}

public void Bar(SomeClass someArgument)
{
if(someArgument.Quantity < 0)
{
throw new InvalidArgumentException("someArgument",
"Quantity cannot be less than 0. Quantity: " + someArgument.Quantity);
}
if(someArgument.Quantity > 100)
{
throw new InvalidArgumentException("someArgument",
"SomeArgument.Quantity cannot exceed 100. Quantity: " + someArgument.Quantity);
}

// Do Real Work
}

I lean toward using unique exceptions for handling this. It allows for better handling of the result and less duplication of the code. For example in the method listed above instead of using an InvalidArgumentException when the Quanitity is negative, I could use a NegativeSomeClassQuantityException. For the second one I might use an ExceededSomeClassQuanityException with the following resulting code.

public void Bar(SomeClass someArgument)
{
if(someArgument.Quantity < 0)
{
throw new NegativeSomeClassQuantityException("someArgument", someArgument.Quantity);
}
if(someArgument.Quantity > 100)
{
throw new ExceededSomeClassQuantityException("someArgument", someArgument.Quantity);
}

// Do Real Work
}

This is great because my code isn’t concerned with how to format these exceptions. My code just passes the required information via constructor parameters and the exception knows how it should be formatted. The calling code can catch each of these exceptions if it has a special way of handling either one or through the use of polymorphism it can handle both of them.

We want to make sure that we inherit from a relevant exception as well, so we could use the InvalidArgumentException.

public class NegativeSomeClassQuantityException : InvalidArgumentException
{
public NegativeSomeClassQuanitytException(string argumentName, int quantity) :
base(argumentName, "Quantity cannot be less than 0. Quantity: " + someArgument.Quantity)
}

public class ExceededSomeClassQuantityException : InvalidArgumentException
{
public ExceededSomeClassQuantityException(string argumentName, int quantity) :
base(argumentName, "SomeArgument.Quantity cannot exceed 100. Quantity: " + someArgument.Quantity)
}

Working with Interfaces - Practical Uses

Expanding on an article I wrote a couple of years ago where I explained interfaces in C#, I’d like to explain why people should use interfaces. I received an email from a reader of my ASP Alliance article. He understands how interfaces work, but he’s trying to see why so many people are raving wildly about their greatness. His questioning of them is great, because it really is not obvious why interfaces are useful. Anyone who says otherwise is just trying to brag.

A couple of years ago, you wrote an article for ASP Alliance called "Understanding Interfaces." Once again, I saw how the code works, once again, I failed to see how it will benefit me.

Here's where everything breaks down for me: You create an interface with just method, property and event signatures. Then you inherit them in a class, recreate these same signatures and write the code to implement these methods and properties.

So I’ll start by mentioning that nearly all patterns, practices, principles, etc. in software development are based on code reuse. One of the most important reasons for code reuse is change. Developers are always responding to and creating changes. We must mitigate the risks of change, identify where changes will occur, and we must make changes.

Right about now you might be thinking, “but interfaces don’t reuse code. They just force you to implement new code. Using inheritance would be the way to achieve code reuse.” You ate technically correct. You understand how interfaces work, but you’re not seeing why we use interfaces. Interfaces themselves do not give us code reuse at all, however, they enable us to achieve code reuse.

Remember that I said that we must identify where changes will occur. Making this identification allows us to isolate changes thus mitigating the risks of changes and allowing us to make changes. Isolating the places that change also allow us the reuse the code which does not change, so by keeping some parts separate we can reuse others. The interfaces are for the places we can’t reuse the code.

Interfaces are “places of change”. Each implementation of the interface is a variation on how that required piece of the puzzle could have been implemented. This is contrary to how you’ll see a lot of interfaces used. It is sometimes difficult to see this as the behavior of interfaces, because people overuse interfaces.

As I see it, I could have saved a whole lot of time by not creating the interface in the first place! I mean, it's not doing any work. I still have to create the signatures in the class. Why on Earth do people praise these things and call them the answer to multiple inheritence? They don't do anything!

It is mostly true that interfaces don’t do anything. As far as being executable code is concerned an interface is basically just a worthless extra step, so why would we use them? Declaring an interface is like saying, “there is more than one way that this behavior could be implemented, but interactions with this behavior should be done this way only.” Having that common “interface” allows us to use any of these implementations interchangeably.

When to Use Interfaces

Some people would recommend that interfaces should be used everywhere. I’ve heard people say that no variable should be declared with a concrete type if it can be avoided. That may be a valid point, but if you’re just learning how interfaces can be useful that is a bad approach. If you don’t see value in interfaces, you will certainly not see the value of them when people use them everywhere. This washes them out and obfuscates their purpose.

Interfaces are used for logic which will have multiple or changing implementations. This means that we should use them in places where we will out of necessity have duplicate logic. Using the interface is what allows us to do this. Take a look at this code for composing a letter.

public string ComposeLetter(string recipientName, 
string messageBody, bool isFormal)
{
string messageText = string.Empty;
if (isFormal)
{
messageText += GetFormalGreeting(recipientName);
}
else
{
messageText += GetCasualGreeting(recipientName);
}

messageText += messageBody;

if (isFormal)
{
messageText += GetFormalSignature();
}
else
{
messageText += GetCasualSignature();
}

return messageText;
}

Notice how we have these flow control operators dictating how the code will execute. What will happen if we need to have a third option for greetings and signatures for family members? We might add another else-if or we might use a switch. Either way this code gets larger and changed every time.

However, if we identify the aspects of the code that are changing we can isolate them and mitigate the risks of changing the code by keeping separate the logic which has multiple implementations. Notice we have already used one form of encapsulation by keeping each of those pieces of logic in separate methods. The logic we haven’t encapsulated is the flow control.

We can create an interface for it. The best name I’ve got for now is IFormalityGenerator, which is not a great name, but it will do for now. I’ll create that interface with two methods: GetGreeting and GetSignature. Very simple interface. Now we can rewrite our method to look like this.

public string ComposeLetter(string recipientName, string messageBody, 
IFormalityGenerator formalityGenerator)
{
string messageText = string.Empty;

messageText += formalityGenerator.GetGreeting(recipientName);

messageText += GetMessageBody();

messageText += formalityGenerator.GetSignature();

return messageText;
}

We now just make the decision sooner and only once which implementation we are using. If this is a formal letter we will use the FormalFormalityGenerator. If it is casual we will use the CasualFormalityGenerator. Down the road when we create one for family members we can just go and create an implementation for the FamilyFormalityGenerator. We’ve made it so we create new code each time instead of going and changing the existing code in this method.

The power of an interface is in its ability to encapsulate the volatile aspects of a program and isolate that which can be reused more easily.

When Should You Comment Your Code

Comment your code when it is hard to understand or determine your intent, because your code is crap. Yep, that is pretty much the best time to comment your code. When I was in college I was told to make sure that I commented my code. I always wondered why. Now I know. Comments really tended to clutter things and make it less clear what I was trying to achieve. I’ve written plenty of comments, but I know that when I use a comment that it means my code sucks.

Comments take time to write, they take up valuable space, they add clutter, and they’re often out of date. So why do we write them? We write them because there is something confusing about some code. Or something that we need to tell future readers about the code.

I very much enjoy being reassured of the way I do things by the books I read. I’ve been reading Code Complete, and it makes me glad they I blatantly disagreed with the people who told me to comment my code. Why? Because the author of the book tells me the exact opposite. I’ve often used the phrase, “code should be self-documenting.” I am not sure from whom or from where I first heard that, but it also affirmed my belief about comments.

The proper use of comments is to compensate for our failure to express ourself in code. Note that I used the word failure. I meant it. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration.

Aside from the misuse of the English language, that is an excellent paragraph. I’ve never liked writing comments, and I doubt I ever will. It is interesting how some programmers swear by them. I think they are the same programmers who use single-letter variables, magic numbers, and hundred line methods.

I highly recommend reading through the best comments in source code question on StackOverflow.

Remember kids, anytime you feel the need to write a comment, fix your code instead. You’ll thank yourself down the road. You might be the future developer maintaining the code.

A few steps to follow. (These are the easy ones. Harder ones take more than a bullet point to explain and justify.)

  • Rename variables to more expressive names.
  • Extract methods so people know what you’re doing.
  • Extract classes to handle each responsibility.

The Joy of Removing Code

Removing code is one of my favorite activities. Isn’t it one of yours? As a software developer I strive to write less code. Sounds kind of funny, but what I mean is that I want the code that I write to be reused as effectively as possible. Having less code means that maintenance is easier. I can fix things faster, change things faster, find things faster, and figure things out faster.

This is a very good case of “less is more”, which is one reason why I love removing code. I really enjoy getting more or even equivalent work done with less code.

I just finished eliminating a constructor. Why? Well, it really was not needed. As it turns out there was a more appropriate constructor to use for the class. Not sure when or why the constructor was created, but it doesn’t really matter. I am fairly certain that nothing is using it after my removing it. Code still compiles. Tests still pass.

This does a lot of good things. It makes the class less intimidating by dropping the line count. It makes clearer which constructor to use when there are fewer of them. If I need to make a change to the constructor by either adding or removing a parameter for example there is only one place to do this now. Before there were two places.

I love writing code, but I also enjoy removing excess code. It just makes things simpler, which is exactly how I like things. I want my code to be just complex enough to work. When I am refactoring old code this is one of the best things to do. Chopping off all the bits and pieces of unneeded legacy code is progress.

Has anyone else removed any code recently they were glad to be rid of? Anyone eliminate any entire class libraries or anything cool like that?

“Do you want complexity with that?”

“No, thank you.”

Fast Beats Right, a Principle of Mediocre Programming

Steve Smith just posted an interesting set of anti-principles, anti-patterns, and anti-practices that make up mediocre programming. In the post one of the principles of mediocre programming that Steve mentions is,

Fast Beats Right (FBR) – It’s more important to get something done that probably works, or that works right now even if it will be hard to change later, than to spend time ensuring that it is correct or is well designed.

I think we’ve all seen people who code this way before. They’ll get the really quick, dirty solution in place. Steve also makes note of what he has experienced as management’s opinion of this behavior.

sometimes management may be OK with dictating that for a given feature or prototype, speed is more important than anything else

The really scary part here is that there are managers who think that faster == better. Some teams have programmers following this principle and the managers think those are the best programmers. Why? Well, that guy gets lots of new stuff done. These other guys don’t (because they have to clean up the crap the fast guy writes.) Sure, for any task that is small enough I can do the work really quickly without testing or structuring things correctly. However, it might not work for all cases. The code could be fragile. It is very hard to determine how well it will stand up. Down the road I might need to add on to that code, and it could be so bad that it needs to be completely rewritten.

I really hope that no one is stuck at an office where management believes that an FBR programmer is a good programmer.

Have you every worked with a coder like this? What was the opinion of developer from the management point of view?

How Coding Katas Can Help You

Here at Nimble Software Professionals one of the activities that we have started doing is coding katas. We do these to help hone our skills as software developers. We do them because we value continual improvement among our team. The importance of an ever-growing, ever-improving team is very important, and through constant training and reemphasis of these techniques we expect to be able to achieve this important endeavor.

As developers we are presented with problems we must work through on a regular basis. Solving these problems is easier if we know all of the theory and mechanics to help us along the way. Knowing design patterns helps, since these are patterns which occur often enough that there is a repeatable solution. You can also just be a programming genius, and that will also help.

So how useful is it to know a bunch of design patterns? Not very if you haven’t had experience using them. You will not see the opportunity to use it if you haven’t seen it used or used it. Through training and practice you will learn what works when and why.

A kata is about solving a known problem. The standard way to do a kata is to follow along with someone who knows how to solve the problem. Following along with someone will let you see how to solve the problem the correct way. This is designed to help you think and solve problems the same way as that known smart person solves problems.

That is a great approach, but I prefer doing that after trying to solve the problem my own way. This lets me get my own perspective on solving the problem first. I can then compare my thought process with the one of the kata leader. Perhaps I prefer something I did over something they did.

The kata should be repeated again later. This time you’ve done it before, so your new solution should be better. Once you finish once again compare with how the leader did it. Make improvements like this every time until you have either the same thing as the leader or until you’re satisfied with your solution. Once you reach that state you will still do the same kata, but attempt to repeat the same solution, so that the process for solving the problem is well understood. You want to know how to solve problems. You do not want to think about how to solve problems.

One of my favorite katas is the Bowling Game Kata. One of the reasons I like it is because my first time solving the problem I created a solution nothing like the one that the kata teaches. From the kata I have improved how I do things. In my first solution for it I violated YAGNI.

My solution worked very well, and if there would have been more development of the problem my solution might have ended up being “better”. But it is true that I do not know what might come for the project in the future my solution was not as good, and since then I have been training myself to not make the same mistake again. By following along with the kata I’ve learned to improve the development process I use.