Archive for ◊ August, 2012 ◊

Monday, August 27th, 2012
Validation on business objects is a responsibility that changes based on the requirements and sometimes gets added or removed based on the context.  The decorator design pattern can be utilized to provide various validations on business objects which can be attached to the object dynamically. In this post we’ll see how we can use the fluent decorator to implement fluent validations on an entity. We’ll create the base validate as a generic class so that it can be used on any entities in the application.
public class Order
{
public string OrderNumber { get; set; }
public int OrderId { get; set; }
public string Description { get; set; }
public Customer Customer { get; set; }
public DateTime OrderDate { get; set; }
public string ShipmentDetails { get; set; }
public DateTime? RecievedDate { get; set; }
public OrderStatus Status { get; set; }
}
We’ll be using the Order object and validate it in this sample. The interface IEnityValidator is used as the
signature for our validation objects.
public interface IEntityValidator
{
bool Validate();
string GetErrorMessage();
bool IsValid();
List<ValidationError> GetErrors();
}
public class ValidationError
{
public ValidationError(string field, string message)
{
Field = field;
Message = message;
}
public string Field { get; set; }
public string Message { get; set; }
}
The abstract EnityValidationDecorator is the base class for the validation decorators. All our decorators will inherit this class and implement the Validate method to do validations on the object passed to the validator.
public abstract class EntityValidationDecorator : IEntityValidator
{
protected T _Entity;
protected IEntityValidator _Validator;
protected StringBuilder _messageBuilder = new StringBuilder();
protected List<ValidationError> _Errors = new List<ValidationError>();
protected EntityValidationDecorator(IEntityValidator validator)
{
var entityValidator = validator as EntityValidationDecorator;
if (entityValidator != null) _Entity = entityValidator._Entity;
_Validator = validator;
}
protected EntityValidationDecorator(T entity, IEntityValidator validator)
{
_Entity = entity;
_Validator = validator;
}
public abstract bool Validate();
public abstract string GetErrorMessage();
public List<ValidationError> GetErrors()
{
if (_Validator == nullreturn _Errors;
_Errors.AddRange(_Validator.GetErrors());
return _Errors;
}
public abstract bool IsValid();
}
Implementing the Order number validator.
public class OrderNumberValidator : EntityValidationDecorator<Order>
{
public OrderNumberValidator(IEntityValidator validator) : base(validator)
{
}
public override bool Validate()
{
_Validator.Validate();
string validationMessage;
var orderNumber = _Entity.OrderNumber;
if(string.IsNullOrEmpty(orderNumber))
{
validationMessage = “Order number cannot be empty”;
GetErrors().Add(new ValidationError(“OrderNumber”, validationMessage));
_messageBuilder.AppendLine(validationMessage);
return false;
}
if(orderNumber.Length < 5)
{
validationMessage = “Order number should be greater than 5″;
GetErrors().Add(new ValidationError(“OrderNumber”, validationMessage));
_messageBuilder.AppendLine(validationMessage);
return false;
}
return true;
}
public override string GetErrorMessage()
{
return string.Concat(_Validator.GetErrorMessage(), _messageBuilder.ToString());
}
public override bool IsValid()
{
return !GetErrors().Any();
}
}
Similarly we can use different kinds of validators for performing validations on our Order object. Later we can add fluent interface support to the validations by using extension methods as given below.
public static class OrderDecoratorExtensions
{
public static EntityValidationDecorator<Order> AttachValidator(this Order order)
{
return new OrderValidator(order);
}
public static EntityValidationDecorator<Order> AddOrderNumberValidation(this EntityValidationDecorator<Order> validator)
{
return new OrderNumberValidator(validator);
}
public static EntityValidationDecorator<Order> AddOrderCustomerValidation(this EntityValidationDecorator<Order> validator)
{
return new OrderCustomerValidator(validator);
}
public static EntityValidationDecorator<Order> AddOrderDateValidation(this EntityValidationDecorator<Order> validator)
{
return new OrderDateValidator(validator);
}
}
Testing the validators.
[TestMethod]
public void OrderNumberShouldNotBeEmpty()
{
var order = new Order();
var orderValidator = order.AttachValidator()
.AddOrderNumberValidation()
.AddOrderCustomerValidation()
.AddOrderDateValidation();
var isValid = orderValidator.Validate();
var errorMessage = orderValidator.GetErrorMessage();
Assert.IsTrue(errorMessage != string.Empty);
Assert.IsFalse(isValid);
}
Sunday, August 26th, 2012
Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs by offering a number of attributes and helper classes to help formalize any assumptions you make in your code into a contract. A contract can pertain to pre-conditions, post-conditions, assumptions and “object invariants” that enable static contract verification and runtime checking of values.
The Introduce Assertion refactoring recommends making an assumption explicit with an assertion if a section of code is going to make that assumption about the state of the program. You can use code contracts to implement this refactoring in your code. In this post, we’ll see how to refactor your code to add code contracts for assumptions.
[TestMethod]
public void TransferDepositsRequestedAmountInTheAccountFromTheCurrentAccount()
{
var account = new Account(300);
var accountToTransfer = new Account();
account.Transfer(accountToTransfer, 150);
Assert.AreEqual(account.GetBalance(), 150);
}
public decimal Transfer(Account account, decimal amount)
{
_accountBalance -= amount;
account.Deposit(amount);
return _accountBalance;
}
The code given assumes that the client that calls the transfer method on the current account object passes a valid account object to the transfer method to do the transfer.
We can prevent the object from being instable by adding assert assumptions as given below.
[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void TransferDepositsRequestedAmountInTheAccountFromTheCurrentAccount()
{
var account = new Account(300);
var accountToTransfer = default(Account);
account.Transfer(accountToTransfer, 150);
Assert.AreEqual(account.GetBalance(), 150);
}
public decimal Transfer(Account account, decimal amount)
{
Assert.IsNotNull(account);
_accountBalance -= amount;
account.Deposit(amount);
return _accountBalance;
}
Apart from checking that account should not be null, we need to make further assumptions or verification on the code before we do the actual transfer. We need to make sure that the account has the required balance before transferring the amount to the other account. Also after the transfer the account should have a minimum balance according to the requirements.
Let’s see how code contracts can be used to add the required assumptions and verifications on the code.
[TestMethod, ExpectContractFailure]
public void TransferDepositsRequestedAmountInTheAccountFromTheCurrentAccount()
{
var account = new Account(300);
var accountToTransfer = new Account();
account.Transfer(accountToTransfer, 300);
Assert.AreEqual(account.GetBalance(), 50);
}
public decimal Transfer(Account account, decimal
amount)
{
Contract.Requires(account != null);
Contract.Ensures(Contract.Result<decimal>() >= _minimumBalance);
Contract.Assume(amount < _accountBalance);
_accountBalance -= amount;
account.Deposit(amount);
return _accountBalance;
}
The ExpectContractFailure attribute is a custom attribute created to assert the ContactFailed exception.
public class ExpectContractFailureAttribute : ExpectedExceptionBaseAttribute
{
const string ContractExceptionName = “System.Diagnostics.Contracts.__ContractsRuntime+ContractException”;
protected override void Verify(Exception exception)
{
if (exception.GetType().FullName != ContractExceptionName)
{
RethrowIfAssertException(exception);
throw new ArgumentException(“Exception {0} as found instead of contract exception.”,
exception.GetType().FullName);
}
}
}
Category: .Net, Agile/Scrum | Tags:  | 3 Comments
Thursday, August 23rd, 2012
The decorator pattern is used to extend or alter the functionality of an object at runtime. IT does this by wrapping the object with a decorator class, leaving the original object intact without modification. Let’s look into the code structure given below for a Starbucks coffee menu implementation for calculating the cost of the beverages including the various coffee toppings provided. An inheritance based approach will result in an object explosion like this.
We can try to reduce the complexity of this design by refactoring this to a decorator implementation. Later I’ll show how we can use fluent interfaces to create a fluent decorator that is more readable and a cleaner approach to use.  The final implementation changes our code structure to something like
We’ll start our refactoring task by creating a base class for our beverage decorator as given below.
public abstract class Beverage
{
public string Name { get; set; }
public abstract string GetDetails();
public abstract int GetCalories();
public abstract decimal GetCost();
public abstract string GetDescription();
}
public abstract class BeverageDecorator : Beverage
{
protected Beverage _beverage;
protected BeverageDecorator(Beverage beverage)
{
_beverage = beverage;
}
public override string GetDetails()
{
var descriptionBuilder = new StringBuilder();
descriptionBuilder.Append(_beverage.Name);
descriptionBuilder.AppendLine(_beverage.GetDescription());
descriptionBuilder.AppendFormat(” with : {0}”, Name);
descriptionBuilder.AppendLine();
descriptionBuilder.AppendFormat(“Costs : {0:C}”, _beverage.GetCost() + GetCost());
descriptionBuilder.AppendLine();
descriptionBuilder.AppendFormat(“Total calories : {0}g”, _beverage.GetCalories() + GetCalories());
descriptionBuilder.AppendLine(_beverage.GetDetails());
descriptionBuilder.AppendLine(GetDescription());
return descriptionBuilder.ToString();
}
}
We include a protected Beverage member in our decorator to access it and apply extensions on the methods.
Next you can start creating the decorators for the coffee toppings. I’ve added a sample implementation for the whip cream decorator below
public class CreamDecorator : BeverageDecorator
{
public CreamDecorator(Beverage beverage) : base(beverage)
{
Name = “Whip cream”;
}
public override int GetCalories()
{
return 100 + _beverage.GetCalories();
}
public override decimal GetCost()
{
return _beverage.GetCost() + .50M;
}
public override string GetDescription()
{
return “Sweetened and flavored with vanilla.”;
}
}
You can now use the beverage object with added toppings as given below
[TestMethod]
public void DecoratorAddsFunctionalityAtRuntime()
{
Beverage beverage = new CafeMisto();
beverage = new CreamDecorator(beverage);
beverage = new ChocolateFlakesDecorator(beverage);
beverage = new CinnamonSprinklesDecorator(beverage);
Assert.IsTrue(beverage.GetCost() > 2M);
Assert.IsTrue(beverage.GetCalories() > 110);
}
Next we can use fluent interfaces approach by adding extension methods to the Beverage class as
public static class BeverageDecoratorExtensions
{
public static Beverage AddCream(this Beverage beverage)
{
return new CreamDecorator(beverage);
}
public static Beverage AddChocolateFlakes(this Beverage beverage)
{
return new ChocolateFlakesDecorator(beverage);
}
public static Beverage AddCinnamonSprinkles(this Beverage beverage)
{
return new CinnamonSprinklesDecorator(beverage);
}
}
After applying fluent interfaces our decorator implementation can be applied by using the syntax
[TestMethod]
public void DecoratorAddsFunctionalityAtRuntime()
{
var beverage = new CafeMisto()
.AddCream()
.AddChocolateFlakes()
.AddCinnamonSprinkles();
Assert.IsTrue(beverage.GetDetails().Contains(“Whip cream”));
Assert.IsTrue(beverage.GetCost() > 2M);
Assert.IsTrue(beverage.GetCalories() > 110);
}
Category: .Net, Agile/Scrum | Tags:  | One Comment
Author:
Tuesday, August 21st, 2012

One of the biggest challenges for agile teams or for that matter lot of organizations is fear of conflict. This fear of conflict is a major reason why organizations fail to call right shots. In a survey conducted among US and Europe executives, 85% have acknowledged that they had issues/concerns at work that they were afraid to raise. They were afraid of conflict that would provoke, afraid that it would lead to arguments that they won’t know how to manage and loose.

Arguments are necessary; disagreements are required to drive creative solutions to problems. Well, easier said than done. How can we have these conversations more easily and more often? Organizations culture should reflect and encourage the attitude of questing, willingness to start an argument. Imagine in an agile team, if individuals are hesitant to prove others wrong, it will ultimately do bad to the team.

Developing “Prove me wrong” attitude doesn’t mean that team/organization loses team sprint. In fact, the opposite would happen; there is even more team collaboration, very little room for wrong decisions or judgments. The reason why Phd theses have such a high quality is because they have to pass “Prove me wrong” phase.

It is not enough to make things transparent and open, but as I mentioned above, the discussions and arguments around it is what makes it effective.

Openness isn’t the end; it’s the beginning.

Credit: This blog is inspired by the TED talk give by Margaret Heffernan – Dare to disagree

Author:
Friday, August 10th, 2012

Scrum offers different benefits to people in different roles. If you’re a developer, switching to Scrum will help you in several ways. I am a developer, and I confess, I was a bit apprehensive about Scrum when we started about 3 years ago. But having done it, I think it was the best move for me, my team and our client. The biggest advantage I experienced was a sense of empowerment.

Scrum promotes self-organizing teams. As a part of this team you’ll have better support, better control and higher flexibility. Every sprint the team works towards a common goal and team members are bound to voluntarily help each other do whatever it takes to meet that goal. You’ll have better coordination with your colleagues. Team members will be more willing to seek help when they’re stuck. Team members will also be more willing to help each other. You also get the flexibility of working on different kind of tasks. Team members usually pick tasks in the order of their priority, so you’ll get to work on new things (sometimes with help from another team member). Eventually, the collective knowledge of team will grow.

As a part of scrum team, you have more control over estimations. In scrum, you’re not working on someone else’s schedule. The team estimates, everyone has a say (and stake) in estimation. The commitment per sprint is simply a reflection of your velocity. The whole thing is pretty transparent. Which is beneficial to you as a developer and also to your customer. Estimation techniques like Planning Poker facilitate this and makes sure every team member is involved in the estimations and the conversations around it.

As a part of scrum team, you’ll have lesser instances of high work pressure (or burnouts). Scrum works in Sprints of short durations. Each sprint has a fixed set of goals/commitments which is known right at the start of the sprint. In fact, the team chooses this commitment. Throughout the duration of sprint, the team works together in meeting these goals. The daily scrum meeting helps the team coordinate their efforts towards this goal. You work at a consistent pace and don’t have late nights or burnouts.

I’ve also found that Scrum makes your more involved with your work and your customers. You’ll talk to your customer more often, you understand their problems better and are in a better position to offer solutions. In turn, you’ll feel more satisfied with work you’re doing. You get to make a difference. You’ll also be delivering more often and get feedback from the users sooner. It’ll help you and your customers immensely.

Are you a developer? Are you doing Scrum?

Are you not doing Scrum? Do you have questions or comments for me?

Feel free to post them below.

- Anand Gothe

Author:
Tuesday, August 07th, 2012

Back in collage days, I learnt a lesson when my friend almost killed me (not literally though :) ) when I responded to a question by saying “yes, you look fat”.  Recently I noticed such a scenario in a team, well it’s nothing to do being fat :) but fundamentally it was same, “Giving and taking feedback”.

I believe that feedback is a gift. It always helps us grow personally and professionally. Yet, most of us have a negative perception towards it. Most of us still believe age old saying “If you don’t have anything nice to say, don’t say anything at all.”

Today’s demanding and challenging work environment calls for an imbibed culture of giving and receiving feedback. This aspect should be even more emphasized in agile teams. For example, lot of agile practices have an inbuilt framework to facilitate faster feedback such as with XP, we have CI, Pair programming, Peer reviews etc, with scrum we have retrospectives etc. Most of these feedback mechanisms are targeted at technical accepts and abstracted at team level.

In order to have hyper-productive teams, individuals should be comfortable to give feedback at an individual contribution level to acknowledge his/her achievements or to identify any growth areas.

Here are some points on giving and receiving feedback.

  1. Give your feedback as soon as possible: If you notice something done really well, don’t wait till a retrospective or some event to give a pat on back. If it is appropriate, drop an email, or post it in a bulletin board about the good work. At the same time, if you see something can be improved, or done at substandard level, let the person know ASAP.
  2. Balance your feedback: Always start your feedbacks with a positive note. It is important to mix both positives and growth areas.
  3. Be Constructive: The whole idea of giving feedback to help the other person to grow and not to criticize. So, always give your feedback in a constructive way. Be careful with the language you use. Replace words such as “but” and “however” with the word “and” when you string together your positive and negative feedback. When people hear the word “but” they immediately discount the part that came before it and only hear the negative comments.
  4. Listen: While receiving feedback, listen to the other person’s point of view. Perceptions are true at least for the ones who own it. So here it out without any justification or explanation.
  5. Reaction: If you don’t completely accept the feedback, thank the person and tell him how you are going to take that feedback. Be careful, it sometime do happen, that rather than accepting the feedback, we tend to denounce not only what is said but also those who say it.

Always remember, if someone is giving you feedback, it means they are interested in what you are doing and wants to help you to become better at it. Now, coming back to my collage days, if I had known point 3, I would have said “This dress suites you very well and I guess you look little big now” (not sure if it would have really helped) :)

Author:
Friday, August 03rd, 2012

Naturally, I’m tempted to answer “YES” to this question as I wear my Agile Coach hat at work. As I pay close attention to the person’s conversation, what he/she is really saying (screaming inside) is bunch of fears such as

  • Fear of failure
  • Fear of change
  • Fear of moving out of comfort zone
  • Fear of learning curve
  • Fear of wrong decision
  • Fear of transparency
  • Fear of losing control
  • And it’s so easy to give orders or follow orders J

So, when you want to convince your boss or your customer to go Agile, ask what challenges they think that exists currently with their organization or team. It’s much easier to focus on solutions and start that conversation when people acknowledge that a problem exists.

Author:
Thursday, August 02nd, 2012

JavaScript performance is always a question of debate in web development. Bulk of JavaScript’s problem in client side programming is due to its blocking nature. Most of the browsers use a single process for UI updates and JavaScript execution. Longer the time it takes for JavaScript execution longer the browser is locked for updating contents on the web page.

The following are refreshers for improving JavaScript performance.

i) Place <script></script> tag always at the bottom of the page.
<html>
<head></head>
<body>
<div>..</div>
<script>JavaScript Code Snippet</script>
</body>
</html>

ii) Group multiple JavaScript files together.  It always faster to load one 100KB file than to load four 25KB files.

iii) Minification and Obfuscation – Sure minification and obfuscation helps but not at the cost of losing readable content.

iv) XHR – Though XHR addresses bulk of the synchronous loading nature of JavaScript it still has cross-domain policy issues. XHR also doesn’t address dependency management.

To address the blocking nature and the dependency management functionalities in JavaScript we use Script Loaders.

One of the more popular framework for Script loaders available today is RequireJS.

i) RequireJS addresses blocking nature of JavaScript by loading just one JavaScript file and releases the browser process for UI.
<script data-main=“scripts/main” src=“scripts/require.js”></script>

This script requires you to load require.js. User scripts will be located in a file called main.js under scripts folder. User scripts are loaded asynchronously.

ii) RequireJS also addresses dependency management by loading scripts on demand
require(["scripts/jquery"], function($) {
$(“display”).html = “This is my text”;

});

This script will add jQuery module to the application.

….. More about RequireJS and its functionality in future sessions.

Category: Javascript  | 2 Comments
Thursday, August 02nd, 2012

FluentAOP is a lightweight, fluent interface based library that allows implementing aspects of method interception in a simpler and easier way. FluentAOP is primarily designed to simplify the adoption and use of AOP in .NET. In contrast to most AOP implementations, its interception semantics exclusively rely on strongly-typed method definitions and a fluent API. Check this link for more details on method interception and AOP.

Creating the FluentAOP proxy is as easy as
return new Proxy<IEmployeeService>().Target(new EmployeeService()).Save();
The OnBefore and OnAfter methods can be used to execute some logic before and after the intercepted method is invoked for execution.
[TestMethod]
public void OnBeforeExecutesTheActionBeforeTheMethodIsCalled()
{
var service = EmployeeServiceFactory.Create();
var employees = service.GetAll();
Assert.IsTrue(employees.Any(e => e.Id == 10));
}
return new Proxy<IEmployeeService>()
.Target(new EmployeeService())
.InterceptMethod(m => m.GetAll())
.OnBefore(m =>
{
var service = m.Target as IEmployeeService;
if(service == null) throw new TypeAccessException();
service.Add(new Employee(10, “Test Employee”));
})
.OnAfter(m => Debug.WriteLine(string.Format(“Method called with argument {0}”, m.Arguments[0])))
.Save();
The OnInvoke method can be used to intercept the method call.
[TestMethod]
public void OnInvokeShouldInterceptTheActualMethodExecution()
{
var service = EmployeeServiceFactory.Create();
var employees = service.GetAll();
Assert.IsTrue(employees != null);
}
return new Proxy<IEmployeeService>()
.Target(new EmployeeService())
.InterceptMethod(m => m.GetAll())
.OnInvoke((m) =>
{
if(Cache.Instance.Exists(“Employees”))
return Cache.Instance.Get(“Employees”as IEnumerable<Employee>;
return m.Method.Invoke(m.Target, m.Arguments);
} )
.Save();
You can also use the OnReturn method to intercept the return value from the method and take actions based on the value.
[TestMethod]
public void OnReturnShouldBeCalledAfterTheInterceptedMethodExecutionCompletes()
{
var service = EmployeeServiceFactory.Create();
service.GetAll();
Assert.IsTrue(Cache.Instance.Exists(“Employees”));
}
return new Proxy<IEmployeeService>()
.Target(new EmployeeService())
.InterceptMethod(m => m.GetAll())
.OnReturn((m, r) =>
{
Cache.Instance.Update(“Employees”, r);
return r;
})
.Save();