Monday, August 17, 2015

Dunning-Kruger effect on effort estimates

This post has two parts. The first is an experiment with a poll. The second is the actual content with my thoughts.

The experiment and the poll comes first as I don't want to infect you with my idea before you answer the questions. If you are in the mood of reading a short story and answering a couple of questions, keep reading. In case you are only concerned with my ideas, you may skip the first part.

I won't give any discussion about the subject. I'm just throwing my ideas to the internet, be warned.

Part 1. The experiment

You have to estimate the effort needed to complete a particular task of software development. You may use any tool you'd like to do it, but you will only get as much information as I will tell you now. You will use all the technologies that you already know, so you won't have any learning curve overhead and you will not encounter any technical difficulty when doing the task.

Our customer is bothered by missing other co-workers birthdates. He wants to know all co-workers that are cellebrating birthday or just cellebrated, so he can send a "happy birthday" message at the very morning, when he just turned on his computer. To avoid sending duplicated messages, he doesn't want to see the same person on multiple days at the list.

Your current sofware system already have all workers of the company with birthdates and their relationship, so you can figure out pretty easily who are the co-workers of the user and when is the birthdate of everyone.

Now, stop reading further, take your time and estimate the effort of this task by answering the following poll.

Okay, now I'll give you more information about it and ask for your estimate again.

Some religions do not celebrate birthdates and some people get really mad when receiving a message of "happy birthday". To avoid this, you also need to check if the user wants to make its birthdate public.

By the way, the customer's company closes at the weekend, so you need to take into account that at monday you will need to show birthdates that happened at the weekend and not only of the current day.

This also applies to holidays. The holidays are a bit harder as it depends on the city of the employee, as they may have different holidays.

Oh, and don't forget to take into account that the user may have missed a day, so it needs to see everyone that he would on the day that he missed the job.

Now, take your time and estimate again.

Part 2. The Dunning-Kruger effect on estimates

I don't know if the little story above tricked you or not, but that same story tricked me in real-life. :)

The Dunning-Kruger effect is stated at Wikipedia as:

"[...] a cognitive bias wherein relatively unskilled individuals suffer from illusory superiority, mistakenly assessing their ability to be much higher than is accurate. This bias is attributed to a metacognitive inability of the unskilled to accurately evaluate their own ability level. Conversely, highly skilled individuals may underestimate their relative competence, erroneously assuming that tasks that are easy for them are also easy for others."

I'm seeing that this effect contributes to make the task of estimating effort to be completely innacurate by nature, as it always pulls to a bad outcome. If you know little about it, you will overestimate your knowledge and consequently underestimate the effort to accomplish it. If you know much, you will underestimate your knowledge and consequently overestimate the effort.

I guess one way to minimize this problem is to remove knowledge up to the point that you only have left the essential needed to complete the task. Sort of what Taleb calls "via negativa" in his Antifragile book.

What do you think? Does this makes any sense to you?

Tuesday, June 30, 2015

Haskell is just some steps away from Java

Start with Java, then:
  1. Forbid using null;
  2. Use only immutable objects, add "final" modifier to everything;
  3. Swap methods by static functions with the the original "this" as the first argument, e.g. "" turns into "bar(foo)";
  4. Add a lot of features to the type system;
  5. Remove type annotations, i.e. "Foo bar(Foo self)" turns into "bar(self)";
  6. Remove useless parens, i.e. "bar(foo)" turns into "bar foo";
  7. Add call-by-need evaluation;
  8. Done, you have Haskell.
It's not that hard, is it?

One, using null references is a recognized bad practice, see "Null References: The Billion Dollar Mistake." Java 8 already provides the Optional type to stop using nulls.

Two, immutable objects are a win strategy, see posts by Hirondelle Systems, IBM, Yegor, and others.

Three, as you only have immutable objects, there is no reason to use methods instead of static functions, considering you maintain polymorphism (not quite the case for Java, but for the sake of this rant, consider as if it has this feature).

Four, improve the type system. The type system used by Java language misses a lot of features. If you don't feel it, just consider this as an added bonus. When you start using the type system features in your favor, you end up with much better code.

Five, imagine the Java compiler could infer the type of the arguments, so you don't need to type them everywhere. You still have the same static typing language, you just don't need to write the types. Shorter code means less liability to haunt you.

Six, why all those parens? Just drop them. Less code to write, hurray!

Seven, call-by-need just makes a lot of things easier (also makes a lot of things harder), but I really think it is a winner when you talk about productivity. When coding, I feel it a lot easier to express things in terms of values instead of steps (mathematicians have been doing this since long before computers). Expressing things in terms of values in a universe without call-by-need will result in a lot of useless computations, so call-by-need is a must.

Eight, done! This is Haskell. No functors, monads, arrows, categories or lists needed.

Why this post? Well, I don't know. It just occurred to me that if you really go into following good coding practices in Java (e.g. avoid null, use immutable objects), you will eventually feel familiar with functional code. Add some more things to the mix, and you end up with Haskell. I think people feel a bit scared at first contact with Haskell (and family) because of the academic and mathematical atmosphere it has, but in the end it is just a lot of good practices that you are kind of required to comply with.

Friday, March 20, 2015

Using Facebook's Flux architectural style for game development in Unity 3D

I decided to work again in an old game project. The game is named "Shotem" and the mechanic is quite simple: coins start falling from the sky and you need to "shot them" (got it?). Tap on a coin to shoot it, you gain score if you hit and you lose score if you miss the shot or if a coin falls off the screen (in case you didn't tap it). You have seven bullets to use, each shot (finger tap) consumes a bullet and you need to shake the mobile device to reload your bullets.

The game is still a work in progress, but I added the following video in order to show that it actually works in real life:

I'll write the history of the development process of this game. It started in a very naive form, then I converted it to Flux style and left it alone for three months. Now I'm coming back to it and had a pleasant surprise to read the code after forgetting about it. I think Flux style made it easy to continue the project were I left it. This post is 100% opinion based. Please, take a seat.

The first version I coded was very straightforward. Each coin was a GameObject with rendering and game behavior logic. All game state were inside a Singleton and two other objects were responsible for creating coins and handling user taps. Not organized at all.

I was interested in how to code the "reload by shaking" feature. As soon as I got it working, I lost my interest in the game mechanic itself. This happened quite fast actually, Unity 3D has a very nice class to use for dealing with the mobile device gyroscope: Input.gyro.

At the same time, I got in touch with Facebook's Flux architectural style. I tried it in some web projects and had a nice feeling about it. It seemed easier to write, maintain and understand code written in Flux style than the code written in MVC fashion. So, I decided to rewrite the code of Shotem in Flux style.

At first, it didn't seem to fit into Unity's way of doing things. But I worked it out and coded it anyway. It worked fine, then I left the code alone.

Three months later I'm coming back to this project and I didn't remember that I tested Flux style in it. At first I thought: "oh no, I'll need to delete this project and start it over, why did I do it?" Then I did read the code and look at the project structure: I was amazed at how easy it was to get things back on track, I were able to get productive again in less than five minutes! What a pleasant surprise!

Now, I feel that I should share this with the rest of the world. I appreciate feedback, so if you feel that using Flux style in game development is madness or if you feel like giving it a try too, leave a comment.

From now on, I'll use some terms from Flux, e.g. Store, Dispatcher, Action. I won't explain what are their meanings, so feel free to take a little detour and read the official Facebook's Flux website to get a summary of it.

I created a Dispatcher class to register the Stores, dispatch actions, track dependencies between Stores and ensure that the Actions do not cascade. The Dispatcher, in it's full glory, is here:

The core game mechanic is encoded in three Stores: CoinStore, handling all coins in the game; GunStore, handling player's ammunition; ScoreStore, tracking user score.

Player input may dispatch two Actions in the game: ShootAction and ReloadGunAction. To handle the physics of the game (falling coins), one Action is sent every FixedUpdate: PhysicsUpdateAction.

The Stores handle each action according to simple rules:

PhysicsUpdateAction is handled by CoinStore by spawning new coins, moving the coins in the screen and removing coins that are off the screen. ScoreStore waits for the CoinStore to finish and then updates the score by decrementing the amount of coins that were removed from CoinStore, because they have fallen off the screen. GunStore ignores this action.

ShootAction is handled by GunStore by decrementing player's ammunition. CoinStore waits for the GunStore and ignores the action if no ammunition was used, otherwise it checks for overlapping coins in the shot area and removes them. ScoreStore waits for GunStore and CoinStore then increases the score by each coin removed or decreases the score in case an ammunition was used and no coin was removed.

ReloadGunAction is handled by GunStore to reset the player's ammunition to seven. CoinStore and ScoreStore ignores this action.

That's the whole game logic. Each Store is observable, the Views register themselves to receive update notifications. When the Store handles an Action that changes its state, it triggers a notification. I've created an abstract class Store to handle this common behavior:

The listing below is the code of ScoreStore, the other Stores follow the same style:

Setup code is done in a Singleton GameObject's Awake method, I called it StoreHub because I use this to get the reference to the Stores from other Views:

ShotemActionGenerator is a helper class to create Actions and send them to Dispatcher, nothing fancy.

The View classes are also simple, for example, the game may play three different sound effects when the GunStore is updated: when a bullet is shot, when user tries to shot without ammunition left and when the gun is reloaded:

Another view shows the quantity of ammunition remaining, which are just children GameObjects with Renderers that I enable or disable based on the GunStore state:

There is a View to show the score, one to show a tip to remind the player to reload the gun when it's empty, another to handle the renderers of each coin visible in the screen, etc. The entire game is made in the same solid base, or may I say "solid flux". Data always flows in a single direction without cascading, there is always an Action that enters the system and triggers something, nothing happens if no Action is dispatched.

I don't know if this design can scale to a big game project, as the style as it is now depends on it running in a single core. But, none of my games are that intense, so I will try to finish this game with Flux. I guess that using Flux will also make it easier to create automated tests of the game mechanic, as it is self-contained. Maybe I'll post some follow up thoughts on it.

Below is an overview image of the current flux of the game. I decided to call "Inception" the layer that generates the Actions, Flux do not give it a name.

Thanks for your time,

Monday, February 23, 2015

Peg Solitaire

I'm proud to announce my new game: Peg Solitaire.

Peg solitaire is a classic board puzzle game for one player involving movement of pegs on a board with holes.

The objective is, making valid moves, to empty the entire board except for a solitary peg. A valid move is to jump a peg orthogonally over an adjacent peg into a hole two positions away and then to remove the jumped peg. Thus valid moves in each of the four orthogonal directions are:
  • Jump to right;
  • Jump to left;
  • Jump up;
  • Jump down.
The first challenge is to solve the puzzle, and then you can challenge yourself and try to solve it with the minimum number of movements. Each jump is considered a move, multiple jumps with the same peg are considered a single move, so you can keep jumping with the same peg and still count it as a single movement. The game displays the count of how many movements you have made at the top of the screen.

  • Multiple board types to select;
  • Five different board types: English (Standard), European (French), Wiegleb, Asymmetrical (Bell) and Diamond;
  • Display game move count;
  • Quick replay same board;
  • Give up current game;
  • Restart current game;
  • Shows system status bar, so you can keep track of other things while playing, for example current time
The game is entirely free and displays ads, there is no in-app purchase options.

It's made of web technologies (HTML, JavaScript, CSS) and deployed as a native application via Apache Cordova. Translated to six languages. Really exciting!

I tried to get the look and feel of each platform individually, using a flat design for iOS, a Material design for Android and a dark theme for Windows Phone. Take a look, I hope it's pretty obvious which screenshot belongs to which platform:

There are still updates to come. iOS has one in the queue for review process and I'm delivering another one for Windows Phone this week.

Take a look at the game, download, play it and leave a rating or feedback:

Hope to see you soon!

Saturday, December 20, 2014

Personal website

I'm proud to announce that I've created my own personal website.

I've finally purchased a domain for myself and now I have a place to use as a showroom of my personal games, take a look (and download them):

Also, my blog is now hosted at Nice! Right?

My vacations are just starting out and I already have a new domain.
Also, bought a slackline starter kit (I will try it for the first time), a frisbee, a boomerang and a frescobol kit!

I'm so happy. :)

Happy holidays to everyone!

Sunday, August 3, 2014

Code reuse considered harmful

The title is intended to call for attention. This post is about one perspective of software development in the light of my own experience in the area, it won't contain anything really revealing and is not to be taken as an absolute true for life. It's a rant. I hope you have a good time reading it, feel free to leave me any kind of feedback.

I see a bunch of people praising reuse as being the prime thing of good software development, and few talking about replaceability. There seems to be a constant seek to avoid writing code that is used only once, as if it was a really bad thing. Then we end up with software that is made of conceptual factories that create factories that create the things the software really needs, yes there are two levels of factories, or more. Is this really necessary? How much time do we save by this extreme look for reusing code?

First, let me ask and answer a simple question: why duplicated code is annoying? Well, duplicated code makes it harder to change stuff. When you have the same piece of code written multiple times in a code base and you find that it needs a change, e.g. bug fix or new feature, you will need to change it in all places. Things can get worst if you don't know all places where the code is duplicated, so you may forget to change one of these spots. The result is that duplicated code is a sign of harder maintenance and a fertile ground for further bugs to spawn. That's why we learned to hate it. We started fighting this anti-pattern with all strength we had.

Code reuse is the perfect counter to code duplication, right? Sure, it is right, if we reuse a piece of code in two places, we have no duplication between these places. So, we did it! We found the Holy Grail of code quality, no more duplicated code, yay! But something unintended happened. Remember the old saying: with great powers, comes great responsibility. People started to be obsessed with it. As soon as they learned to use the hammer of code reuse, everything turned into a nail, when it didn't work out in the first hit, they adjust the size of the hammer and hit it again with more effort.

This seek after code reuse led us to a plethora of abstractions that seems to handle every problem by reusing some code. Don't get me wrong, lots of them are useful, these are the ones that were created from observation. The problem is the ones that are created from "it's cool to abstract", or other random reason that is not true observation. We see frameworks after frameworks that try to fit every problem of the world into a single model. Developers learn to use these frameworks and suddenly find out that the framework creator is wrong and create yet another abstraction over it or creates yet another framework that tries to use a different model to solve the world.

What happens when we have a bug in one of these abstractions or we need to enhance it? Silence, for a while, then the sky turns black, you take a break, go for a walk, come back to your computer and start blaming the other developer that created the bug or that "got the abstraction wrong", because your vision was the right one. What happened? We reused code to avoid code duplication, but we are still having the same problems: code that is hard to maintain and evolve.

My guess? We missed the enemy. Code duplication is not our enemy. Maintenance problem and rigidity of code is.

My tip? Give more focus on replaceability of code instead of reuse in your talks, codes, classes, etc. Create the right abstraction to fix the problem at hand in a way that is easy to replace the underlying code when needed. Some time in the future, you will need to change it anyway. That's what agile methodologies try to teach us: embrace change. Planning for a design to be reused says: "my design will be so awesome, that I will reuse it everywhere." That's what agile says: "your design will need to change sometime, because the requirements will change, plan for the replaceability of it." People are doing things like service oriented architecture in the wrong way because they are looking for reuse of services and not for replaceability of services, they end up with a Big Web of Mud.

That's all folks. Thanks for your time.

Unity3D, Bejeweled and Domain-driven design

I'm working in a new game like Bejeweled. I'm happy with the freedom of code organization that Unity3D engine allows. During my first contacts with it, I thought that almost everything would be oriented to MonoBehaviour class, but this showed to be false. This class is necessary just as a glue point between any C# code and the objects of the engine. I'll report how I've started coding this game and the changes I made so far, you can watch the following video to see the current state of the game:

I started creating a GameObject for every entity that I identified in the game mechanics:

  1. Board
  2. Piece
The board contains every pieces and manages them:
public class Board : MonoBehaviour {
  private GameObject[,] pieces;
  void Awake() {
    pieces = /* Initialize pieces */;
The piece type is defined by a MonoBehaviour that exposes an enumeration:
public class Piece : MonoBehaviour {
  public PieceType Type;
public enum PieceType {

After the definition of the entities participating in the game, I started to code game's logic inside these classes. It worked for a while, but some problems appeared. The same classes had lots of different responsibilities (i.e. game's rules, animations, handling input) and this made it hard to code some stuff, because I needed to maintain a mind map of all concerns to avoid breaking something. Also, during animations, the board in memory was in an inconsistent state, waiting for the end of the animation to then continue processing.

Recently I've read some stuff about Domain-driven design (DDD) and decided to apply a bit of it in this game. My first step was to separate my code domain from the others, I selected game's mechanics as my core domain: if this part is not well behaving and it's hard to maintain, I'll be in a bad spot. Then I went to create this domain classes completely separated from the rest of the game, I ignored the existence of Unity3D at this point.

I only seen a single entity for this domain: the board. It makes no sense for the piece to exist on its own, everything that involves pieces always happens inside the board. I still have a class for the piece, but it is an internal thing of the board. My design became this:

public class BoardPosition {
  public readonly int Row;
  public readonly int Column;
  public BoardPosition(int row, int column) {
    Row = row;
    Column = column;

public class Board {
  private Piece[,] pieces;
  public Board() {
    pieces = /* Initialize pieces */;

#region Queries
  public Piece PieceAt(BoardPosition p) { /* ... */ }

#region Events
  public delegate void PieceCreatedDelegate(BoardPosition position, Piece piece);
  public event PieceCreatedDelegate PieceCreated;

  public delegate void PieceDestroyedDelegate(BoardPosition position);
  public event PieceDestroyedDelegate PieceDestroyed;

  public delegate void PieceMovedDelegate(BoardPosition from, BoardPosition to);
  public event PieceMovedDelegate PieceMoved;

  public delegate void PiecesSwappedDelegate(BoardPosition a, BoardPosition b);
  public event PiecesSwappedDelegate PiecesSwapped;

#region Commands
  public void SwapPieces(BoardPosition a, BoardPosition b) {
    ...; // Swap pieces
    PiecesSwapped(a, b);

  public void StepGameState() {
    ...; // Destroy pieces
    ...; // Move pieces
    ...; // Create pieces

    for (...) {
    for (...) {
    for (...) {
This way, the view part of the game register itself to handle the events generated by the board and update the user interface as needed.
public class BoardView : MonoBehaviour {
  private Board board;
  private GameObject[,] pieces;
  void Awake() {
    board = new Board();
    board.PieceCreated += HandlePieceCreated;
    board.PieceDestroyed += HandlePieceDestroyed;
    board.PieceMoved += HandlePieceMoved;
    board.PiecesSwapped += HandlePiecesSwapped;
    pieces = /* Initialize pieces based on 'board' */;

  public void HandlePieceCreated(BoardPosition position, Piece piece) { /* ... */ }
  public void HandlePieceDestroyed(BoardPosition position) { /* ... */ }
  public void HandlePieceMoved(BoardPosition from, BoardPosition to) { /* ... */ }
  public void HandlePiecesSwapped(BoardPosition a, BoardPosition b) { /* ... */ }

  void Update() {
    if (/* ... */) {
      board.SwapPieces(a, b);

This design made it hard to sync time between the model and the view. The model calls the methods of the view to notify about changes, the view has little space left to decide when to handle each event. In my case, some events started animations that needed to hold other events from happening, i.e. there is a temporal sequencing between some events.

I changed the model to return a list of events that happened at each command, instead of calling the handler directly:

#region Events
public interface BoardEvent {}
public class PieceCreated : BoardEvent { /* ... */ }
public class PieceDestroyed : BoardEvent { /* ... */ }
public class PieceMoved : BoardEvent { /* ... */ }
public class PiecesSwapped : BoardEvent { /* ... */ }

#region Commands
public List<BoardEvent> SwapPieces(BoardPosition a, BoardPosition b) { /* ... */ }
public List<BoardEvent> StepGameState() { /* ... */ }
Now, the view needs to call the handlers itself, but can decide when to handle each event:
public class BoardView : MonoBehaviour {
  private List<BoardEvent> events;
  void Update() {
    if (events.Count < 1) { events = board.StepGameState(); }
    foreach (BoardEvent e in events) {
      if (CanHandleNow(e)) {
    // ...
    if (HandledEverything) { events.Clear(); }
After this, I still felt that this temporal sequencing was not clear, it was "floating in the air". I decided to put it into the model, it's part of my domain: every event has a temporal identifier:
public class Board {
  private int timeCounter;
  public List<BoardEvent> StepGameState() {
    ...; // Destroy pieces
    for (...) {
      events.add(new PieceDestroyed(timeCounter, ...));
    if (eventHappened) { timeCounter++; }

    ...; // Move pieces
    for (...) {
      events.add(new PieceMoved(timeCounter, ...));
    if (eventHappened) { timeCounter++; }

    ...; // Create pieces
    for (...) {
      events.add(new PieceCreated(timeCounter, ...));
    if (eventHappened) { timeCounter++; }

    return events;

public class BoardView : MonoBehaviour {
  private int timeCounter;
  private List<BoardEvent> events;
  void Update() {
    if (events.Count < 1) { events = board.StepGameState(); }
    foreach (BoardEvent e in events) {
      if (e.When() == timeCounter) Handle(e);
      if (e.When() > timeCounter) {
        stillHasEventsToHandle = true;
    if (/*handledAnimationOfAllEventsOfMyTimeCounter*/) { 
      // Advance time perception of view
    if (!stillHasEventsToHandle) {
      events.Clear(); // Will step game state at next frame
Both view and model has a temporal identifier and the sync is more evident.

The actual code is looking very similar to the listed here. The model is handling well up to now. I feel bad about one thing: the Step command of the model may leave the board in a "not-consolidated" state, as it makes a single interaction to check for matching groups to be removed from the board. The view then needs to call the Step command more than once between handling two inputs from the user. I didn't want to make a lot of interactions in a single Step to avoid putting lots of stuff in memory before anything is handled by the interface, looks like a waste to me. I miss the lazy part of Haskell.

I still have lots of stuff to add to the game's mechanics (my core domain). I'll see the problems of this design in the next days and will post news with the next changes. Critics and suggestions are welcome.