Tag Archives: development

D2TM Rewrite – Development Blog – SDL initialization & initial game setup

In my previous post I have described a way to compile your project with a Maven style like project structure. Using that as basis I am busy rewriting my project Dune II – The Maker. This time I am using SDL.

Because I have started over I thought of writing blog posts about my progress. Blog posts will be about progress made, decisions taken, etc. This is by no means a real tutorial sequence, but you could follow the blog posts probably and make something out of it. Do note: In reality I am much further in development then my blog posts. The blog posts are based upon older revisions than HEAD. If you are interested in the most recent version you can get the source yourself.

In this blog post I will describe how I have started to setup the project. I already have a directory structure as described in my previous blog post.

My goal is to have a primitive architecture set up, I have used the first SDL tutorial as starting point.

The reason I went with a tutorial is that I wanted to be inspired by a different approach than I have done myself in the past. In fact, I have always just tried to do what I thought what was best. In this case I took the tutorial and from there I will change it how I think it should be. Its never bad to take a fresh look at things ūüôā

The very first start was to create a Game class, it has the following class declaration:

[sourcecode language=”cpp”]
#ifndef GAME_H
#define GAME_H

#include <SDL/SDL.h> /* All SDL App’s need this */

class Game {

public:
int execute();

private:
bool running;

int init();
void shutdown();

void handleEvents();
void update();
void render();

void onEvent(SDL_Event * event);

SDL_Surface * screen;

};

#endif
[/sourcecode]

The only function that needs to be exposed is the execute method. All other functions are used internally.
The SDL surface screen represents the main display (screen).

The Game class is implemented as follows:

[sourcecode language=”cpp”]
#include "gamerules.h"
#include "game.h"

#include <iostream>

using namespace std;

int Game::init() {
if((SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)==-1)) {
printf("Could not initialize SDL: %s.n", SDL_GetError());
return -1;
}

screen = SDL_SetVideoMode(640, 480, 16, SDL_SWSURFACE);
if ( screen == NULL ) {
printf("Unable to set 640×480 video: %sn", SDL_GetError());
return -1;
}

return 0;
}

void Game::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
onEvent(&event);
}
}

void Game::onEvent(SDL_Event * event) {
if(event->type == SDL_QUIT) {
running = false;
}
}

void Game::update() {

}

void Game::render() {

}

void Game::shutdown() {
SDL_Quit();
}

int Game::execute() {
if (init() != 0) {
return -1;
}

while (running) {
handleEvents();
update();
render();
}

shutdown();

return 0;
}
[/sourcecode]

The execute function does basically everything. A game loop is in essence very simple. In fact the game is one big loop which does two things:
– update state
– show state

To update state, in this case we have separated two things:
– handle events (in SDL terminology, this means we handle input events. Which can have effect on the game state)
– update (here you actually update the game state)

That still remains updating game state, though a bit more split up. We could later split it into keyboard/mouse states. But, these things all are depended on the certain kind of game state you’re in. A main menu screen should react differently on mouse input than lets say the actual game playing. The current design has not given any direction yet what to do. We could have one big switch statement, but we could also do something better… I’ll come to that in a future blog post.

The init function basically sets up the application. I am not too happy about this in this stage, but for the initial setup it is good enough. I believe the factory pattern should be used for constructing a game object though, so I have already created a class for it. The reason is that i want to respect the Single Responsibility Principle. Constructing a Game object, which requires loading resources, setup SDL, etc, has nothing to do really with the basic Game object itself. In fact, as you will see in later blog posts, the Game object has the only responsibility and that’s calling all the right collaborator classes that make the game what it is.

Since I already know I will be using a factory class I already introduce one which for now does nothing spectacular:

Header:

[sourcecode language=”cpp”]
#ifndef GAMEFACTORY_H
#define GAMEFACTORY_H

#include "game.h"

class GameFactory {

public:
Game create();

};

#endif

[/sourcecode]

Implementation:

[sourcecode language=”cpp”]
#include "gamefactory.h"

Game GameFactory::create() {
Game game;

// TODO: load resources for game, do SDL initialization, etc.

return game;
}
[/sourcecode]

Finally the main.cpp which has the entry point of the application:

[sourcecode language=”cpp”]
#include "gamefactory.h"

int main(int argc, char **argv) {
GameFactory gameFactory;
Game game = gameFactory.create();
return game.execute();
}
[/sourcecode]

And thats it! The result is a game that is able to start, it has functions that declare several phases in the game and allows us to expand it further. Because of the factory we can also easily move initialization code out of the Game class.

If you would compile this, and run it, you would see:

A running application

As for developing applications, I believe a certain principle lies behind it. Most of it, you won’t really see. Often, with a few lines of code you can make a lot of stuff happen on the screen. But the actual work is ‘under water’:

How stackoverflow helps me to solve problems, without posting questions…

I really love stackoverflow. It brings developers, good ones, together. And because of the community active there, many questions I had where answered.

However, I dare to say half of my questions where answered by not posting any question

The reason why? Its simple. In order to get the answer you seek, you need to specify the problem precisely. Just posting “it does not work” with some vague description is not enough. It really helps to tell how you stepped through the problem, post snippets of code and so forth. If you are able to specify your problem like that, chances are high (at least with me) that the solution comes along with it. A so called “aha” moment. To me it is like Rubber Ducking. By the time you are half-way through writing down the exact problem you probably figured out the problem yourself.

The good news:

  • You probably found 9 out of 10 ‘doh ofcourse its so obvious’ issues. Preventing you to post ‘stupid’ questions…
  • You end up posting really hard questions (making you look so smart).

The better news:

  • There are people out there who are even smarter than you! And make you smarter in return!
  • You do not have to talk to a real rubber duck at your desk, just type your question at stackoverflow. (your co-workers will stop worrying about your mental state, talking to that duck all the time).

Its a win win win!

In other words…
[sourcecode language=”java”]
Answer answer = null;
try {
Question question = formulateQuestionPrecisely();
answer = stackOverFlowService.postQuestionAndGetAnswer(question);
} catch (AhaMomentException ame) {
// never mind, found the solution myself!
answer = ame.getAnswer();
}
[/sourcecode]

Thanks stackoverflow!

(don’t forget to credit those who give the best answers.. it’s highly appreciated)

Now I just read that posting your question, while you know the answer already, is a good thing. So the next time… consider that (but make sure your question has not been asked for already :)).

EasyMock and Mockito, a little comparison

Someone mentioned a mocking framework called Mockito some time ago to me. I am familiar with mocking frameworks, as I work with EasyMock quite a lot. I really like EasyMock, but I am curious about Mockito. I thought of trying it out a bit and write down my experiences along with a comparison with EasyMock.

This is by all means not a very in-depth comparison, but I did find out some interesting things.

In order to test out the mocking frameworks I have set up some code in place to test. The code to be tested is an ‘itemRepository’ (It is however, not a full implementation of the Repository Pattern). Typically you use it to get some stuff (Items). In this case the Item is retrieved from a Dao object used by the repository. Just for easiniess the DAO returns the same object as the repository. (The repository pattern makes a distinction between the object the DAO returns and the Domain objects the Repository should return).

Here is the code of the ItemRepository:
[sourcecode language=”java”]
public class ItemRepositoryImpl implements ItemRepository {

private ItemDao itemDao;

@Override
public Item getItem(String someInput) {
return itemDao.getById(Long.valueOf(someInput));
}

public void setItemDao(ItemDao itemDao) {
this.itemDao = itemDao;
}

public ItemDao getItemDao() {
return itemDao;
}

}
[/sourcecode]

My goal is to test the ItemRepository’s getItem method. And all I care about is that the itemDao is correctly called with the correct parameters. Hence this is what a collaboration test is all about.

Lets start with my comfort zone: EasyMock

The test class I write talks to interfaces. I find it a good habit to talk against interfaces and not concrete implementations. Doing that however, forces me to cast to an implementation to set collaborators in the tests. Normally such things happen in the @Before. But since I will also create a test with the Mockito framework I have it done in the test method itself.

The begin of the test:
[sourcecode language=”java”]
public class ItemRepositoryTest {

private ItemRepository itemRepository;
private ItemDao itemDao;

@Before
public void setUp() {
itemRepository = new ItemRepositoryImpl();
}
[/sourcecode]

In line of the tripple A testing guidelines I have an arrange, act and assert:
[sourcecode language=”java”]
@Test
public void mustReturnItemFromMockedItemDao_EasyMock_Behaviour() {
ItemRepositoryImpl impl = getItemRepository();
itemDao = EasyMock.createMock(ItemDao.class);
impl.setItemDao(itemDao);

// this is weird: I don’t *want* to bother about returning stuff here, just that it is called!
// mocking and stubbing is combined here
EasyMock.expect(itemDao.getById(1L)).andReturn(null);
EasyMock.replay(itemDao);

// Act
itemRepository.getItem("1");

// Verify
EasyMock.verify(itemDao);
}
[/sourcecode]

As you can see I have pointed out one thing of EasyMock’s behaviours with a comment. Whenever you mock a method that has a return type, EasyMock expects you to fill in that behaviour. If you don’t do that, you’ll end up with an exception like this:

java.lang.IllegalStateException: missing behavior definition for the preceding method call getById(1)

In this case I have ‘solved’ it by returning null. While writing the test, I did not want to be bothered about it, but I have to satisfy EasyMock. Doing so reduces the readability of my code. The intention of the code remains unclear at this point, and that’s something I’d like to avoid as much as I can.

Another well known behaviour of EasyMock is the need to replay your mock after you have set the expectations. Using a ‘recorder’ metaphor it sounds reasonable. But basically you’re writing the behaviour ‘twice’: First you write down the expectations, then you actually run them. Writing the expectations is often found to be a cumbersome job to do, especially with multiple collaborators.

And of course at the end it all needs to be verified. Which is done by EasyMock.verify. We could even check the outcome. Most of the time you’re tempted to do so, you had to write the return value anyway. Better test if the return value being returned is the same as the method returns right? I think not. Reason: your intention of your test becomes unclear if you assert this as well. And as a bonus you introduce your tests to be more fragile. The unit test becomes now a collaborator test and a value-based test in one. Mockito makes this distinction very clear.

Mockito:
[sourcecode language=”java”]
@Test
public void mustReturnItemFromMockedItemDao_Mockito_Behaviour() {
// Arrange
ItemRepositoryImpl impl = getItemRepository();
itemDao = Mockito.mock(ItemDao.class);
impl.setItemDao(itemDao);

// Act
itemRepository.getItem("1");

// Assert / verify
Mockito.verify(itemDao).getById(1L);
}
[/sourcecode]

Plus:
– no need to mock return etc, as we dont care
– seperation of mocking and stubbing (stubbing is done by using the static method when, mocking by using verify).

So how about stubbing in Mockito? Here is how you stub the itemDao:

[sourcecode language=”java”]
@Test
public void mustReturnItemFromMockedItemDao_Mockito_Stubbing() {
// Arrange
ItemRepositoryImpl impl = getItemRepository();
itemDao = Mockito.mock(ItemDao.class);
impl.setItemDao(itemDao);

Mockito.when(itemDao.getById(1L)).thenReturn(null);

// Act
itemRepository.getItem("1");
}
[/sourcecode]

For more information about Mockito, they also have a more extensive comparison between EasyMock and Mockito.

Do you have any experience using Mockito and EasyMock and you would like to share some insights? Please leave a comment.

Someone pointed at RhinoMocks also being available for Java. I’m not so sure about that. However, if you do know about a Java variant, let me know so I can compare it as well.

How to fry your co-developers brain; and then make it better

Here is a little example of code I’ve been faced with (not written by me), that struck me. Although the syntax is correct (it is javascript), it took me a little while to actually understand what is going on.

Here is the code:
[sourcecode language=”javascript”]
someObject: function(data) {
return data.json ? data.json.stateObject ? data.json.stateObject : {} : {};
},
[/sourcecode]

And here is how I refactored it.
[sourcecode language=”javascript”]
someObject: function(data) {
if (data.json) {
if (data.json.stateObject) {
return data.json.stateObject;
}
}
return {};
}
[/sourcecode]

So I mentioned brianpower in a while ago. Michael Feathers though calls such a thing “forming a mental model“. Which is exactly what I meant. You also hear this in the scene of Usability; the less your mental model matches with the actual object you use (expectations), the less likely you’ll probably understand it, let alone *use it*.

So tell me, which one is easier to understand? And how much impact do you think this has?

Tiny refactorings? Compose Method!

I blogged about tiny refactorings not too long ago. I’ve even added an example showing such a refactoring in my game.

I’m reading Refactoring to Patterns, and figured that the refactorings I’ve mentioned have a name; it’s called the Compose Method. In the book it even has its own chapter (Chapter 7 “Simplification”), where it also refers to other great patterns to help you improve your maintainability of your code.

Creating (default) test instances of a class, without exposing default constructor.

Did you ever need to just have an instance of a class you cannot instantiate because the default constructor is not available? Do you want to create a test instance just to be used in unit tests? Don’t want to break up the design of your code just for testing? This post might help you:

Sample code:

[sourcecode language=”java”]
public MyClass {
final int someField;

private MyClass() {
// may not use this
someField = -1;
}

public MyClass(int someFieldValue) {
someField = someFieldValue;
}

int getSomeField() {
return someField;
}
}
[/sourcecode]

So lets say this class is used in a lot of places. And all we want is have a default test instance. We don’t care about the internals. Lets say we only use it to toss around using an interface which we mock in our tests. Like so:

[sourcecode language=”java”]
public void someUnitTestUsingMyClassAndMockingAnInterface() {
MyClass instance = new MyClass(-1); // this works, but its not really descriptive
MyClass someotherMyClass = new MyClass(-1); // like, what is -1? we don’t want to be bothered by this
EasyMock.expect(someinterface.doSomethingWithMyClass(instance)).andReturn(someotherMyClass);

}

[/sourcecode]

There are two ways to approach this problem:

  • Make private constructor public
  • Use a Factory or a creation method

So, just making the default constructor public sounds easy and is used very often. And, because we want to let our fellow developers know it is just to be used in unit-tests we place a comment in them. This mostly results in something like this:

[sourcecode language=”java”]
public MyClass {
final int someField;

public MyClass() {
// Use this only in tests!
someField = -1;
}
[/sourcecode]

However, this has a few drawbacks:

  • You cannot see if the default constructor should only be used for tests, unless you look into the code itself and read that comment line
  • You broke with the initial design decision to have only objects instantiated with a given “someField”

So how do we prevent this?

We use a factory, or a creation method. Lets start with the first, the factory: If there is a factory, just use it to get a test instance. If the factory lacks a ‘createTestInstance()’ method, then add it. Like so:

[sourcecode language=”java”]
public MyClassFactoryImpl implements MyClassFactory {

public MyClass createTestInstance() {
return new MyClass(-1);
}

}
[/sourcecode]

We could discuss about wether you want the method to be factory method to be static here, and so forth, but the idea is clear.

However, when there is no factory present it is unlikely you want to create a factory just for your unit tests. In that case I suggest you use the creation method, also refered to as the factory method pattern. Simply add a public static method that returns a new instance. The final result would be:

[sourcecode language=”java”]
public MyClass {
final int someField;

public static MyClass createTestInstance() {
return new MyClass();
}

private MyClass() {
// may not use this
someField = -1;
}

public MyClass(int someFieldValue) {
someField = someFieldValue;
}

int getSomeField() {
return someField;
}
}

[/sourcecode]

The benefits are clear:

  • The default constructor remains private, so the design is left untouched
  • It is clear what the createTestInstance method does. No comments needed.

And in your unit test (using EasyMock as well) it looks like this:

[sourcecode language=”java”]
public void someUnitTestUsingMyClassAndMockingAnInterface() {
MyClass instance = MyClass.createTestInstance();
MyCLass someotherMyClass = MyClass.createTestInstance();
EasyMock.expect(someinterface.doSomethingWithMyClass(instance)).andReturn(someotherMyClass);

}

[/sourcecode]

Note: When you wind up with multiple create methods you should consider using the Factory pattern instead. Yes, creating a factory is the best thing once creation logic starts to dominate your class. (ie, think of the Single Responsibility Principle).
Note 2: If you’re a design purist, you might even debate that the public constructor of MyClass should be a creation method. It improves consistency as all instances are created by creation methods. It also has the benefit of describing what kind of instance you get (ie, what the field means). Such improvements are valid and should be made. I consider these improvements small refactorings. They should never be undervalued.

The tremendous power of tiny refactorings

More and more I am being intrigued by the power of a small code refactorings. The positive impact it has on the readability, the maintainability and understandability of your code is great. It keeps code clean(er) and since the changes you make are really small (I’ll demonstrate how small),¬†the chance they will break things is small. Of course, with unit tests (you are writing them right?) making sure you did not break anything: a¬†small refactoring is a low-risk high-benefit practice.

In my experience, small refactorings are undervalued. In fact, I undervalued them much myself since not too long ago. They are disregarded as refactorings that don’t help at all, because it is obvious what the code does. However, the flaw in this rationale, as I see it, is that the intended audience is not only¬†you but also the other developer you work with. Also, you know what code does right now. But would you understand it as quickly if you did not look at it for a week and came back? Would another developer understand the code right away?

When working on code, you’re constantly trying to ‘translate’ the code in your mind in order to know what it is doing. Doing this it leads you to where the bugs are or the areas where you need to make changes, etcetera. This process of ‘translating’ code in your mind comes at a price. Literally the energy you need to burn in your brain to grasp the meaning of a piece of code:¬†brainpower; The easier we understand code, the less brainpower we need. The less energy we burn by understanding what is going on, the more energy we have left to create new things, or fix that bug.

I’ve created a little example. The code below represents an implementation of a mail service. The mail service allows you to send an email using a method that uses 4 parameters: to, from, the subject and the message. When all parameters are filled, the email needs to be sent. That is the only requirement for now. Of course, later we might want to validate if the given email adress of from and to are valid. But for the sake of the argument, lets keep it simple. The following code is ‘mind-boggling’, compared to its simple intention:

[sourcecode language=”java”]
public class MailServiceImpl implements MailService {

public void sendMail(String from, String to, String subject, String message) {
if (from != null && !"".equals(from) &&
to != null && !"".equals(to) &&
subject != null && !"".equals(subject) &&
message != null && !"".equals(subject)) {
// send the email
}
}

}
[/sourcecode]

Basically what this says it that any field may not be null or an empty string. It took 4 lines for just to show. Even though you recognize the pattern of a ‘null or empty check’, it costs you time and energy to make that translation happen. So here is a first suggestion to make it¬†read easier:

[sourcecode language=”java”]
public class MailServiceImpl implements MailService {

public void sendMail(String from, String to, String subject, String message) {
if (parametersAreNotNullOrEmpty(from, to, subject, message)) {
// send the email
}
}

private boolean parametersAreNotNullOrEmpty(String from, String to, String subject,
String message) {
return from != null && !"".equals(from) &&
to != null && !"".equals(to) &&
subject != null && !"".equals(subject) &&
message != null && !"".equals(subject);
}

}
[/sourcecode]

When another developer is reading the sendMail method, he will now know that when the parametersAreNotNullOrEmpty the mail will be sent. It does not need any translation, the method name just says what it does! Simple! By doing this, you greatly reduce the needed brainpower to understand what is going on. The refactoring method used is called Extract method.

Reading code is sometimes easy for your brain to handle. Sometimes your brain seems to explode because of the complex statements and context you need to be aware of. It is strongly tied with the Cyclomatic Complexity, the Coupling between Objects (CBO) and the lack of Cohesion in your code. If you are using any tools to measure your code, like Sonar for example, look for these metrics to find code that needs attention. But it is always better to refactor while you have made the translation in your brain, if you see things can be written simpler to reduce the needed brainpower, by all means do so. Not giving software the appropriate attention might let your code rot. Small refactorings help you prevent that.

I hope you have seen a bit of the power of small refactorings. I will get back to them in my future posts as I will post more concrete examples and how I would/have dealt with them. To me, small refactorings need to be part of your system and are introduced when you do TDD. All too often when the code works, it is not looked at again. Making these small refactorings can make a big difference and take relatively no time.

The bare minimals to get started with iOS development

In order to get started for iOS development, you need to do a few things:

– Get yourself a mac (the cheapest is the mac mini)
– Get and install XCode
Register yourself as an Apple Developer (bound to your Apple ID)
– Get Access to the iOS Dev Center (you need to be an Apple Developer)

Of course, you need to learn Objective C and you need to know some fundamentals about programming in a broad sense.

Once you’ve got this, you can get started. Tons of information there. Thats where I will start, more updates will follow!