Code Smells : Object Oriented Abusers

While a well implemented Objected Oriented code is a hallmark of a good program, a poor implementation of the same could  lead to utter chaos as the project progresses. Object Oriented Abusers are a particular genre of Code Smells which refers to incorrect or incomplete implementation of Object Oriented Concepts.

Switch Statements

Switch Statements are something we are used to, it makes writing code faster. But does it make it easier to maintain ? Not really, in fact, switch is almost similar to if-else conditions, just that it is slightly more readable. Another issue with the Switch Statements (or for that matter the if-else conditions) is that it tend to mix logic and data together, which isn’t exactly the best way to do it. We would ideally want to separate the two, so that we can change them independently without interfering with each other. Each time the developer needs to change the logic or the data, he has a mess in his hands. Furthermore it is a violation of Open Closed Principle each time the developer needs to modify the cases to accommodate a new condition (or remove a condition).

The most frequent approach to solve this problem is known as Replace Conditional With Polymorphism, typically done using the Strategy Pattern. Variants of same, namely, Replace Type Code with SubClasses and Replace Type Code with State/Strategy can also be used. There could be situation where there aren’t too many conditions and all of them call the same method with different parameter. In this scenario, polymorphism just might be an overkill and better approach would be a Replace Parameter with Explicit Methods.

A special case that need consideration would be if one of the conditional options is null, wherein you could introduce the Null Pattern or Introduce Null Object.

Temporary Fields

There are times the developer decides to introduce Fields in the Class which are used only by one Method, instead of passing it as method parameter to avoid Long Parameter List. These fields sit idle in the class at all time, except when the particular method is used.

 

The way to tackle this particular type of code smell is using a variant of Replace Method with Method Object, ie, moving the entire method and its related field to a separate class. It would make your code much cleaner.

 

Refused Bequest

Another form of object oriented abuse, particularly inheritance, can be seen in derived classes, which doesn’t use most of the functionalities of the SuperClass. In fact, the SuperClass and SubClass is quite different form each other. These inevitably violates the Liskov Substition Principle. Consider the following example
public class BaseClass
{

public virtual void MethodA()
{
 Console.WriteLine("Do Something Usefull");
}

}

public class SubClass:BaseClass
{
public override void MethodA()
{
Console.WriteLine("Do Something More Usefull");
}
}
The above code is an example of Refused Bequest. The Child Class ignores the functionalities of Base Class (Refuses to implement SuperClass behavior) and Overrides it. Furthermore, This will also violate the Liskov Substitution Principle as the Inherited class cannot replace the BaseClass in a code without affecting the functionality.

 

The solution for this particular Code Smell lies on two different approaches, depending on the need of code. There might be a scenario where the Inheritance makes sense to a certain extend, despite symptoms of Refused Bequest, for example, it applies only to limited methods and data fields of super class. In such a scenario, Push Down Method  would be one of the refactoring technique you could opt for. Push Down Method recommends to move the method completely to the Sub Class as none of the sub classes uses the functionality provided by the Base or Super Class. The solution with Push Down Method applied would look similar to code below.
public class BaseClass
{

// Other used methods
}

public class SubClass:BaseClass
{
public override void Method()
{
Console.WriteLine("Do Something More Usefull");
}
}
A closely related technique would be Extract Super Class.

 

In certain other scenarios, the inheritance might seems purely superficial and the best approach would be to get rid of inheritance. That’s where Replace Inheritance with Delegation comes into picture.

 

Replace Inheritance with Delegation as the names suggests opposes the usage of inheritance when it seems like it is unwanted.  This approach suggests us to use an instance of the BaseClass and delegate the functionality to the instance, especially in scenarios when the Sub Class doesn’t require all the methods and data of the Base Class.

 

Alternative Classes with Different Interface

 The last type of Object Oriented Abusers we would be inspecting is known as Alternative Classes with Different Interfaces, which hints at a situation wherein two different classes seems to perform similar responsibilities, but have different interfaces (different method names, signature etc).

 

Such situation arises mostly when there is lack of communication between team members who end up developing similar classes, or when the developer fails to check the available classes.

 

The ideal approach towards treating this particular variant of Code Smell is by Renaming Methods or Moving Methods so that both classes end up implement the same interface. There would be other times when only a part of the classes are similar, leading to usage of Extract SuperClass.

 

Code Smells : Bloaters (Primitive Obsession, Long Parameter List, Data Clumps)

Primitive Obsession

If there is a code smell I often misses, then it has to be Primitive Obsession. Quite honestly, I have been guilty of falling for Primitive Obsession more than once. This particular type of Code Smell refers to the tendency of Developers to use primitive types instead of small objects for stimulating certain fields.  For example, one of the most common form of primitive obsession is usage of strings to represent Phone Numbers or Zip Codes.

 

Clearly, Phone Numbers and Zip Codes have their own formats and having primitive string to represent it would mean, you need to do additional checks (mostly repeated preconditions) in every method which utilizes it to ensure they hold the integrity needed by the stimulated object.  Instead, the Users could Replace Data Value With Object along with the associated behavior ( and validation checks).

 

Another possible technique associate itself when primitive fields are used in Method parameters. There might be cases when same group of parameters are used by more than one methods. Let’s consider the following code for example.
public IList GetBirthdays(DateTime startDate, DateTime endDate);
public IList GetAnniversaries(DateTime startDate, DateTime endDate);
public IList GetOtherLandmarks(DateTime startDate, DateTime endDate);
As seen in the above code,  two date time parameters, namely StartDate and EndDate are repeatedly used by 3 different methods. You could introduce a object here replacing the repeated parameters. The above code could be rewritten as following

 

public IList GetBirthdays(DateRange Dates);
public IList GetAnniversaries(DateRange Dates );
public IList GetOtherLandmarks(DateRange Dates );

 

This technique of Refactoring is known as Introduce Parameter Object as observed by Martin Fowler. Another technique related to primitive parameters being used as Method Parameters is called Preserve Whole Object. Consider the following code.

 

var employeeID = employeeInstance.GetEmployeeID();
var employeeDepartment = employeeInstance.GetDepartment();
var employeePaymentDetails = payment.GetPaymentDetails(employeeID, employeeDepartment);

 

Instead of calculating individual fields like employeeID and employeeDepartment, and then passing it to the GetPaymentDetails method, you could pass the employeeInstance object instead. This works in treating Long Methods  as  well.

 

The advantages of staying away from the Primitive Obsession include increased flexibility of code and well organized code. You have centralized place to maintain operations and conditions related to the particular data type. Also, it becomes easier for a future developer who doesn’t have to spend time guessing the limits/conditions related a particular data type.

 

Long Parameter List

How often have we ended up working with Methods which require more than 5 parameters ? Even harder would be existing code which utilizes a method which has many parameters. Remember, developers spend a better part of their development time reading existing code rather than creating a new one. So the implication of not writing easily readable code is quite large.  At least with .Net we do have Named Parameters which increases the readability a bit but at the end of the day, a method with 3 or 4 parameter is always easier to work with than one with 5-8 parameters. Ideally, anything more than 3 parameters for a method is a good candidate for refactoring.

 

So what are the effective refactoring techniques that could treat this particular kind of Code Smells.  We  have already discussed two earlier in this very blog post – Introduce Parameter Object and Preserve Whole Object. These two methods are effective in reducing the number of parameters used in a method.

 

A third technique, known as Replace Parameter with Method Call involves something similar. Consider the following code.

 

var employeeID = employeeInstance.GetEmployeeID();
var employeeDepartment = employeeInstance.GetDepartment();
var employeePaymentDetails = payment.GetPaymentDetails(employeeID, employeeDepartment);

 

Instead of the above code, where the daysWorked is calculated and passed to CalculateIncentive Method, we could have the CalculateIncentive method do the call to GetDaysWorked within itself, rather than being send as a Parameter. This would get rid of the parameter and simplify the method call.

 

Data Clumps

Another common bloater found in code is known as Data Clumps. Martin Fowler has coined the term as follows

 

“Whenever two or three values are gathered together, turn them into a $%#$%#^ object” – Martin Fowler

 

At times, you see a set of variables hanging around in groups in different part of the code. These are potential to be made into an object of their own.  If the group of variables are instance variable in class, then Extract Class is a good technique to apply. There might be other scenarios where the group of variables are as parameters of method, which gives us the option to employ Introduce Parameter Object and Preserve Whole Object.

 

Treating Data Clumps goes a long way in organizing code in a better way.

Caliburn.Micro #006 : Event Aggregators & Window Managers

Consider the classic scenario when you need to show the currently logged in User Name in your main Window, once you have successfully logged in. The The login Window is supposed to be a Modal Dialog, and isn’t remotely aware of the Label displaying Username in the Main Window.

WPF handles Modal Dialogs and messaging service between Views using Window Managers and Event Aggregators.

Event Aggregators allows a loosely coupled message parsing mechanism between different View Models in the system. As the Caliburn Micro Documentation states, an Event Aggregator is a service that provides the ability to publish an object from one entity to another in a loosely based fashion.

Let’s being by creating our Sample Application using the Caliburn.Micro Template Pack, which makes it easier to kick start a Caliburn.Micro based application. The complete sample code described in this post is available in Github.
Capture

 

We would be using MEF as our IoC Container. So let’s make changes to Bootstrapper to accommodate MEF. For sake of ease, we will remove the existing Bootstrapper and add MEF Template supplied along with the Caliburn.Micro Template Pack.

 

Capture1
We will now our Contract Interface and the required LoginView as well as our MainWindow (we will it ShellView). The skeleton of code looks like following now.
ShellView.Xaml
 <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="50"></RowDefinition>
        </Grid.RowDefinitions>
        
        <StackPanel Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Label x:Name="UserName" FontWeight="Bold" FontSize="32"></Label>
        </StackPanel>
        
        <StackPanel Grid.Row="1" Margin="10,10,10,10">
            <Button Margin="5,5,5,5" cal:Message.Attach="[Event Click]=[Action PromptForLogin]">Login</Button>
        </StackPanel>
    </Grid> 

IShell Interface

    public interface IShell
    {

    }

ShellViewModel

  [Export(typeof(IShell))]
    public class ShellViewModel : PropertyChangedBase, IShell
    {
        private string _userName  = default;
        public string UserName
        {
            get => _userName;
            set
            {
                _userName = value;
                NotifyOfPropertyChange(nameof(UserName));
            }
        }

        public void PromptForLogin() {};

    }
We will add the skeleton code for Login Window as well before adding the code to invoke it as a separate Window (not Content Control).
LoginView.Xaml
 <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="20"></RowDefinition>
        </Grid.RowDefinitions>
        
        <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Center" Background="Lavender">
            <Label>User Login</Label>
        </StackPanel>
        <TextBox Margin="5,5,5,5" Grid.Row="1" Name="UserName">UserName</TextBox>
        <TextBox Margin="5,5,5,5" Grid.Row="2" Name="Password">Password</TextBox>
        <Button Grid.Row="3" Margin="5,5,5,5" cal:Message.Attach="[Event Click]=[Action Validate(UserName,Password)]">Login</Button>
    </Grid>

ILogin Interface

public interface ILogin
{
    bool Validate(string userName, string passWord);
}

LoginViewModel

[Export(typeof(ILogin))]
public class LoginViewModel : ILogin
{
    // Since this is a demo, we will always return true
    public bool Validate(string userName, string passWord) => true;

}

Alright, so we have our barebone code ready. Time to link up the chain. The first task is to ensure we have ShellView as our primary start up Window, which we set by altering the code in our Bootstrapper.

protected override void OnStartup(object sender, StartupEventArgs e)
{
    DisplayRootViewFor();
}

The next task is to ensure the Login Window User Clicks Login Button. We do this by utilizing the Window Manager, which is injected (via Dependency Injection) into ShellViewModel. We will add a constructor for ShellViewModel decorated with the ImportingConstructor Attribute. We will also inject LoginViewModel as well in to the class. We will then use the WindowManager for invoking the LoginViewModel as a Modal Dialog. Our constructor and PromptForLogin Method looks like following now.

[ImportingConstructor]
public ShellViewModel(IWindowManager windowManager,ILogin loginWindow)
{

}

public void PromptForLogin() => _windowManager.ShowDialog(_loginWindow);

This opens up the Login Window for you. All good till now, the Login Window is displayed, and you type in the UserName & Password, and Click the Login button to invoke the Validate Method. But how do you pass the UserName information to the ShellViewModel ? This is where Event Aggregator comes into place.

Event Aggregators allows ViewModels to pass (broadcast) information (in a model) to any other View Models who has subscribed to the event. We will begin by creating the model which would contain the information that will passed along Event Aggregators.

public class UserInfoModel
{
     public string UserName { get; set; }
}

We will then inject an instance of EventAggregator in the LoginViewModel. We will also modify our Validate Method a bit. The LoginViewModel class now looks like following.

[Export(typeof(ILogin))]
public class LoginViewModel : ILogin
{
private IEventAggregator _eventAggregator;

[ImportingConstructor]
public LoginViewModel(IEventAggregator eventAggregator)
{
    _eventAggregator = eventAggregator;
    _eventAggregator.Subscribe(this);
}

// Since this is a demo, we will always return true
public bool Validate(string userName, string passWord)
{
    _eventAggregator.PublishOnUIThread(new UserInfoModel(){UserName = userName});
    return true;
}
}

As you can see, we have used the PublishOnUIThread Method of Event Aggregator to publish the UserInfoModel object to anyone listening. We will now move to our ShellViewModel and ensure the class is listening. We would also see how we access the message send by the Login View Model.

Let’s begin by modifying the ShellViewModel to inject the EventAggregator to ShellViewModel, Our constructor now looks as following.

[ImportingConstructor]
public ShellViewModel(IWindowManager windowManager,ILogin loginWindow, IEventAggregator eventAggregator)
{
    eventAggregator.Subscribe(this);
    windowManager.ShowDialog(loginWindow);
}

Now comes the most important part, we need to implement the IHandle interface, where T is the model of the event object, which in our case is UserInfoModel. The interface contains a single method Handle, which we implement soon. Prior to that, this is how our class declaration looks now.

public class ShellViewModel : PropertyChangedBase, IShell, IHandle

The Handle Method of IHandle Interface looks like following.

public void Handle(UserInfoModel message)
{
this.UserName = message.UserName;
}

As you can see, we have assigned the UserName property of ViewModel from the message passed by the EventAggregator. That’s all we need to do. The EventAggregator has passed the message to all subscribers in the message bus for that particular event model. We then capture the message by implementing the Handle Method in IHandle interface.

Code Smells : Bloaters (Long Methods, Long Class)

Code Bloats or Code Bloaters are probably the most common signs of code smells you can see in any branch of code. In fact, eradicating bloaters act as the first step towards refactoring your code. Bloaters are nothing but classes or methods that have grown excessively over a long time marking it difficult to work with. Typically, bloaters doesn’t happen right away, but is accumulate long term as your code base grows.

In this blog post, we will be discussing two of the most common bloaters, Long Method and Long Class

Long Methods

It is recommended that any method which is longer than 10 lines of code is a good candidate for refactoring. One could Extract Code Fragments (that does a specific task and relates to each other than any other piece of code in the method) that can be grouped together to a new Method (Extract Method), even if the new method is hardly couple of lines. It could also help in reducing code duplication and isolating independent parts of code.

Another refactoring technique that could be applied for Long Methods is Separating Query from Modifiers . It would be better to segregate the code fetching data from that modifies/mutates a state. The crux of this technique is based on the Command Query Seperation (CQS) Principle. CQS recommends dividing an object’s method into two broad categories, Queries (Returns a result, but doesn’t change any observable state) and Commands (changes observable state but doesn’t return a value). An observable state of an object is a state which can be accessed by the client code. However, care should be taken to avoid race condition that comes along the CQS approach in a multi-threaded application.

There might be certain scenario’s as well where the local variables are so intertwined with the code that it becomes difficult to extract method. In such scenarios, it might be a good idea to Replace Method with a Method Object, or in other words separate the Long Method into a Separate class, where the local variables of the class becomes Fields variables of the new class. Then it becomes much easier to split the method to smaller chunks of code.

Conditional Operators such as If-else or Switch Cases is another place where you could cut down the Method. You could either opt for refactoring techniques such as Decompose Conditional or use Strategy Pattern. Usage of Strategy Pattern also helps in bringing down the Cyclomatic Complexity of the Method.

Large Class

Large Class, similar to Long Methods are another undesired quality accumulated over time. Developers find it more convenient to add methods to existing classes than creating a new one. This results in Classes which cluttered with large number of methods and fields.

It is always better to split up a large class (Extract Class), especially if it has more than one responsibility. This ensures the class aligns with Single Responsibility Principle. There might be other cases where , there might be a class which utilizes a subset of its feature only in certain special scenarios. For Example consider the following code.

public class Person
{

void PublishMarks()
{
if(PersonType == PersonType.Student)
{
// Do Something
}
}

void PublishSalary()
{
if(PersonType == PersonType.Faculty)
{
// Do Something
}
}

}

In the above class, despite being related to the Person Class and sharing many other features with it, methods PublishMarks and PublishSalary are used only when the PersonType is Student or Faculty respectively. In this scenario, separating an entirely new Class for Student and Faculty isn’t quite recommended. Instead, we could take advantages of Inheritence and creates subclasses of Person Class, separating the Student and Faculty functionalities to SubClass. This technique is refactoring is known as Extracting SubClass.

Another scenario that is worth mentioning is cases when Domain (Business) Logic and Data gets embedded in the UI (Presentation) class. Problem with this approach is that you might end up with lot of duplicate code as the same domain objects might be required at other places in Presentation Classes. The refactoring technique, Duplicate Observed Data, recommends to remove Domain Data to separate classes and use an Observer pattern to synchronize the classes.

In the next of this series, we will look into few more Bloaters, including Primitive Obsession, Long Parameter List and Data Clumps.

References :
https://refactoring.com/catalog/
https://sourcemaking.com/

Command Query Separation(CQS)

One of the side effect of using a method out of a library (for which you do not have source code) is that you are not pretty sure if it changes state of a related object. And if it did, when you are least expecting them to, you might have more headaches than you could imagine.  But what if the creator of library had struck with the CQS Principle ?

 

Command Query Separation

CQS, or Command Query Separation was introduced by Bertnard Meyer and it states that every method should be either a command that performs an action, or a query that returns data to the caller, but not both.

Or in other words, Bertnard Meyer wants us to separate our methods into two broad categories, Commands and Queries. Commands can change observable states of the object (and hence has a side effect), but doesn’t return a value. On other hand, Queries does not change states of the object and returns a value. It doesn’t have a side effect and can be called any number of times without having any implication.

The advantage of adhering to the CQS Principle is that the Client have a clear understanding of which methods would be causing a side-effect on the object state and which doesn’t.
Code Samples
// Queries
PersonInfo GetUserDetails(int userId);
// Command
void UpdateUserName(int userId, string userName);
However, it is not always possible to follow the CQS Principle. There are times when you would want to modify the state and return an object as well. The most noticeable example is when you work with Stacks. Consider the following code.
Stack sampleStack = new Stack();
sampleStack.Push("DummyDataString");
var fromStack  = Test.Pop();<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
As you can see from the code above, the Pop Method of Stack Object not only returns a value, but modifies the state of Object as well. The same applies to Queue as well. Likewise, there might be scenarios in our code wherein we would like to do both state change as well as return value with a method. Hence, CQS is a good principle to follow whenever possible, but one needs to be aware that there could be exceptions.

Caliburn.Micro

Caliburn.Micro is a extremely lightweight MVVM Framework. This series provides an introduction/refresher to developing WPF applications with Caliburn.Micro
1. Caliburn.Micro: Introduction
2. Caliburn.Micro: Bindable Collections & Events
3. Caliburn.Micro: Events (Short Hand Syntax)
4. Caliburn.Micro:Bootstrapper with SimpleContainer
5. Caliburn.Micro: Bootstrapper with MEF
6. Caliburn.Micro: Event Aggregators & Window Managers
7. Caliburn.Micro: Bootstrapper with Unity
8. Caliburn.Micro: Gesture Recognition using Short-Hand Syntax

 

YAGNI Principle

We developers have a common problem – We tend to overthink and over engineer. We tend to over think into the future attempting to foresee some of the features that we might require in the project. But most often than not, those features might require a lot of changes resulting in technical debt, or not used at all.

YAGNI

This is the issue YAGNI or You Aren’t Gonna Need It intends to resolve. The YAGNI Principle states that we should implement features only when we actually need them, and never when we foresee that we might need them.

YAGNI is the crux behind XP’s (Extreme Programming) Practice of “Do the simplest thing that could work” and Emergent Design which encourages developers to design only for the features that is actually needed, unlike Big Design Up Front (BDFU). This reduces a large amount of unwanted work, and avoids feature creep, resulting in avoiding cost of delay.

Think about it, if you are including features that you don’t require now, there is additional cost of delay due to additional development and testing. And to think you might never actually need that code might have you banging your head cursing your assumptions which resulted in writing the code.

YAGNI discourages developers to work on features based on assumptions that you might require it later on. In fact, YAGNI aligns with the Occam’s Razor (modern interpretation for Software Development) which states among competing hypothesis, choose one with the least assumptions. This is what Lean Software Development teaches us as well, to delay the decision making as much as possible so that decisions can be made based on facts rather than assumptions.

Fail Fast Principle

There are 3 keys ways a developer usually approaches error handling in code.

  • Ignore
  • Fail Safe
  • Fail Fast

We have, at different point of writing code, used all three approaches. There are times when have good reasons to ignore a particular exception scenario, while at other times, we are opt for Fail Safe approach.

Fail Safe approach never hides the exception, but rather, delays it until it is safe to raise it. This is a reasonable approach, considering we are now swallowing an exception. But there is a huge problem with this approach. Most often than not, the Fail Safe approach makes the application to fail slowly, resulting in the system to continue working smoothly when the exception occurs and then fail later on. This, as a developer, inevitably leads you to spending hours debugging your code to trace a bug. What would have been a better approach ?

Fail Fast Principle

Fail Fast Principle that has its heart in Defensive Programming, encourage developers to fail fast and visibly when an exception occurs. The biggest benefit of this approach is a faster feedback loop. In early days of adhering to this principle, you might end with a lot frustrating moments as you might think your have build a fragile software, but remember, it is always better to fix the bugs upfront, than to have the customer face them. The Fast Fail Principle does exactly that for you and aids you in building a robust application.

That doesn’t mean that you should completely ignore the first two approaches. This is the guidelines I keep for myself.

  • Use Ignore, only when having really specific reasons.
  • Use Fast Safe, when it is a critical piece of code, and Failing Safe is a better approach
  • Any other times, Use Fail Fast.

 

StarFish Retrospective

“At regular intervals, the team reflects on how to become more effective, then tunes and adjusts its behavior accordingly”

– 12th Principle, Agile Manifesto

It doesn’t need any explanation why Retrospectives are important in any scrum team. Question is, how can we make Retrospective Sessions more effective.

I was in conversation with a friend recently and one of the things he said he is running into trouble with is that the team members attempt to blame each other rather than getting to root of issues during retrospective.

To start with, key lies in making it more transparent. That doesn’t mean you need to document and publish it to anyone outside the team to view it. That is effectively an anti-pattern that plagues the success of retrospective. Unless the team members believes that what happens during the retrospective lies within the team, they wouldn’t be open with their opinions. This is the same reason why Line-Managers should be kept away from such meetings.

Care should also be taken to ensure the meeting doesn’t end up as a blame game, which is why the role of Scrum Master becomes critical, in the way he facilitates the meeting. The idea should be generate positive energy and responsibility, rather than a blame game that ends up depressing and energy draining.

Sprint Retrospective

Sprint Retrospective’s are usually revolved around 3 key questions

  • What went well ?
  • What did not go well ?
  • What can be improved ?

StarFish Retrospective

If the Scrum Master feels the questions are too broader for team to answer, he could employ exercises like the StarFish in the retrospective. The Starfish focuses on 5 Questions, instead of 3.

  • Stop Doing : Focus on things which are not doing any benefits for the team, and rather is getting on the way
  • Start Doing : Focus on new things which can add value to team
  • Continue Doing : Recognize things which is working well, and team should continue doing.
  • Do more often : Recognize things which is working well for team and could do team more good if done more frequently
  • Reduce Doing : Recognize things which is working well, but could reduce the frequency a bit.

The key however lies on finding the root cause, for example for things that you have chosen to stop doing completely. The team need to understand why it is not working. For this the Scrum Master could employ methods like the 5 Whys.

5 Why’s

5 Why’s is a root cause analysis technique that focuses on getting to the root of any problem by repeatedly asking “Why”. Each answer would form the basis of next question. You could read more on the 5 Whys in Wikipedia.

Mutation Testing

Even with TDD, the quality or coverage of the existing Unit Tests are always a concern for the developer. “Have I done enough ?” That’s one question that haunts him throughout.

Mutation Testing is a structural testing method that attempts to add more value to Unit Tests by aiding in identifying the ‘misses’ in Unit Tests. The central idea behind is to write Mutant of existing code, each of the mutant varying each other by a single change.

For example, Let’s think about the following code.

int TestMethod(int CurrentValue)
{
if(CurrentValue<=3)
return 100;
else
return 200;
}

One of the mutants of the method would be replacing the decision parameter “”.  The Mutant would look like following.

int TestMethod(int CurrentValue)
{
if(CurrentValue>3)
return 100;
else
return 200;
}

Idea behind the Mutation Testing Approach is to ensure that the Testing Data set is near complete and adequate to identify all possibles that the code could have.  The focus would then shift to create Test Cases that would kill as much as mutants as possible.

The mutants can be broadly categorized under 3 categories.
  • Decision Mutations  – Conditions are changed for checking design errors, typically relational, logical and arithmetic operators.
  • Value Mutations  – Typically focused on changing the values (especially constants) to detect the impact/error
  • Statement Mutations – Statements are removed/duplicated.
Thinking about it, Mutation Testing looks a must for any developer if one was turn blind on the extensive resources (mutants) that could be generated. However, from the perspective of a .Net Developer (especially if you are using Visual Studio 2017), there is definite lack of tools and related documentation. Some of the tools that are available for .Net developers are
While Visual Mutator looks the most user friendly, it doesn’t seem to support Visual Studio 2017. Ninja Turtles, on other hand, suffers from lack of documentation and guidance for usage.