And so, finally, me and Gustaf decided to put our writing skills together to form a new blog. Inspired (drugged) by coffee and cool technical terms such as TDD (Test Driven Development) and BDD (Behaviour Driven Development), we decided to call it Coffee Driven Development...
Please visit (and possibly subscribe to) the blog at:
http://CoffeeDrivenDevelopment.blogspot.com
That also means that this probably will be my last post here, unless me and Gustaf starts disagreeing on some odd topic and war is uppon us. Then I might come back here to write about why Gustaf is wrong. :)
But until then, see you at coffedrivendevelopment.blogspot.com!
Christian
söndag 27 april 2008
onsdag 16 april 2008
Retained or Immediate?
This topic is based on a discussion with a friend, Johannes, so many creds to him for sharing his experience and knowledge! Here you are Johannes, a can of coke! :)

Now, with that taken care of, let's get started :)
There are nowadays two ways of visualizing data, either using retained or immediate mode. In retained mode you have no control over the rendering your self, but put all your rendering setup in an internal data structure, which then is used by the renderer to know what to render. You don't tell the renderer directly how to render it, but "hey, here is my stuff, can you cache it for me and then render it when you want to". In immediate mode you render your data directly, by explicitly telling the rendering framework (OpenGl/DirectX) what you want to render.
Retained Mode
In games, retained rendering would typically be represented by a scene graph, looking something like this:
In gui rendering, this is often represented by gui controls holding their own states. For example a checkbox having an internal state "checked", which typically represents some logical value you store elsewhere in your application.
As you see, because the gui caches the value for you, you need to make sure to update your own internal state "myCheckedState" when the gui control chances state. And of course, if you change the value of myCheckedState you probably want to update the gui as well.
Immediate Mode
In the opposite method, immediate mode, you instead render all objects your self in an explicit rendering call. Instead of caching your state, and then letting an external renderer handle the rendering, you collect all your rendering into your own function, which when called renders your current state to the screen.
This is good because you don't need to cache your values anywhere, and have better control over the rendering. Instead of adding new nodes to your scene graph, which would probably be represented as new instances of a scene node class, you just add your function calls directly in your rendering method.
For window applications, this type of rendering hasn't been quite as accepted as in game rendering. In Java, though, I think most of their gui controls are represented as a view and a model (the so called model view controlled (mvc) approach). This is a good way of defining guis, as a view of some model. The gui should not store any values it self, but only reflect a model you define and maintain elsewhere. Unfortunately this is not possible in many other gui-platforms, such as in .Net.
There is another technique for gui rendering which, as far as I know, is relatively new. It is called IMGUI, or immediate gui. For a nice video explaining imgui, see:
http://www.mollyrocket.com/video/imgui.avi
IMGUI basically means that the gui has no state at all, and even no callbacks. The gui is only responsible for drawing the current state, which is drawn every frame, and at the same time returning any state. For example, to find out if a button is pressed, you make a rendering call such as:
This code will both render the button at position x, y, and return true if the button is being pressed. Because of this you need to render the gui ever frame (several times each second), but with todays graphic cards this shouldn't be a problem.
I won't go into detail about how to use IMGUI, but for another more complex example of how to use it, see Johannes post on www.spellofplay!
Which One is Best?
Now, the big difference between immediate and retained rendering is that in immediate rendering you specify, in your rendering loop, exactly what you want to render. This makes it more coupled, as the rendering must know of all the different types of models, instead of, as when using a scene graph, only telling the renderer that you want to render something that has "these properties". But in this case the renderer doesn't know what it is rendering. This is the reason immediate rendering is so much better. You know for sure what you are rendering, and can, based on this knowledge have more control over the rendering. You never get to a situation where you need to question yourself "am I rendering a can of coke?".
And that is where I want to get to in this post, that you always should strive for writing code so that you always know what data you are working on. Avoid using a generic base class for everything where you put a lots of virtual methods doing all your magic stuff, because
In school you learn to use scene graphs, to structure your code into a big hierarchy of classes, and to always prepare for the case when you "need to expand". Don't do that! Make it simple, don't prepare for the worst, don't make your classes super generic. Write code that does exactly what it should, no more, no less, and always try to make it as readable as possible. That is my tip to you today!
Now, with that taken care of, let's get started :)
There are nowadays two ways of visualizing data, either using retained or immediate mode. In retained mode you have no control over the rendering your self, but put all your rendering setup in an internal data structure, which then is used by the renderer to know what to render. You don't tell the renderer directly how to render it, but "hey, here is my stuff, can you cache it for me and then render it when you want to". In immediate mode you render your data directly, by explicitly telling the rendering framework (OpenGl/DirectX) what you want to render.
Retained Mode
In games, retained rendering would typically be represented by a scene graph, looking something like this:
void SetupRenderer()
{
SceneNode node = new SceneNode();
node.Mesh = myMesh;
node.Transform = Matrix.Create(...);
renderer.SceneGraph.AddNode(node);
}
In gui rendering, this is often represented by gui controls holding their own states. For example a checkbox having an internal state "checked", which typically represents some logical value you store elsewhere in your application.
void SetupGui()
{
CheckBox b = new CheckBox();
b.Checked = myCheckedState;
b.OnCheckedChanged += OnCheckBoxCheckedChanged;
}
void OnCheckBoxCheckedChanged(object o, EventArgs e)
{
myCheckedState = (o as CheckBox).Checked;
}
As you see, because the gui caches the value for you, you need to make sure to update your own internal state "myCheckedState" when the gui control chances state. And of course, if you change the value of myCheckedState you probably want to update the gui as well.
Immediate Mode
In the opposite method, immediate mode, you instead render all objects your self in an explicit rendering call. Instead of caching your state, and then letting an external renderer handle the rendering, you collect all your rendering into your own function, which when called renders your current state to the screen.
void Render(State myState)
{
Mesh playerMesh = getPlayerMesh();
foreach( Player p in myState )
{
renderer.RenderMesh(playerMesh, p.Position, p.Orientation);
}
}
This is good because you don't need to cache your values anywhere, and have better control over the rendering. Instead of adding new nodes to your scene graph, which would probably be represented as new instances of a scene node class, you just add your function calls directly in your rendering method.
For window applications, this type of rendering hasn't been quite as accepted as in game rendering. In Java, though, I think most of their gui controls are represented as a view and a model (the so called model view controlled (mvc) approach). This is a good way of defining guis, as a view of some model. The gui should not store any values it self, but only reflect a model you define and maintain elsewhere. Unfortunately this is not possible in many other gui-platforms, such as in .Net.
There is another technique for gui rendering which, as far as I know, is relatively new. It is called IMGUI, or immediate gui. For a nice video explaining imgui, see:
http://www.mollyrocket.com/video/imgui.avi
IMGUI basically means that the gui has no state at all, and even no callbacks. The gui is only responsible for drawing the current state, which is drawn every frame, and at the same time returning any state. For example, to find out if a button is pressed, you make a rendering call such as:
if (gui.DoButton(x, y, "Press me!"))
{
// Button was pressed
}
This code will both render the button at position x, y, and return true if the button is being pressed. Because of this you need to render the gui ever frame (several times each second), but with todays graphic cards this shouldn't be a problem.
I won't go into detail about how to use IMGUI, but for another more complex example of how to use it, see Johannes post on www.spellofplay!
Which One is Best?
Now, the big difference between immediate and retained rendering is that in immediate rendering you specify, in your rendering loop, exactly what you want to render. This makes it more coupled, as the rendering must know of all the different types of models, instead of, as when using a scene graph, only telling the renderer that you want to render something that has "these properties". But in this case the renderer doesn't know what it is rendering. This is the reason immediate rendering is so much better. You know for sure what you are rendering, and can, based on this knowledge have more control over the rendering. You never get to a situation where you need to question yourself "am I rendering a can of coke?".
And that is where I want to get to in this post, that you always should strive for writing code so that you always know what data you are working on. Avoid using a generic base class for everything where you put a lots of virtual methods doing all your magic stuff, because
- Reading such code is a hell because you never know what will happen when you call that function, until you actually run it
- The code will get very coupled as you need to put all your specific implementations at the same place, unless you:
- Use the visitor pattern (requires a lots of code, and a new class for each new type of action to perform on the types).
- Use reflection (non-portable solution, what if you change an entity type to another?).
void Render()you should write:
{
foreach(Entity e in entities)
{
e.Render();
}
}
void Render()You move the render specific stuff out from the entity you are trying to render and into the rendering code, where it should belong. You also know for sure exactly what types of entities you have in your world, and can thus perform different tasks depending on the type directly, instead of first trying to resolve the type using different techniques.
{
foreach(Player p in players)
{
RenderPlayer(p);
}
foreach(Enemy e in enemies)
{
RenderEnemy(p);
}
foreach(CanOfCoke c in canOfCokes)
{
RenderCanOfCoke(c);
}
}
In school you learn to use scene graphs, to structure your code into a big hierarchy of classes, and to always prepare for the case when you "need to expand". Don't do that! Make it simple, don't prepare for the worst, don't make your classes super generic. Write code that does exactly what it should, no more, no less, and always try to make it as readable as possible. That is my tip to you today!
söndag 6 april 2008
Experimenting with syntax highlighting
Every code blogger need syntax highlighting, so no exception for me! After struggling some with different scripts, I finally got it to work! Doesn't it look good?! :)
// Example comment
class X
{
int p;
}
söndag 30 mars 2008
Dedefending my case: Stop documenting your code!
Here is my response to Peters post - Do comment code!:
First off, I think it's okey to be critical, you should not take anything for granted, and of course we all have our own ways of programming. My post was more of a tip based on my own experience from working in a larger team with no/little code documentation.
I'm not saying you should avoid all documentation, but documenting every class and function is always redundant if the documentation doesn't state anything new. You should always strive for having code that is easy to read, before putting comments around everything you do.
Here are some final notes from me:
First off, I think it's okey to be critical, you should not take anything for granted, and of course we all have our own ways of programming. My post was more of a tip based on my own experience from working in a larger team with no/little code documentation.
Commenting code isn’t as much about pinning down knowledge, as it is communication. And when it comes to communication, redundancy is almost never a problem :)Commenting code is communication, but you are communicating knowledge. The same knowledge is always communicated through the code. If you find it hard to "read" the code, then, in my own experience, the code is not well written and/or formatted. Make sure you have a coding policy stating how you should write code so that all code looks the same and can be easily "parsed by your brain". It's amazing how much easier it is to read code that is well written and formatted.
I'm not saying you should avoid all documentation, but documenting every class and function is always redundant if the documentation doesn't state anything new. You should always strive for having code that is easy to read, before putting comments around everything you do.
And another thing, without documentation, I might misunderstand the code I’m reading and think that I find defects or suboptimal solutions.That's true. Of course you can have comments here saying "don't use this function this or that way", but perhaps there is another way of writing the function so that it can't be used incorrectly? If you write a method and document in the header that this function should only be used if some requirements are met, then I guarantee you that this function sooner or less will be misused. Make sure you add requirement checks (for example assertions) in the beginning of the function breaking the program, so that you crash early if someone make such misstates. But always strive for writing code that is impossible to use incorrectly.
And then there’s the case with APIs that you don’t have the code to… Ok ok, thats another story.If you are shipping your code to another company, or group of programmers, then you always need to communicate what the code does, because the code you shipped is persistent and will not change. Thus, the comments you write will always be correct (if being correct when shipped). And if you don't ship along your implementation, then of course you need to document your code, but more importantly, document your project as a whole. Do this by describing how it should be used and what the subparts of the project does and how they communicate with each other. Focus on the big picture.
But hey, you can’t possibly mean that I shouldn’t document my Assembly code, do you? Super haxxor might read and understand ASM as I understand English, but the vast majority don’t.Well, if the super haxxor wrote the code then he or she will in most cases be the only one reading it and than you don't need documentation. If the assembly code is only a small part of the project which is written in another language (say C++), extract the assembly code and put it in it's own function describing what it does. By doing so, you will also make the code more easy to test and validate! A better question might be, do you really need assembly code?
Saying that documenting/commenting code is wrong, is saying ‘I don’t care if other people are able to read my code, and if they don’t understand their lazy and dumb’. And thats lazy and dumb :-)I'm saying that if you write your code so that a follows a well written coding policy, you will not have any problems with reading the code. If you feel that some code you have written needs to be documented, stop a second and think about it. Is there another way of formatting the code so that it's easier to read? What if I extract a part of this function as a new function, giving that function a good name, would that help? What about using coding policies for variable naming conventions? Adding prefixes such as m_ for member, p_ for parameter and l_ for local will for example quickly let you identify the scope of a variable.
Here are some final notes from me:
- If you are working on a larger project, then your comments will become deprecated sooner or less. You must alway be aware of the fact that any code you write now will probably be changed in the future (no code is perfect).
- Always strive for as little code as possible. The more code you have, the more code you need to maintain. The same goes for comments.
- Write comments in unclear situations, but don't write trivial comments. Instead, define a good coding policy and start writing "easy to read" code!
torsdag 27 mars 2008
Twitter and Counter Posts
Gustaf recommended me this site called twitter, which seems to be a great way of finding out what your friends are doing right now. Like a mini-blog where you write max 140 lines of text. I have just tried it out, but recommend you all to test it and to find out if you like it. Hanselman wrote a nice blog on this twitter-thing - read it at:
http://www.hanselman.com/blog/TwitterTheUselessfulnessOfMicroblogging.aspx
And also, if you haven't read the comments on my last post, Peter posted a comment, which he also posted as a "counter-post" on his own blog, describing why you should comment code. There are some nice arguments, so please read it. Of course I'm planning a "counter-counter-post" on my blog, put you have to wait some more days before I will release it into the public :)
http://www.hanselman.com/blog/TwitterTheUselessfulnessOfMicroblogging.aspx
And also, if you haven't read the comments on my last post, Peter posted a comment, which he also posted as a "counter-post" on his own blog, describing why you should comment code. There are some nice arguments, so please read it. Of course I'm planning a "counter-counter-post" on my blog, put you have to wait some more days before I will release it into the public :)
tisdag 18 mars 2008
Stop documenting your code!
I've been reading this interesting book for a while now, The Pragmatic Programmer by Andrew Hunt and David Thomas. I was actually planning to blog about it first when being finished, but my mind is just going crazy about some stuff I've read recently, and thus I feel the need to blog about it now!
The book is based on "tips" that can easily be memorized and used again later when you put your programming hat on. One of these tips, which especially caught my attention, and which is going to form this post, describes the following principle:
Instead, think about the following for a second: being a programmer, does repeated knowledge only apply to code? What about comments? What if you comment a function, doesn't this mean you repeat knowledge? For example, look at the following code:
This is obviously repeated knowledge, right? Both the name of the function and the implementation perfectly describes what it does. Is there really a need for documentation here? I know from experience that in many cases you write comments like this, just because you should write something.
So what about a more difficult case:
If the comment didn't state that "" is returned when no level is loaded, then you could actually think it should throw an exception when no level is loaded, or that you would get the name of the previously loaded level (or if you are using C# or Java that null should be returned). But once again, knowledge is repeated. Just look up the implementation and it will state exactly what it does.
Fact is, the implementation is the only "valid" documentation, because it's the only one you will know for sure is true. How many times haven't you written a function, documented it, then later in the development process realized that this function needs to be changed. You change the code but are a bit too lazy to update the documentation. Suddenly you have invalid knowledge! Isn't it better then just to remove the comment and let anyone who wants to know what it does open up the implementation and actually read the code?
If you find it too hard to find out what a function does, you probably need to refactor the function by giving it a more descriptive name, extracting larger independent blocks of statements, rename your variables (members, parameters and local) to something more descriptive (i.e. don't use "temp"!) and so on. If this doesn't work, then you are either bad at reading others code (which is a good practice in order to become a better programmer!) (I hope you know how to read your own code!? :) ) or the code you are looking at is really bad and should be removed as quickly as possible. You don't want to maintain such code.
Reading code should be like reading a book! You don't want the author of a book to add a lots of comments everywhere describing everything a second time in other words. The same goes for writing code, you should not add comments repeating what you have already written in another language.
So, my tips to you is this: refactor your code, and remove those comments!
The book is based on "tips" that can easily be memorized and used again later when you put your programming hat on. One of these tips, which especially caught my attention, and which is going to form this post, describes the following principle:
DRY - Don't Repeat YourselfThis basically means that you should not repeat knowlegde. Further the book states that:
Every peace of knowledge must have a single, unambiguous, authoritative representation within a system.Well, you say, this is trivial, you should not write two peaces of code that does the same type of work. If you for example have two functions being very similar, then you use refactoring and extract the common code into a new function. If you have two classes representing two different branches of some common structure, then you extract what is common, put it in a new base class, and let the two classes inherit from this new base class. But this you probably already know, so I will not bore you with this anymore.
Instead, think about the following for a second: being a programmer, does repeated knowledge only apply to code? What about comments? What if you comment a function, doesn't this mean you repeat knowledge? For example, look at the following code:
// Sets the name of the player
// @param name The new name of the player to set
void SetPlayerName(string name)
{
mPlayerName = name;
}
This is obviously repeated knowledge, right? Both the name of the function and the implementation perfectly describes what it does. Is there really a need for documentation here? I know from experience that in many cases you write comments like this, just because you should write something.
So what about a more difficult case:
// Returns the name of the currently loaded level
// or "" if none is loaded.
string GetCurrentLevelName();
If the comment didn't state that "" is returned when no level is loaded, then you could actually think it should throw an exception when no level is loaded, or that you would get the name of the previously loaded level (or if you are using C# or Java that null should be returned). But once again, knowledge is repeated. Just look up the implementation and it will state exactly what it does.
string GetCurrentLevelName()
{
if (mCurrentLevel != null)
return mCurrentLevel->mName;
else
return "";
}
Fact is, the implementation is the only "valid" documentation, because it's the only one you will know for sure is true. How many times haven't you written a function, documented it, then later in the development process realized that this function needs to be changed. You change the code but are a bit too lazy to update the documentation. Suddenly you have invalid knowledge! Isn't it better then just to remove the comment and let anyone who wants to know what it does open up the implementation and actually read the code?
If you find it too hard to find out what a function does, you probably need to refactor the function by giving it a more descriptive name, extracting larger independent blocks of statements, rename your variables (members, parameters and local) to something more descriptive (i.e. don't use "temp"!) and so on. If this doesn't work, then you are either bad at reading others code (which is a good practice in order to become a better programmer!) (I hope you know how to read your own code!? :) ) or the code you are looking at is really bad and should be removed as quickly as possible. You don't want to maintain such code.
Reading code should be like reading a book! You don't want the author of a book to add a lots of comments everywhere describing everything a second time in other words. The same goes for writing code, you should not add comments repeating what you have already written in another language.
So, my tips to you is this: refactor your code, and remove those comments!
onsdag 12 mars 2008
Gimpel Software Bug of the Month
Finally someone made games for us programmers ;) Check it out!
Gimpel Software Bug of the Month
And if you find them to be a bit too trivial, here is a harder case (actually the post where I first found out about this "Bug of the Month" site):
Visual C++ Team Blog : Diagnosing Hidden ODR Violations in Visual C ++ (and fixing LNK2022)
That one was really tricky (I couldn't solve it), but was fun reading!
Have fun :)
Gimpel Software Bug of the Month
And if you find them to be a bit too trivial, here is a harder case (actually the post where I first found out about this "Bug of the Month" site):
Visual C++ Team Blog : Diagnosing Hidden ODR Violations in Visual C ++ (and fixing LNK2022)
That one was really tricky (I couldn't solve it), but was fun reading!
Have fun :)
Prenumerera på:
Inlägg (Atom)