Red/Green/Refactor: a pattern for clean code that works, Part II (How, Where, When)

On the first part of this post I spoke of the concept of TDD, as well as the reasons for using it. But what about the way to apply it, and more importantly, the context in which it should be used? This second part will address those subjects.

Example: Visual Studio Unit Testing Framework

In order to exemplify a kind of unit tests used in TDD in a graphical way, I chose to develop a quite simple Tic-Tac-Toe solution in C#, using Visual Studio. The following image shows three tests for the Square class, which can hold only circles, crosses or empty spaces (simulating a Tic-Tac-Toe square).

image

The use of this unit testing framework (Visual Studio Unit Testing Framework) is quite self-explaining. There is a test class that holds tests methods, which can be executed individually or all together. Each test method shown here has an Assert method in the end, which is one way of defining if the method passes or fails.

Note that these tests were written before actually coding anything to the actual class; so, when going to code the required functions, the API has already been defined by the tests, and it’s quite easy to know what to do.

Another important thing to mention is that tests shouldn’t have any kind of correlativeness between each other, since they should act as individual testing units. Here this is exemplified by the fact that the instance of the Square class can have different names among the tests, and they’ll still work perfectly.

TDD, ATDD and Scrum

Since a key matter in TDD based projects is to know how to divide and prioritize development tasks, TDD is more effective in agile environments such as Scrum. Practicing TDD is a good way to deliver constantly (see Frequent Delivery in our company mindsets), so TDD and Scrum do benefit from each other.

Furthermore, mainly because of the last point in the benefits section of the first part of this post, it’s extremely important for the customer to have an active and appropriate role in constantly defining the direction of the project (he is the one that will consume the product, hence it is wise for him/her to participate in the decision making). So that’s where Acceptance Test Driven Development (ATDD) comes into consideration. ATDD is in fact a really interesting subject which deserves a post on its own and more, but just to mention the concept, it’s a methodology that implies writing Acceptance Tests, that become the criteria that the customer defines for his business requisites.

It’s important, though, that the role of the customer and the developer doesn’t overlap each other: in other words, the customer shouldn’t define specific implementation details (the how) as requirements, because the developer usually knows more about it; and the developer, on the other hand, shouldn’t decide on strategic external features (the what), since the customer knows more about his business.

(Ideas for this section have been taken from ‘Diseño Agil con TDD‘, a must-read free online book for Spanish-speaking developers interested on the subject)

Conclusion

Test Driven Development is a powerful methodology, that can bring outstanding results, especially in large, complex projects. Its benefits are best shown not when using it on isolation, but when combining it with the appropriate resources and organization.

Again, if you have any thoughts about what I’ve said, don’t hesitate to comment here.

Red/Green/Refactor: A pattern for clean code that works, Part I (What, Why)

During my training-oriented pair programming sessions with Martin Salias and Angel ‘Java’ Lopez (don’t miss the chance to read his blog), both extremely experienced and knowledgeable software specialists, the very single thing they focused in teaching me was Test Driven Development. Given the emphasis this software development technique was given in my training, it’s fairly evident that it’s something worth learning. But what is it about?

Introduction

Test Driven Development, commonly referred to as TDD, is a methodology for developing software, included in the Extreme Programming methodology created by Kent Beck. It focuses mainly on the following cycle:

  • A developer should write tests before actually coding the program functionality.
  • These tests should be carefully written to express the desired features for that solution. In order to check that, it is a good practice to make the test actually fail before writing any code.
  • After making a test, the coding should focus only on making that test pass.
  • Once the test has passed, the code should be refactored; that is, make it cleaner, more understandable, eliminate duplicity, but without altering its public API.
  • Then the new features to be designed must be expressed in another test, and the cycle will begin again.

TDD Diagram

This simple but powerful approach guarantees that the programmer’s concern for the implementation (the how) won’t interfere with his/her concern for the actual features the customer asked for (the what). In fact, even the architecture is subordinated to the functionality, and not the other way round. This leads to a series of benefits, that will be discussed on the following section.

Benefits

The main benefits developers gain by using TDD are:

  • Less number of defects. Since every single feature is expressed in a test, there is less space for undetected bugs in the final product. It’s very common that after implementing a new feature, another one starts to work improperly. By having a test for each feature, this can be known instantly, since the test for that feature fails.
  • More modularized and extensible code. Due to the methodology implied in TDD, the developers think of the software in terms of small units, and so this leads to smaller, cleaner and more focused classes, that in the end, can be more effectively reused.
  • The features implemented are only those that the customer needs. This is what I believe is the most important benefit of TDD. Since the coding is focused on passing the tests, and the tests clearly express the desired functionality, deviations from the requirements set by the customer are a lot less likely to happen. After all, what is the use of developing unnecessary features that weren’t asked for?

You can check this post by Matt Hawley for some interesting figures about TDD’s advantages and challenges. If you are further interested in this kind of studies, you could check this link.

(Ideas for this section have been taken from ‘Diseño Agil con TDD‘, a must-read free online book for Spanish-speaking developers interested on the subject)

This should cover basically what is TDD, and why it is good to use it. On the second part of this post I’ll speak about how, when and where to use it.

If you disagree with anything I’ve said, you think something can be improved, or you just want to comment on the subject, please don’t hesitate to write a comment here.

Tobias Mayer: Ideas from a change agent

Last week we had a really interesting visit. Tobias Mayer came to our headquarters, where he acted as the facilitator for a series of agile workshops we hosted, organized by Agilar. On Friday he gave a talk in which he spoke about his personal experience as well as his vision on Scrum.

image

Then he kept speaking in an informal conversation, where I had the privilege of talking face-to-face with him.

image

Here are some concepts I found interesting about it. They cover some fundamental aspects of scrum, as well as some mindsets for effectively reaching the necessary creativity to succeed in complex environments such as working with emerging technologies.

  • At first one might do some different, seemingly unrelated activities; then at some point in our life we experience an ‘aha’ moment, and we combine your passions into a task in which we unleash a large amount of creative energy.
  • People neglect change, because it initially implies suffering, getting away of the ‘comfort zone’. For example, Tobias told us an example of a company making changes to its culture in order to implement scrum, which is an extremely complex process. He then said that in such cases, scrum can be applied, since scrum is effective for complex problems.
    image(This diagram was inspired on Ken Schwaber’s book ‘Agile Project Management With Scrum‘ p5.)
  • Adding constraints or rules can boost creativity to an unimaginable level; sometimes, changes must be done just to keep the spirit of change, keep the team alive (Idea from Martin Salias).
  • If one can’t apply the traditional approach to complex/chaotic development processes, then we must redefine our approach, expectations, and mindsets, and we will increase our chances of succeeding. ‘If you can’t succeed, then redefine success‘.
  • “Don’t sell scrum, do scrum; because scrum done well sells itself“.
  • Scrum principles don’t transmit an answer itself, but rather a way of thinking than will lead us to reach our own answers. It gives us a set of rules, a framework, which we then implement in a different way, depending on the changing context and needs of the company where scrum is being implemented.
  • Scrum divides complex problems in chunks, optimizes from the small.

Since here at Southworks we do work a lot with complex emerging technologies, it’s understandable that using Scrum helps us greatly increase our productivity and creativity in serving our customers’ to their highest expectations.

The 7 Habits of Highly Effective People: Part II (Southworks’ culture)

Now it’s quite clear that this book is worth reading. And, as Mariano Szklanny wisely said in his blog post:

Technology is a key part of culture, but technology on its own is not enough.

So it seems evident that reading a book that reflects our culture is a good idea. But why ‘The 7 Habits’?

Easy to work with

The very core mindset shared among Southies is to be easy to work with. This implies fundamentally an open communication flow, which results in a better understanding of the clients and partners’ needs in every stage of the business. As stated in of our values:

We desperately strive for understanding our customers and partners’ needs and for exceeding those needs and expectations by appealing to cutting-edge technology.

In order to achieve this, it’s important to seek first to understand and then to be understood. This way, before defining the guidelines for our activities, we focus on deeply understanding what the client really wants to be done; we take implicit assumptions as explicit quality requirements, and this is reassured by constant, fluent communication with the client.

Our people

Another point of coincidence with ‘The Seven Habits’ is the focus on people and relationships. A high level of teamwork allows us to benefit from creative cooperation to its highest degree: the performance of the team is considerably higher than the sum of the individuals’.

The fundament or basis of these synergistic contributions lay on the pride of workmanship (another important mindset we have), which guarantees that pursuing the integrity of every individual is a high priority.

Inside out

The fact that I have read this book as a part of my training reflects, in my opinion, an inside-out approach. In order to productively contribute to the company, first I must develop my personal and professional abilities; the company, then, develops itself constantly to serve the customers to their highest expectations. This is pursued with a long term, win-win mentality, keeping honesty as the center stone, which is what I think made Southworks reach where it is now.

I personally believe deeply in learning and constantly seeking improvement, so I’m relieved to find so many people who share this thought here!

Again, if you have any comment or suggestion about it, they’re highly appreciated~

The 7 Habits of Highly Effective People: Part I (Overview)

Speaking of books that can change your life… I’ve just finished reading ‘The 7 Habits’, by Stephen Covey. Before actually starting to read the contents of the book, I took a quick glimpse at the chapters (I’m quite sure I’m not the only one who does that), read a few summaries, and then I knew it was going to change my views to a certain extent. To my great surprise, it ended up affecting me in a deeper way than I thought. But why?

stephen-covey-7-habits-of-highly-effective-people

What makes this book special?

Initially, the word effectiveness, understood as getting better results, suggested that the book would explain some methods or techniques shared among highly effective people, which is quite a recurrent subject in this kind of books (I mean, who doesn’t want to get better results?). Chapter names such as ‘Be Proactive‘, ‘Put First Things First’, ‘Synergize’ reinforced that idea. In fact, they sound like techniques, but they’re actually mindsets.

That is what makes this a great book. It doesn’t deal with task-specific superficial techniques, but it proposes a whole new paradigm of thought, based ultimately on the idea that even though you can’t always control external stimuli, you can decide how things affect you, and then decide how to respond, following your deeply instilled values.

I won’t make a summary of the whole book, since it’s already been done thousands of times (there’s a nice, brief summary on the second paragraph of this great post by Damian Schenkelman), and it would make this post larger than you and I would like it to be. Instead, I’d like to highlight some concepts I found throughout the book, which made the greatest impression on me.

Private Victory

Something I really like about this book is that it focuses on the long term, but with a particular approach. It says that if you dedicate enough time to important but not urgent things, you will develop a production capability that in the end, will have a great impact on your productivity, and will free you from the overwhelming pressure of important and urgent things, as these are mostly going to be taken care of beforehand. Managing the balance between production and production capability is a key ability to be effective in every task that can be done. By speaking of balance it assures that you don’t need to completely sacrifice short term productivity in order to achieve long term success.

This often involves knowing how to say no to unimportant matters; that is, in order to find time to do those vital important but not urgent things, you must abandon some unimportant activities. This seemingly difficult task needs two things: first, you have be sure what exactly is important for you, so your objectives must be clear to you; then, you must have the inner strength not to succumb to the temptation of doing unimportant things due to external pressure.

That is the general idea of the Private Victory, which is the key of achieving independence. But that’s not all that matters, as we live in an interdependent reality.

Public Victory

In order to benefit from the great results of effective, creative cooperation, one must first recognize the importance of relationships. Indeed, if you prioritize long term results, it’s a lot better to establish a lasting, mutually beneficial, trust-based relationship than to ‘force’ someone to do something by using techniques, recurring to your position, and so on.

In order to truly form this kind of relationships, one must understand other people before trying to make your point understood. This is absolutely essential, not only to foster fruitful interactions, but also to enrich your views with other people’s ideas and experiences. If you take the time to actually listen their ideas openly, instead of thinking only of what you’re going to answer, you’ll be surprised to find how many times this brings your thoughts to a higher level.

But being open usually leaves you in a vulnerable state, so you must be strong enough to face that risk. The source of both the strength required for that openness and the skills necessary to have effective relationships must be your integrity, and your inner sense of security and worth, which must come from inside, not from the ’social mirror’. People value that integrity, and if you try to bypass that by using techniques or something, they sense the duplicity and it’s impossible for them to trust you. Public victory is based on trust, cooperation and understanding, and as you imagine, it’s the key of achieving interdependence.

That is, basically, what I think the message this book communicates is about. In the following post I’ll explain how these ideas relate to the culture inside Southworks, and why I think I was given this book to read.

Programming Practices for Self-learners

It’s a fact that lots of developers’ first steps with programming are self-learning, trial and error experiences. It’s not that I think it’s wrong; in fact, I myself followed that approach. But there are certain risks that come from learning to program on your own. This post will try to address them, and help those who are starting to program to follow the right direction.

Before going into to the actual recommendations, I should note that this post was inspired on reading ‘Microsoft Visual C# 2008, Step by Step‘, and so, some of the practices mentioned only apply to C# and similar languages. Nevertheless, I’m going to organize them from the general to the specific, so if you program in a different language, you can skip the specific parts; or, you could take this as a nice chance to learn some facts about these kind of languages.

A very common misconception many people have when they start programming is that the only necessary aspect of a program is that it functions. That’s wrong. In most real-case scenarios your program will not only have to work, but it will also have to be readable by other programmers, extensible in the future, and as efficient as it can be.

In this context, it’s advisable to follow certain guidelines about formatting and documenting:

  • Document your code. This as first may be seen as a waste of time, but you won’t think the same if you look at your code some months later. This is even more important if someone else will be reading your code. At least you should try to comment it.
  • Be consistent with formatting. Although it isn’t necessary to follow a specific formatting criteria, it does make a difference if you follow the same conventions all along your code. It makes it a lot more understandable.
  • Use descriptive names for identifiers. It’s wise to name a variable, method or whatever identifier you may use with a name that somehow reflects its function, so that it’s easier for you or other person to know why it’s there and what it does. Also, it’s not recommended to name two identifiers that differ only in case, because the resulting solution won’t be able to be reused in case insensitive languages.
  • Use an appropriate notation for identifiers. There are certain widespread notation conventions that most programmers share. It’s not that they are better. But everyone happens to use them, and so it constitutes a good way of making sure other people understand what you code. For example, in object oriented programming it’s common to use camelCase notation for private fields, and PascalCase for classes, public methods, and so forth.
  • Use parenthesis even if it isn’t strictly necessary. Even though it’s good to know the precedence, associativity and order of evaluation of operators, it’s better to write parenthesis anyway, not only to avoid mistakes, but also to make clear your intention when writing that operation to other people that may not be familiar with those rules.

Now shifting more into the concern of the actual functionality:

  • Separate the logic from the design. It’s a good practice to separate the actual business logic of your program from the user interface, so that modifying or even replacing one doesn’t alter the other. This also increments testability. An interesting way of putting this into practice is to follow an architectural pattern such as MVC.
  • Separate the functionality from error handling. While you can make a method output an error message directly to the same place it outputs normally, it’s better to separate the detection and signaling of an error from its catching and handling. Try()…Catch() and Throw() statements, present in lots of languages, are useful to this purpose.
  • Use object-oriented constructions in object-oriented languages. Most things you can do with objects and classes can be done with procedural constructions; but that ‘emulation’ of object functionality should be avoided, since object-oriented programming is a lot more efficient in this context (that is, the language was designed to be used like that). An example of this is to use global variables sparingly, when applicable.
  • Be aware of memory consumption. While this may seem irrelevant in small programs, it’s important to keep memory consumption into consideration. For example, if you’re going to use an integer variable that won’t reach higher values than 255, use the byte type instead of the int type. You never know whether your solution will be further extended or integrated into another one, and hence memory consumption should be always a concern. This should be paid more attention in languages without garbage collection.

Finally, some things about common operations you usually do:

  • Be aware of types. If, for example, you would make 5/2 (5 and 2 being int types) in a typed language such as C#, the result would be 2, and it won’t throw any kind of exception, because the result of an int divided by another int will necessarily be of int type. So you should be careful with this. Furthermore, even when it’s possible, try not to mix types For example, when making operations between an int and a double, it’s better to explicitly convert the int to double type so that both operands are of the same type.
  • Overflowing and checked statement. If you’re making integer calculations very close to overflowing the type’s limit, remember by default it won’t throw an exception, at least in C#. So it’s advisable to use the checked keyboard whenever the calculation could overflow; but don’t abuse of this, since it hinders performance.
  • Increment/decrement operators in postfix and prefix form. The increment (++) and decrement (–) operators can be placed both after and before the target variable; the difference is the result the expression evaluates to. For example, if you have a variable named ‘number’ whose value is 5, and you evaluate ++number, it will return 6, but if you evaluate number++, it will return 5 (even though the variable itself was incremented). When using these operators in isolation, however, it’s good to stick to the same way, to make your code clearer (that way is usually the postfix form).
  • Short-circuit. When you evaluate two expressions with the AND (&&) and OR (||) logic operators, you must be aware of a feature called short-circuit, that makes the program evaluate the second operand only if it’s necessary. That is, if you’re using an AND operator, and the first condition is false, then it’s not necessary to evaluate the second one to know that the whole expression will evaluate to false. In this context, it’s advisable to put heavy calculations, or expressions that are less likely to vary as the second operand, so as to save the program from making unnecessary calculations.

Another thing worth mentioning is that, although in most cases you can actually code with notepad, it’s more efficient to use a programming environment such as Visual Studio. It may seem that you “learn more” by doing everything by yourself, but in the end these programs simplify repetitive tasks and make you avoid extremely common mistakes, so you can focus on learning what you really must learn.

Following these practices probably won’t alter the global behavior of your program, especially if it’s not a large solution, but it’s definitely worth the time, since it’ll increase the overall quality of your programming, necessary in order to productively work in teams to develop large, significant solutions.

If you have any remark, suggestion, or if you want to share your experience on the subject, please don’t hesitate to write a comment, they are highly appreciated.

My first impression on the culture inside Southworks

It’s fairly evident nowadays that software engineering is not a mechanical activity with only one possible outcome, but rather a creative process is implied as well.

With that in mind, it is expectable for the initial training process to be focused not only on the technical aspect of our formation as software developers, but also in the human aspect, as stated in Mariano Szklanny’s post. That is easily seen in the fact that the very first book I am beginning to read is “The Seven Habits of Highly Effective People” along with, of course, some technical programming books.

From what I’ve read of that book I can certainly say that it’s going to be helpful in both my professional and personal life. But what really does make a difference is that the technical and non-technical training is synergized as a whole integral training. There is no difference between them, as they are focused towards the same goal: quality in every aspect and stage of the process.

But, as Aristotle once said, “Quality is not an act, it is a habit”. And so, this approach isn’t followed only on the training process. The general work ambient is one of unobstructed information flow, open mindedness and a true desire to contribute. I can imagine it’s usual to have strict internal or external norms (such as ISO 9001), and to follow work methodologies (such as Scrum), but here the underlying source of the fulfillment of those standards are deeply instilled mindsets shared by everyone. The standards are guidelines and frameworks to channel the inner creativity and efficiency into productivity, rather than limits and minimum requirements. Again recurring to a quote, this time from Henry Ford, “Quality means doing it right when no one is looking“.

This, however, doesn’t necessarily imply that working here is easy. In fact, it really seems like you have to do twice the effort, because you are constantly working on a wider range of aspects, considering things most people usually don’t. But that’s the price of excellence, a price I gladly pay because I know I’m directing my efforts into the right direction.

.Net basics and C#

Last week I had a meeting with a Microsoft MVP, Martin Salias, in which he gave me an introductory explanation to the technologies I’m going to start using in Southworks. I’m very happy to be able to start my technical training with such a person, and I’ll make sure to put everything he teaches me to good use.

.Net Platform

He went over some history about the .Net Platform, and its role as an infrastructure that makes it possible to develop scalable, multi-platform applications in a variety of languages. The most remarkable features of the .Net Platform are the Common Language Runtime (CLR), and the Common Intermediate Language (CIL, formerly known as Microsoft Intermediate Language, MSIL).

Common Intermediate Language

It has been mentioned that .Net supports a variety of languages, such as C#, C++, Visual Basic.Net, and so forth; but in order to maintain interoperability, all the compilers of .Net applications related to any of these supported languages compile into a form of bytecode, which is in fact the CIL. It is the lowest level human readable code in the .Net Platform, and it can be thought of as a “generic” assembly-like code.

Common Language Runtime

Based on the Common Language Infrastructure, the CLR is a virtual machine that compiles the CIL code into native code, before actually running the program, or even progressively during runtime (which is known as Just In Time compiling). This step is important, because it allows the software developed in the .Net platform to be highly platform-independent. Not only programs written in different languages interact within the same environment as if they were written in the same language, but also a .Net based program can run in any device supporting the CLR, no matter which platform it was compiled in. In other words, .Net compilers create .exe and .dll files that look like normal compiled files, but the actual conversion into native code is done on the device that runs the program.

Base Class Library

The main purpose of supporting multiple languages in the .Net platform is for long time programmers to avoid abandoning the syntax and customs of the language they had been using for so long. So in this context, there is a large library of classes known as .Net Framework Class Libraries or just simply Base Class library (BCL), that nowadays groups most of the functionality of the .Net platform, and can be accessed by any .Net supported language. So now, the main difference between the several languages is just the syntax.

C#

In this context, C# is intended to be a simple, multi-purpose language that is greatly adapted to the .Net specifications and libraries, and is able to provide an interface to most of the .Net functionality. For example, C# doesn’t even have the capability of outputing text to the console, as this is comprised in the BCL.

I’m eager to keep studying this and I’ll post again as soon as I have learnt something interesting on the subject!

Hello Southworks!

Hi everyone!
Thank you all for the warm welcome! Especially to the ones that keep helping me learn so many new things.
I hope to be able to contribute in the developement, writing and every activity I can be of help soon.