3 tips to make you a better developer

four20puzzle

introduction

I’m sorry for the clickbait headline, I didn’t have a better idea/name for it.

We (developers) occasionally produce lazy/messy code and from time to time we need to remember the most important rule: “We do code to solve problems but also for human being be able: to use, to maintain and to evolute”. 

TLDR; (a unit can be a: function, var, method, class, parameter and etc)

  1. Naming your units with care and meaning;
  2. Try to see your code as a series of transformation;
  3. When possible make yours units generic.

Keep in mind that these tips are just my opinions and at the best they were based on: excellent books (Refactoring, DDD, Clean Coder and etc ), articles & blog posts,  excellent people I’ve worked/paired with,  presentations,  tweets and experiences.

naming is hard

Name your units with care and meaning. Your code should be easy to understand.

Although naming things is really hard, it is also extremely important. Let’s a see a snippet of code:

Let’s discuss about this code above:

  • the function topComments receives an id but is it the id from the comment, user, article? Let’s say it’s form the user, therefore userId should vanish this doubt.
  • the name of the function is topComments but it looks like it’s getting the top 10 latest comments only thus we could call it top10LatestCommentsFrom.
  • the ajax function accept two callbacks one in case of success (succCB) and otherwise an error (errCB), I believe we can call them: onSuccess and onError for better understanding.
  • all the arguments are using short names and we can have less confusing names just by using the entire name.
  • you got the ideia, naming things to let the code clear!

Although we still have so many problems in this code, now it’s easier to understand and we only named things properly.

For sure there are some cases when short names are just okay, for example: when you’re developing an emulator or virtual machine you often use short names like sp (stack pointer) and pc (program counter) or even doing a very generic unit.

filter -> union -> compact -> kick

Try to see and fit your code as transformations, one after another.

Some say that in computer science almost all the problems can be reduced to only two major problems: sort and count things (plus doing these in a distributed environment), anyway the point is: we usually are coding to make transformation over data.

For instance our function top10LatestCommentsFrom could be summarized in these steps:

  1. fetch comments (all)
  2. sort them (by date)
  3. filter them (only top)
  4. select the first 10

Which are just transformations over an initial list, we can make our function top10LatestCommentsFrom much better with that mindset.

 

By the way this could lead you to easily understand the new kid on the block sometimes referred as Functional Reactive Programming.

<be generic>

Work to make your units generic.

Let’s imagine you are in an interview process and your first task is to code a function which prints the numbers 1, 2 and 3 concatenated with “Hello, “. It should print: “Hello, 1” and then “Hello, 2″…

Now they ask you to print also the letters: “D”, “K” and “C”.

It was the first step toward the “generic”, now the interviewers say you have also to print a list of person’s name but now it’ll be a list of objects [{name: “person”},…].

Things start to get specific again and the interviewers want to test you. They ask you to print a list of car’s brand [{brand: “Ferrari”}, ..] plus a list of game consoles with their architecture [{name: “PS4”, arch: “x86-64”}, …]

Yikes, I suppose you’re not proud of that code and probably your interviewers will be little concerned about your skills with development, let’s list some of the problems with this approach.

  • Naming (we’re calling a person of an item)
  • High coupling (the function print knows too much about each printable)
  • Lots of (inner) conditionals 😦 it’s really hard to read/maintain/evolute this code

What we can do?! Well, it seems that all we need to do is to iterate through an array and prints an item but each item will require a different way of printing.

 

I said naming is important but when you make something very generic you should also make the abstract names not tied to any concrete concept. In fact, in Haskell (let’s pretend I know Haskell) when a concrete type of something may vary we use single letters to take their place.

Bonus round

  1. Make your units of execution to perform a single task.
  2. Use dispatch/pattern matching/protocol something instead of conditionals.
  3. Enforce DRY as much as you can.
Advertisements

Will we only create and use dynamic languages in the future?

Since I’ve playing with some dynamic languages (Ruby and Clojure), I have been thinking about why would anybody create a new static typed language?! And I didn’t get the answer.

I started programming in Visual Basic and I taste its roots, which are almost all full of procedure commands (bunch of do, goto and end), then I moved to C#, sharper it changes the end’s for }’s and give us a little more power based on some premises: we can treat two different things in the same way, polymorphism. The last static language, but not the least, I used (and I use it) Java, abusing of his new way of treating a set of things equality, the interfaces and using its “powers” on reflections.

Although when I started to use Ruby I saw that I could treat a group of things equality without doing any extra work. I still need to code models and composed types, even though we can create or change them dynamically using “real power” of metaprogramming.

When I start to study and apply the Clojure and its principles, my first reaction was the rejection, how can I go on without my formal objects, how can I design software without a model in the head and so on. I wasn’t thinking about how actually I do software, currently I use TDD to design software and I don’t think what models I need to have, I do think in terms of “what I want”. At minimum, Clojure make me think about, do we really need object to design software?! .  A three days ago I saw an amazing video about similar thoughts: Some thoughts on Ruby after 18 months of Clojure.

Summarising: With my limited knowledge of theses languages, let’s suppose we use a function (which we don’t have source code) and we want to do something before that function is executed (intercept) using: VB I’ll need to check every single piece of code which we call this function and call another one, in Java we can use a AOP framework, in Ruby we can use the spells of metaprogramming. It seems that some frameworks, patterns and extra work aren’t needed more because of this dynamic language evolution.

My conclusions using dynamic languages (Clojure/Ruby) for now it’s: I write less code and reuse them more easy, so I don’t see any reason to create/use a new static typed language, would you see any motivation to do that?

PS: When I use C# (.Net Framework 1.3 – 2.0) it was not so super cool as today.

Testing JavaScript with Jasmine and Jessie and node.js

Testing
Testing JS, can you imagine?

Javascript

JavaScript is a prototype-based, object-oriented scripting language that is dynamic, weakly typed and has first-class functions. It is also considered a functional programming language like Scheme and OCaml because it has closures and supports higher-order functions. Cool language isn’t? A new feeling inside me tells me that everything (related to I.T.) I would like to learn I should start writing a tests. However I thought that JavaScript test was stucked on Alert windows and then I found out Jasmine framework.

How could we write tests to JavaScript?

Using Jasmine in a BDD style.

describe("Jasmine", function() {
  it("makes testing JavaScript awesome!", function() {
    expect(yourCode).toBeLotsBetter();
  });
});

To run it and get feedback you have some options whose I take two: seeing the html file on browser and seeing the terminal result as rspec way. We will do the second way. For that we will use: node.js, npm and jessie.

node.jsevented i/o server (and also you can use it as an interpreter) for javascript vm (specifically v8)
Installing node.js

git clone --depth 1 git://github.com/joyent/node.git
cd node
git checkout v0.4.11 #opt, note that master is unstable.
export JOBS=2 #opt, sets number of parallel commands.
mkdir ~/local
./configure --prefix=$HOME/local/node
make
make install
echo 'export PATH=$HOME/local/node/bin:$PATH' >> ~/.profile
echo 'export NODE_PATH=$HOME/local/node:$HOME/local/node/lib/node_modules' >> ~/.profile
source ~/.profile

npm – node package manager, as its own name suggest. You can use it to install and publish your node programs. It manages dependencies and does other cool stuff.
Installing npm.

curl http://npmjs.org/install.sh | sh

jessie – Jessie is a Node runner for Jasmine. It was created to provide better reporting on failures, more modular design, easier creation of formatters and optional syntactic sugar.
Installing jessie.

npm install jessie

With all these binaries on your path you can just run your tests from terminal typing:

jessie folder_with_specs/ -f nested

In fact I’ve been using the gitub and jessie to learn and apply javascript.

Ruby overview

Introduction

Take a look at this, there is two classes: a person and a teacher. The person (originally) just know how to speak English and then teacher teach him speak other language, it can show you how powerful and beautiful ruby is.

class Person
 attr_accessor :name
 def speak_english
  puts "Hi people!"
 end
end

class BrPortugueseTeacher
 def teach(person)
  def person.speak_portuguese
   puts "Ola pessoal!"
  end
 end
end

bill_gates = Person.new
bill_gates.nome = "Bill Gates"
pasquale = Teacher.new
pasquale.teach bill_gates
#now bill gates knows portuguese
bill_gates.speak_portuguese

The intent here is just show a quick overview of ruby from a newbie.

Code’s comment

#one line comment
=begin
Multiply lines comment.
Given that ...
=end

String

String in ruby is mutable (but when you use the operator method + it creates another string, so to concatenate strings you should use the operator <<) and just a little tip avoid the concatenation by using + instead prefer use interpolation, a way to handle string very similar to expression language, and it’s faster than normal concatenation.

ran = 34434
who = "Leandro Moreira"
puts "#{who} generates this #{ran} number"

Conventions

Yet on mutability, when you write a method that can affect the internal state, you should use the bang operator (!) on method’s name.

old_source_name = "angeline"
puts old_source_name.capitalize
puts old_source_name.capitalize!

Another cool convention to Boolean methods is end them with ?

if account.cancelled?
 puts "Run Forest, run!"
end

Range object

In ruby you can use a type Range to describe ranges and its use is very easy.

zero_to_ten = (0..10) #inclusive
one_to_seven = (0...8) #exclusive
alphabetic = ('a'..'z') #you also can omit the (

It’s all object and quick tips

– Hey, language prints I win three times.

puts "I win " * 3

You can use anything on if statement and it can ben true or false (and nil which is false too).

A weird thing is one way of handle the regular expressions.

/myexp/ =~ "sentence"
#"sentence" matches myexp?

Another weird operator is or equals.

list ||= flights
#the list will just receive the flights if list is nil.

The classes are really open

One of the main features of ruby is Open Class, this is cool, you just can grab a class and write a new feature for it.

class String
 def do_nothing
  puts "doing nothig"
 end
end

And then you just call it.

"number".do_nothing

Let’s trick the addition operations on number.

class Fixnum
 def +(other)
  self - other
 end
end
puts 2+1
#and it will prints 1. (~:

Variable arguments

Sometimes you need to use this kind of flexibility.

user.buy computer
user.buy computer, mouse, monitor

To achieve this you just use the syntax. The splat operator how it is known.

def buy(*products)
 #buy logic
end

Hash enhancements

There is a lot of people which claims to use hash as parameter.

e_account.transfer :to_account => my, :value => 4800

def transfer (parameters)
 dest_account = parameters[:to_account]
 #...
end

Declarations

class Anything
 @field #object field
 @@field #class field
end

Singleton in Ruby

Singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.  (From wikipedia)

class HyperDao
@@instance = HyperDao.new
def self.instance
return @@instance
end
private_class_method :new
end

But we’re talking about ruby, don’t we?

require 'singleton'
class God
include Singleton
end

It’s done! 😀

Equals

If you want or need to rewrite the equals…

def ==(other)
 self.id = other.id
end

Duck typing – good-bye interface

Duck typing is a style of dynamic typing in which an object’s current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. The name of the concept refers to the duck test, attributed to James Whitcomb Riley (see History below), which may be phrased as follows:”When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.” (From Wikipedia)

class PremiumAccount
 def saldo
   #
 end
end

class CommonAccount
 def saldo
  #
 end
end

The bank manager will accept that.

class BankManager
 def total_debt(accounts)
  for account in accounts do
   debt += account.saldo
  end
 end
end

Mixin

Mixin is a class that provides a certain functionality to be inherited or just reused by a subclass, while not meant for instantiation (the generation of objects of that class). Inheriting from a mixin is not a form of specialization but is rather a means of collecting functionality. A class may inherit most or all of its functionality from one or more mixins through multiple inheritance. (Again, from Wikipedia)

module Logging
 def log(message)
  puts message
 end
end

class Anything
 include Logging
  #...
end

any = Anything.new
any.log "It started now!"

Metaprogramming

Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime. In many cases, this allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation.

class Person
 attr_accessor :name
 def speak_english
  puts "Hi people!"
 end
end

class BrPortugueseTeacher
 def teach(person)
  def person.speak_portuguese
   puts "Ola pessoal!"
  end
 end
end

bill_gates = Person.new
bill_gates.nome = "Bill Gates"
pasquale = Teacher.new
pasquale.teach bill_gates
#now bill gates knows portuguese
bill_gates.speak_portuguese

Highly influenced by ruby on rails from Caelum.

ThoughtWorks Brazilian hiring process

The hiring process

My intend here is to explain my personal view of the hiring process (which I was submitted) of Brazilian ThoughtWorks. In fact the ThoughtWorks hiring process is already explained, see a brief view of it:

“Hiring is our signature process, so as you might expect, we’ve thought hard about how we access your suitability for a career with us. We believe we’ve created a process that is fun, that shows you what being a ThoughtWorker is all about and challenges your abilities. Many hiring processes consist of a couple of interviews and perhaps a chance to meet your new boss. We reject that. We want to find out what work environment suits you, what you value and how you do your job, so we don’t just sit and ask you questions. We get you to show us what you can do.”

The steps (Dev role)

The TW talent scout sent me a message telling me about the open positions at TW (Porto Alegre) and then I answer her asking how to apply, she informed everything I need to do. Then I’ve applied to dev position (03/20/2011) and the First Step: a informal phone interview, that first interview it’s very easy and weightless 🙂 just to know you a little bit. The Informal Phone Interview is designed to help tw get to know each other beyond CVs and web pages.

Second Step was the code submission: they will send you two problems, you must choose only one, to solve. On this part they are trying to access a number of things, these include the design aspect of your solution, but mostly we are looking for good coding practices and your object-oriented programming skills. Good tip here is: use your primary programming language (I do love and want to learn ruby but Java was my main tool that moment).

Then if you have passed on this phase you will be on Third Step: the tech phone interview that consists of one ThoughtWorker interviewing you more technically, in my case Rodrigo Wolschick (A.K.A. Patrola) did the interview and despite his nickname he was fine with me.

So after that you will be on Fourth Step: Office Interview (here the real fun will start), they ask me to schedule two days to be at office. At the office you will pass through several interviews (culture values, programming pairing…) and logical assessments, I can tell you it’s very tiring BUT IT’S SURPRISINGLY FUN. After this long process I started to work at June 21.

PS: I should write this before I’ve posted ThoughtWorks POA.

Ohh, one last note we’re hiring, so if you are interested :

Open positions at ThoughtWorks Brazil

JChip16BR the newest toy

Chip16

The last days I’ve been playing around a new virtual machine. This VM is known as Chip16 and its specification can be obtained from Ngemu. The Chip16 is quite simple, it has only 19 registers (including PC and SP), the CPU speed is only 1Mhz, memory’s size 64 KB (65536 bytes). The main way you to interact with the machine is by mapped io. The set of instruction (at version 0.7) is around 48. It’s a start project for those want to learn a little bit of emulation. Maybe you know its father Chip8 that has some inconsistencies and undocumented features.

Emulator Basic flow

Emulator basic flow
Emulator basic flow

Basic steps:

  • [0] Load ROM -> ROM it’s the input of the machine, sometimes it can be a ISO image or a specific structure created by community. It’s a file (structured or not) that contains the data to be executed and read by the machine.
  • [1] Load Memory -> You need to know the memory map of target system. So you properly fill the memory with data from ROM at the correct addresses.
  • [2] Initiate Machine -> It’s the initial state of the machine, some of them used to start with random data all over the RAM, and it used to have the initial address for the first opcode among other tasks.
  • [3] Decode Opcode -> It’s basically the act of read the opcode from memory (pointed by PC) and its parameters too.
  • [4] Execute Instruction -> With the full set of data, you know how to execute the instruction (using the parameters).
  • [5] Events -> Eventually the machine does some events or some interruptions are raised.
  • [6] Cycle Tasks -> This are the tasks performed at given time (measured by clock (number of cycles) or time (ms)): update screen, update inputs and etc.

JChip16BR

JChip16BR architecture
JChip16BR architecture

I did a simplest implementation using Java as language/platform and Java2D as render engine. The idea is: implement this vm and have fun with object-oriented programming. I’ve divide this into several objects. I tried to apply some design patterns, basic oop and etc. The core is the facade Machine which provide methods for start, pause, resume, see the internal state of CPU, draw and etc. The coolest part (IMHO) is the CPU, full of internal classes composing the instruction table which is findable by opcode. For graphics it used a simple short multidimensional array, acting like a screen of pixels.

Video

Source code

You can access the source code at GitHub.

PS: I used the concepts of emulator, simulator and virtual machine as synonymous but my intend was to show how a vm/emulator/simulator or mix of all this works at implementation level.

TDD in practice – developing a game

Test-Driven Development

On this post I’ll try to explain on practise some concepts and techniques behind the TDD and I’ll do it by example.

Scenario


Product: A role-playing game titled as Breath of Fantasy

Story: The battle scheme – Create the battle scheme for the game.

Description:
The battle will be based on turns, each time a character attacks and the other receives the damage. The character has energy points and power points. These two properties are integers numbers. For example, if the hero(energy points: 60, power points:45) attacks a enemy(energy points: 60, power points:45) the enemy will have the energy decreased some points. The damage received, decreased energy points, by enemy depends on luck factor. Luck factor is a random number from 0 to 100 that is given for each attack turn.

There is four kinds of attacks based on your luck factor:

  1. When the luck is 0-3 then the attack is Miss -> doesn’t cause any damage;
  2. When the luck is 4-70 then the attack is Normal -> causes 1/3 of your power points in damage;
  3. When the luck is 71-96 then the attack is Lucky -> causes 1/3 of your power points plus twenty percent of this 1/3 in damage;
  4. When the luck is 97-100 then the attack is Critical -> causes the double of normal attack.

STEP BY STEP

Write a tests to given story, the first one should validate when a character attacks another with Miss attack and see if the damage caused is 0.

@Test
public void validateMissAttack(){
   UnitCharacter hero = new UnitCharacter("hero",60,45);
   UnitCharacter enemy = new UnitCharacter("enemy",60,45);
   hero.attack(enemy);
   Assert.assertEquals(enemy.getEnergyPoints(), 60);
}

You still don’t have the class UnitCharacter, so you can create it now. You should create it just enough to compile and run the test.

public class UnitCharacter {
 public UnitCharacter(String name, int energy, int power) {
 }
 public void attack(UnitCharacter other) {
 }
 public int getEnergyPoints() {
  return 0;
 }
}

When you try to run the test it will fail; PERFECT this is what we want! Now move to next, write code to that test pass. The most obvious /simple solution should be used:

public int getEnergyPoints() {
  return 60;
}

Run the test again, test pass; PERFECT this is what we want! Now move to next, refactor the code. The constructor of UnitCharacter lets spaces for misinterpretations for example use the second argument as power point instead of energy. To solve this possible problem we could use tiny types.

public UnitCharacter(String name, Energy energy, Power power) {
}

public class Energy {
 public Energy(int energy) {
 }
 public int getEnergyPoints() {
  return 60;
 }
}

public class Power {
 public Power(int power) {
 }
}

Looking the new code, we can imagine that there will be a little change in UnitCharacter. The method getEnergyPoints() will just delegate the calling to Energy. Now we’ve refactored all it just run the test again and see if it passes. Now we can move next: create the next tests.

Given: A hero(energy points: 60, power points:45) and a enemy(energy points: 60, power points:45)

  • Test: when the hero attacks the enemy with Normal attack and see if the damage caused is 15.
  • Test: when the hero attacks the enemy with Lucky attack and see if the damage caused is 18.
  • Test: when the hero attacks the enemy with Critical attack and see if the damage caused is 30.
    @Test
    public void validateNormalAttack(){
        UnitCharacter hero = new UnitCharacter("hero",new Energy(60),new Power(45));
        UnitCharacter enemy = new UnitCharacter("enemy",new Energy(60),new Power(45));
        hero.attack(enemy);
        Assert.assertEquals(enemy.getEnergyPoints(), 45);
    }
    @Test
    public void validateLuckyAttack(){
        UnitCharacter hero = new UnitCharacter("hero",new Energy(60),new Power(45));
        UnitCharacter enemy = new UnitCharacter("enemy",new Energy(60),new Power(45));
        hero.attack(enemy);
        Assert.assertEquals(enemy.getEnergyPoints(), 42);
    }
    @Test
    public void validateCriticalAttack(){
        UnitCharacter hero = new UnitCharacter("hero",new Energy(60),new Power(45));
        UnitCharacter enemy = new UnitCharacter("enemy",new Energy(60),new Power(45));
        hero.attack(enemy);
        Assert.assertEquals(enemy.getEnergyPoints(), 30);
    }

When you try to run all these tests they fail; PERFECT this is what we want! Now move to next, code to these tests pass. I’ll focus on validateNormalAttack method test to make it pass.

public class Power {
    private int power;
    public Power(int power) {
        this.power = power;
    }
    public int getPowerAttack() {
        return power/3;
    }
}

public class Energy {
    private int energy;
    public Energy(int energy){
        this.energy = energy;
    }
    public int getEnergyPoints(){
        return energy;
    }
    public void decrease(int attack) {
        energy -= attack;
    }
}

public class UnitCharacter {
    private final Energy energy;
    private final Power power;
    public UnitCharacter(final String name,final Energy energy,final Power power) {
        this.energy = energy;
        this.power = power;
    }
    public void attack(final UnitCharacter other) {
        other.energy.decrease(power.getPowerAttack());
    }

    public int getEnergyPoints() {
        return energy.getEnergyPoints();
    }
}

When you rerun the tests the validateNormalAttack pass but the test validateMissAttack fails! The test suite help us to know it and now we can code to fix this fail! One important concept is the luck factor which influences the type of attack, let’s try to design the luck to the attack.

public interface Luck {
    double nextAttackLuckFactor();
}

public class LuckAttack implements Luck {
    private final Random random = new Random();
    private final static double MISS = 0;
    private final static double NORMAL = 1;
    private final static double LUCKY = 1.2;
    private final static double CRITICAL = 2;
    @Override
    public double nextAttackLuckFactor(){
        int randomFactor = random.nextInt(101);
        if (randomFactor > 0 & randomFactor <=3){
            return MISS;
        } else if (randomFactor > 3 & randomFactor <= 70){
            return NORMAL;
        } else if (randomFactor > 70 & randomFactor <= 96){
            return LUCKY;
        } else {
            return CRITICAL;
        }
    }
}

public class Power {
    private int power;
    private Luck luck;
    public Power(int power) {
        this.power = power;
        this.luck = new LuckAttack();
    }
    public int getPowerAttack() {
        return (int) ((power / 3) * luck.nextAttackLuckFactor());
    }
}

Now if we rerun the tests sometimes one or two passes sometimes all of them fails. Why? The luck is a random number then is unpredictable. Now we can use mocks / stubs objects (there is a tech discussion about the differences between mock and stub) to simulate the desired luck factor.

public class Power {
    private int power;
    private Luck luck;
    public Power(int power,Luck luck) {
        this.power = power;
        this.luck = luck;
    }
    public int getPowerAttack() {
        return (int) ((power / 3) * luck.nextAttackLuckFactor());
    }
}

public class TestAttack {
    @Test
    public void validateMissAttack(){
        Luck missLuck =  new Luck() {
            @Override
            public double nextAttackLuckFactor() {
                return 0;
            }
        };
        UnitCharacter hero = new UnitCharacter("hero",new Energy(60),new Power(45,missLuck));
        UnitCharacter enemy = new UnitCharacter("enemy",new Energy(60),new Power(45,missLuck));
        hero.attack(enemy);
        Assert.assertEquals(enemy.getEnergyPoints(), 60);
    }
    @Test
    public void validateNormalAttack(){
        Luck normalLuck =  new Luck() {
            @Override
            public double nextAttackLuckFactor() {
                return 1;
            }
        };
        UnitCharacter hero = new UnitCharacter("hero",new Energy(60),new Power(45,normalLuck));
        UnitCharacter enemy = new UnitCharacter("enemy",new Energy(60),new Power(45,normalLuck));
        hero.attack(enemy);
        Assert.assertEquals(enemy.getEnergyPoints(), 45);
    }
    @Test
    public void validateLuckyAttack(){
        Luck luckyLuck =  new Luck() {
            @Override
            public double nextAttackLuckFactor() {
                return 1.2;
            }
        };
        UnitCharacter hero = new UnitCharacter("hero",new Energy(60),new Power(45,luckyLuck));
        UnitCharacter enemy = new UnitCharacter("enemy",new Energy(60),new Power(45,luckyLuck));
        hero.attack(enemy);
        Assert.assertEquals(enemy.getEnergyPoints(), 42);
    }
    @Test
    public void validateCriticalAttack(){
        Luck criticalLuck =  new Luck() {
            @Override
            public double nextAttackLuckFactor() {
                return 2;
            }
        };
        UnitCharacter hero = new UnitCharacter("hero",new Energy(60),new Power(45,criticalLuck));
        UnitCharacter enemy = new UnitCharacter("enemy",new Energy(60),new Power(45,criticalLuck));
        hero.attack(enemy);
        Assert.assertEquals(enemy.getEnergyPoints(), 30);
    }
}

This refactoring made the Power uncoupled of the concrete implementation of Luck this has drive our design to a better state. We could use a mock framework as Mockito, JMock and others to simulate the “falses” results. Now try to rerun the tests. All pass great. Next step refactor the test class there is too much duplicated code. Always try to be DRY

IS JUST IT? NOW THE TESTS ARE OVER…?!

No! for each new class we’ve created we should create unit tests for them. For example:

  • what if I create a Energy or Power passing negative number to it?
  • what if I create a UnitCharacter with null Energy?
  • what if I create a UnitCharacter with energy points equals to 97 and power points equals to 51 how the round will work?

You need to to feel safe and confidence about you code. There is some tools for analysing the coverage of your unit tests (like Cobertura) over the project.

THE BENEFITS

The design was entirely modelled by TDD. Now you have a solid suite of tests and when you would do the design of the spell and item usage you can run this tests again and see if they fails. TDD not only give us safety it also lead us to the appropriate design, we don’t spent too much time thinking in the future, we solve the problem of that story and we prove our solution.

IS THAT THE BEST SOLUTION TO THIS PROBLEM

No! You probably has a better one, this is one of the possible.