torsdag 16 oktober 2008

The ForEach extension method (C#)

Everyone knows about the foreach keyword, but have you ever noticed there are no equivalent extension method for IEnumerables? I.e. execute "this action" on each element. Perhaps the most simple extension method of them all, which is the reason I'll share it with you :)

public static class MyExtensionMethods
{
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
foreach(var item in list) action(item);
}
}

For you who aren't familiar with extension methods, what it really says is that, ForEach is a member method of IEnumerable<T>, and can be called by simply writing
myList.ForEach(myAction)

For example, to output each item of a list to the console, you could write:
myList.ForEach(x => Console.Write(x));

instead of
foreach(var x in in myList) Console.Write(x);

In this case you might not gain so much in terms of code size, but I think it makes the code more readable. You are reading text from left to right, so it makes sense having the for each statement to the right, right? :)
myList.WhereThis().SelectThat().DoThis();

(There is probably some kind of cool name for this pattern, like "The opposite of law of demeter"... Gustaf probably has more knowledge in this!)

Here is a more complex example of a combination of extension methods:
myList.Where(x => x.IsValid()).Select(x => x.ComputeValue()).Where(x => x > 0).ForEach(x => Console.Write(x));

Where and Select are also extension methods of IEnumerable. Without these you would have to write:

foreach(var x in myList)
{
if (x.IsValid())
{
var value = x.ComputeValue();
if (value > 0) Console.Write(value);
}
}

8 lines instead of 1! Impressed? :)

So, extension methods! Learn them, use them, and write your own!

lördag 6 september 2008

ClickOnce deployment or not?

Some weeks ago, I developed a small program in C# called P4 Explorer. To distribute it, i used a technique called ClickOnce deployment, which is a part of Visual Studio C# Express 2008. This blog post will be about what ClickOnce deployments are, how they can be used, and why you in the end shouldn't use them...

ClickOnce
ClickOnce deployments will simplify your deployment a lot. To deploy your application, all you need to do is:
  1. specify the location to publish the application (i.e. a network drive, web site or ftp),
  2. specify from what location the users will install it from (propably the same as 1), and
  3. decide whether the application should be installed at the start menu, or always must be started from the install path (2).
Furhermore you can specify if the application automatically should check for updates, which is really great if you plan to update your application frequently. You then specify how often the it should check for updates, and when an update is found, the user will be notified and can download the latest version. All by only selecting "The application should check for updates". Very nice!

Now, for you to deploy a new version, all you do is click "Publish". When the user then starts the program, the update will be found and installed (if permitted by the user). Very easy!

Limitations
Application Path
ClickOnce deployment doesn't come for free though. First of, the application won't be installed under "C:\Program Files\MyCompany\MySoftware" as you might expect, but at some secret place (hidden from the user and developer). If you decide to let the installer add a shortcut to your start menu, there is no way to find out where this shortcut points, as it's not a normal shortcut. Right clicking on it and selecting properties will not give you the information you expect, i.e. the path to the executable.
Now, there is a simple way of finding out the path of the executable. When starting the installed application, the property Application.ExecutablePath will be correctly set and you can thus be used to, for example, add to the PATH environment variable:
void UpgradePathVariable()
{
string l_ApplicationFolder = Path.GetDirectoryName(Application.ExecutablePath);
string l_PathVariable = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
if (!l_PathVariable.Contains(l_ApplicationFolder))
{
l_PathVariable = l_OldPathVariable + ";" + l_ApplicationFolder;
}
Environment.SetEnvironmentVariable("PATH", l_PathVariable, EnvironmentVariableTarget.Machine);
}

Parameters
Also, because the program doesn't have a fixed installation path, there is no support for sending parameters to the program. I.e. args in static void Main(string[] args) will always be empty. The documentation at MSDN states that the only way to send parameters to a click once application is to deploy it at a web page, and let the user send html-parameters to it, i.e.:
http://www.yourdomain.com/yourapplication.exe?parameter1=val1&parameter2=val2
But
  1. this requires your application to be deployed using a web page, and
  2. you must always download the installer every time you need to sent parameters to the program.
Say for example you want to let the user start the program by right clicking on a file in explorer and selecting "Open in my program". You would need to add a line in your registry pointing to the executable file:

pathtoyourexe "%1"

This would be both slow and hacky if using the recommended http-style mentioned above. Instead, by using the Application.ExecutablePath property, you can actually access the physical path to the installed executable, and thus add this path to the registry. With this setup correctly, right clicking on a file and selecting your program to open it with, will open the program and send the parameter correctly to it!

Settings
But, even though everything might seem to work out fine, you will soon notice that the Settings object defined in your application will be different if starting the program using the shortcut from your start menu, or right clicking on a file. They are not sharing the same application settings. And if you upgrade the program, all settings in your "right clicked version" will be gone, because the new version will be installed in a new folder.

In the end
Even though click once applications are really easy to deploy, and give you a lot for free, the limitations just makes them really hard to work with. Making simple applications might work, but as soon as you want the user to interact with it through the explorer shell, you are better off making your own installer (or using a free one such as NSIS). So in the end I decided to deploy my program manually using a source control, which made all my problems go away. Sending parameters worked, settings worked, and the application had a fixed folder!

The only thing I was really missing from ClickOnce was the ability for the program to automatically check for updates, which was something I really needed to make sure everyone using my application had the latest version (hopefully having less bugs in it). But it turned out this wasn't so hard to make on my own! The pseudo code for it, printed here, is divided in two programs - your main application, yourapp.exe, and the upgrade application, upgrade.exe.

yourapp.exe:
  1. Is there a new version available (i.e. check using source control)
  2. Copy upgrade.exe (and dependencies) to a new folder "temp"
  3. Start new process temp\upgrade.exe
  4. Close program
upgrade.exe:
  1. Make sure all instances of yourapp.exe are closed
  2. Download the latest version (i.e. using source control)
  3. Start new process ..\yourapp.exe
  4. Close program
You can always make it faster by running the check for new version in it's own thread, and only checking every x hour, but the main thing is that I get the same features as if running with ClickOnce, but don't need to limit my application as much as you do with ClickOnce applications!

So, ClickOnce, good for small application, not good for more advanced applications.

fredag 8 augusti 2008

Google Calendar



I love Google Calendar, mostly because of the free sms service, sending you an sms x minutes before an event. What's the point of otherwise having a calendar if you only get notifications from it when sitting in front of a computer, such as how ms exchange and similar works. "You need to be at the dentist in 30 minutes", well hopefully I'm sitting in front of the computer when this message pops up. Of course you can always install a mail service in your mobile, and receive a mail when an appointment is about to happened, and you can buy an expensive mobile phone having it's own calendar which you then can sync with the computer from time to time. But for me, I just want to say "at that time, I need to be there, and wherever I am 30 minutes before that, notify me". That's why I love google calendar, because you can be anywhere and still get a notification!

Now, that's all glorious and so, but as always there are some problems - I want to be able to sync it with other calendars, so that I don't need to open up a browser, enter the adress, and log in every time I need to add an event. For Mozilla Thunderbird there is an add on to support calendars called Lighting, and for this add on there is another one called Provider for Google Calendar, which makes it possible to view and update the google calendar from the calendar within Thunderbird. Niiice!

But hey, wait a minute, the reason I wanted to support google calendar in the first place was because of it's sms service, but as it turns out, the google calendar provider for thunderbird doesn't support this :( So in the end I still need to access google calendar from within a web-browser, and change the settings of all my events manually.

So that's where I'm now, still looking for the perfect solution. Google calendar is still the best option for me, but if you know about a better one then please let me know...

måndag 2 juni 2008

Hacking VS C# 2008 Express

VS C# 2008 Express is a really nice product in many ways - you've got most of the stuff you need, but most of all, it's free!

Though, I was playing around for it a bit, and needed to support compiling against a specific platform (x86 instead of Any CPU which is default). The reason for this was that, in my project, I was refering to a dll written in managed c++ - compiled for x86! Mixing x64 and x86 is never a good solution, and as C# projects per default compiles against Any CPU they will run in 64-bits mode on a 64-bit computer. When the application tries to load the 32-bit dll, the application crashes...

Now, in VS C# 2008 Express, you cannot specify another target platform but the Any CPU platform. Guess they think that "if you need support for specific platforms, you should be able to pay for a commercial version".

I was reading through MSDN, and found this note:
Note /platform is not available in the development environment in Visual C# Express.

"Damn", I thought, "this is the end. But what does development environment mean?". I had to try it out manually using the command prompt, so I compiled the project in VS and copied the command line output from the output window, being something like:
C:\WINDOWS\Microsoft.NET\Framework\v3.5\Csc.exe /noconfig /nowarn:1701,1702 ...
I put the line in a batch file, and added the /target:x86 flag, compiled it and... it worked! The project got compiled using x86 as a target platform.

As it turns out, VS C# 2008 Express does support the /target option, and probably others as well. They only lack the support for the option in the IDE, which is kinda a hacky way of disabling a feature, IMO.

Now, I don't want to build the project using a batch file every time, I would like to build it inside VS IDE so that others can easily build it. As the VS project files are nothing but XML, you can easily open them up in any editor you like to see their contents. I did this to find out if there was some way to add a target flag to the compiler, but unfortunately I couldn't find anything interesting (of course that would be too easy!). I continued with searching the web, and found this strange property:
CSharpProjectConfigurationProperties3.PlatformTarget Property
This member provides internal-only access to C# project configuration properties.
...
External components can access these properties through the Properties collection for the appropriate Visual Studio automation object.
"Well", I said to my self, "the Properties collection would probably refer to the XML properties found in the project file, so once again I opened up the project file, and browsed to two property groups being:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
and
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
In these groups, I added the PlatformTarget property:
<PlatformTarget>x86</PlatformTarget>
I saved the file, reloaded it in VS, recompiled the project... and viola, it worked! All you needed to do was to find out the magic property to add to the project file! :)

This proves that C# Express contains more under the hood than what's visible to the eye. With a simple editor, and some knowledge on how to search MSDN, you can get a lot out of this product!

måndag 12 maj 2008

What is your favorite language?

We all have our favorite language, but for most people it's almost religious to discuss which language is the best. I realized I don't know what language people really prefer, simply because I've never discussed it!

Having a look at TIOBE Programming Community Index for May 2008 got me thinking. You will see Java in top, followed by C and then (Visual) Basic. I couldn't get this, until I read the following:
Observe that the TIOBE index is not about the best programming language or the language in which most lines of code have been written.

Of course, Java produces a lots of lines of code, and C has been around for a long long time. Visual Basic I can't say why is rated third, but I guess every newbie programmer develops in VB, and also, you have all those macros! I guess those makes up for a few lines?! :)

C# is only at 8'th place, but I hope that's because you don't need to write as much code in it as you do with other languages... which probably isn't true because you DO write a lots of code in it. With C# 3.0 you can use synthetic sugar to write less code, but not that much ;) I really think the reason C# is not being that highly ranked is because it hasn't been around for that long. People are still experimenting with it, and those companies that has been around for a while can't see the reason for replacing Java with C#. But, in the future, when everyone is jumping off Java, C# will grow in popularity!

Anyway, I added a vote to this blog (in the left sidebar), so go ahead and vote on your favorite language. And, if you want, post a comment on this post, arguing for why you think your language is the best!

lördag 10 maj 2008

C# Lambda Lazy List FizzBuzz :)

Ok, so here is my next example of an implementation of the FizzBuzz problem. I'm going to use a combination of C# 3.0's lambda expressions, lazy lists and extension methods!

First, I create a function returning a lazy list over all numbers starting from 1:
static IEnumerable<int> AllNumbers()
{
int i = 1;
while (true) yield return i++;
}
Second, I create a function returning a lazy list of strings, being pText every pCount time. I.e. null, null, Fizz, null, null, Fizz.
static IEnumerable<string> FizzBuzz(int pCount, string pText)
{
while (true)
{
for (int i = 0; i < pCount-1; i++)
{
yield return null;
}
yield return pText;
}
}

Now, I need a way of combining the values two lists, so I create an extension method for this. It takes another list and a combinator function:
static IEnumerable<T> Combine<T, TA, TB>(this IEnumerable<TA> pA, IEnumerable<TB> pB, Func<TA, TB, T> pCombineFunc)
{
var i = pA.GetEnumerator();
var j = pB.GetEnumerator();
while(i.MoveNext() && j.MoveNext())
{
yield return pCombineFunc(i.Current, j.Current);
}
}

And here is the whole FizzBuzz program, returning a list of strings being 1, 2, Fizz, 4, Buzz...:
static IEnumerable<string> FizzBuzz()
{
return AllNumbers().Combine(
FizzBuzz(3, "Fizz").Combine(FizzBuzz(5, "Buzz"), (x, y) => x + y),
(x, y) => (y != "") ? y : x.ToString());
}

To write the result to the console, I use this main function:
static void Main(string[] args)
{
foreach (string fizzBuzz in FizzBuzz().Take(100))
{
Console.WriteLine(fizzBuzz);
}
}

Thats it! Nice and easy eh? :) Hope you liked it and perhaps makes you look into C# 3.0, if you haven't already? You can always download Visual Studio 2008 C# Express for free if you want to try it out!

Edit: Changed generic parameters <T> to html-characters. Changed C# 3.5 to 3.0 (thank u Gustaf :))

torsdag 8 maj 2008

C# FizzBuzz :)

Here is my thoughts and solution to Gustafs Functional FizzBuzz problem! It's more or less a copy from what I wrote as a comment in his old blog, except for some modifications in the code snippet below.

I believe that in almost all cases, where you should write a solution for a given problem, you have two solutions to choose from. The first one focuses on writing well looking, readable, code (which is always good), the second focuses on writing fast code (which is required in some projects).

My solution for a bit faster code (I guess), would be this (c# style):

for (int i = 1, j = 1, k = 1; i <= 100; i++, j++, k++)
{
string t = "";
if (j == 3)
{
t = "Fizz";
j = 0;
}
if (k == 5)
{
t += "Buzz";
k = 0;
}
if (t == "")
{
t = i.ToString();
}
Console.WriteLine(t);
}

The difference is that you don't need to call "x `mod` m == 0" to find out if you should print Fizz or Buzz, instead two extra counters are used to keep track on when to write Fizz and when to write Buzz. I guess you could write this in functional style as well, but my haskell skills are a bit out of date so I wouldn't dare to try that ;)

söndag 27 april 2008

New blog at CoffeeDrivenDevelopment.blogspot.com

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

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:
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
  1. Reading such code is a hell because you never know what will happen when you call that function, until you actually run it
  2. The code will get very coupled as you need to put all your specific implementations at the same place, unless you:
    1. Use the visitor pattern (requires a lots of code, and a new class for each new type of action to perform on the types).
    2. Use reflection (non-portable solution, what if you change an entity type to another?).
So, instead of writing:
void Render()
{
foreach(Entity e in entities)
{
e.Render();
}
}
you should write:
void Render()
{
foreach(Player p in players)
{
RenderPlayer(p);
}
foreach(Enemy e in enemies)
{
RenderEnemy(p);
}
foreach(CanOfCoke c in canOfCokes)
{
RenderCanOfCoke(c);
}
}
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.

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.
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 :)

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:
DRY - Don't Repeat Yourself
This 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 :)

lördag 8 mars 2008

C++ vs. C#

For you who think that C# is the master language, why really is it? C++ has been around for soon 30 years, and is still considered to be the one language for many developers. You might say that those developers are a bit out of date or conservative, only sticking to the one language they learned several years ago, but the thing is I really think C++ has some interesting stuff not supported by other languages such as C#.

Memory Control
For one think, C++ has total memory control. You can allocate memory when every you want to and then use it any way you like. Then, when you don't need the memory you release the memory manually. This means of course that it's easy to shoot your self in the foot and forget to release the allocated memory, but also that you aren't required to have a garbage collector running in background thread taking up important cpu power (if the cpu power is important). Also, garbage collectors can only release an instance when there are exactly no references left to it left, so if there are circular references then those can never be released (except when exiting the application).

The garbage collector can thus not remove something on demand. For example, at some point in your program you might know for sure that "this instance is not going to be used any more, if it is then there is a bug", but you don't know for sure that there are no references left to it (perhaps you put it in a list somewhere and forgot to remove it?) and thus the garbage collector might not remove it and your memory consumption will grow larger and larger. After running your program for some time you will notice that the memory usage becomes large, and because you have no control over memory you cannot simply search in the code for a missing "delete" statement (which you can in C++, or actually search for new with a missing delete). And because the garbage collector can clean up the memory when ever it wants to, you cannot rely on the destructor being called at an appropriate time. C# (or Microsoft) thus doesn't recommend you to use destructors, but rather to implement a method such as void Dispose() which you must call manually to dispose any unmanaged resources being held by that object (you can actually use destructors, but what if you in that destructor adds a reference to the object somewhere? Suddenly the object is alive and shouldn't be destructed...). But if you forget to call Dispose in your code, you could easily lock up resources and get unpredictable behaviors.

In C++ you have better control to whether put something on the heap or the stack. If on the stack, you know that the destructor will be automatically called when leaving the scope, something not possible to do using C#. In C# you instead need to implement the Dispose method, and then create an instance of that class in a using-block, which will automatically call Dispose when the instance leaves the scope. There is no other way to do this in C#. If you for example have a lock helper class that automatically locks a given object when constructed and releases the object when being destructed, you could write code like this in C++:
void doDangerousStuff(Object &a, Object &b)
{
LockScope lockScopeA(a);
LockScope lockScopeB(b);

// Do dangerous stuff on a and b
}
In C# you could write this:
void doDangerousStuff(Object &a, Object &b)
{
LockScope lockScopeA(a);
LockScope lockScopeB(b);

// Do dangerous stuff on a and b

lockScopeA.Dispose()
lockScopeB.Dispose()
}
But what if you got an exception in the middle of the code? Then the Dispose() method would not be called, so instead you should use the using keyword:
void doDangerousStuff(Object &a, Object &b)
{
using( LockScope lockScopeA(a) )
{
using( LockScope lockScopeB(b) )
{

// Do dangerous stuff on a and b

}
}
}
But this doesn't look good, and what if you need to add more locks on other variables, the code would just grow more and more to the right, and at least to my opinion that's something you should avoid to the max. C# thus doesn't give you a good solution to this problem.

Actually, in C#, you can control whether to put something on the heap or on the stack. Classes are automatically put on the heap when allocated, and structs are stored on the stack. This means that it theoretical should be possible to call the destructor when the instance of a struct leaves the scope, but unfortunately C# doesn't allow you to add destructors to structs, so no good luck there :(

Headers and Linkage Errors
Another positive thing of C++, which some of you might find confusing, is the possibility to declare a function in a header, but then never implement it. This lets you design a class without actually giving an implementation. If you then try to compile the program you will not get any compiler errors but instead linkage errors. This means that "the code looks good, but I couldn't find the definition of these functions". You cannot do this in C#. Instead you need to add a method with an empty body, and in that body you throw an exception or assert false. Thus, instead of getting linkage errors, you get runtime errors.

The Const Keyword
I just can't figure out why languages such as Java and C# doesn't support the use of a const modifier. In C++ you can state a class method to be const, meaning it can't modify the state of the object. This is very useful if you for example want to pass an object by reference to a function, but want to make sure it isn't modified. You then mark is as const, and the function can only call the methods declared on that object that are marked as const. The state of that object will thus remain unchanged.

In Java and C# this is not possible. In Java you can at most (at least to my experience) send primitive types such as int, byte and float which will be passed as values (copies) and thus any change of these values in the function will only affect the copy. In C# you can do something similar, but even structs will be passed by value, enforcing the state of that object not being changed. This though would require you to rewrite every class you want to be able to pass to a function without it being modified, which of course isn't a very pleasing solution. Quite the opposite actually, as it also enforces you to make copies of the object every time you want to use it in another function.

To get around this (at least what I think) Java and C# have implemented some classes that are immutable. One such class is the String class. If you have ever examined this class you might realize that there is no way to modify it, it is fixed. To change it you actually have to instantiate a new string which holds the changed value. So, functions taking strings as parameters cannot modify them, even though they are passed by reference. But is this the solution you want for your big universal state that you want to pass a function which should not modify it?

Macros
One last thing to mention about C++, and which is also not supported by C#, is macros. A macro can totally destroy your code, but also let you write complicated beautiful code in only a few lines. If you for example have a lots of classes that you want to register to a factory, instead of writing:
factory.RegisterClass("MyClassA", &MyClassA::Constructor);
factory.RegisterClass("MyClassB", &MyClassB::Constructor);
you can define a macro and simply write
#define REGISTER(class) factory.RegisterClass(#class, &class::Constructor)
REGISTER(MyClassA);
REGISTER(MyClassB);
Isn't that cool? You can actually do a lot more complicated stuff if you want to, and even generate default class implementations this way. With macros you can do anything! The closest thing to macros you have in C# is reflection. With reflection you can for example extract the name of a class dynamically, and get a function from a class based on a string (the name of that function), but if that class hasn't implemented that function you will instead get a runtime error. In C++ this error will appear when compiling!

Why C# Still is Cool :)
But to turn to the other side of the street, C# isn't that bad after all. Compiling C++ code will give you a headache if compared to compiling C# code, which will only take a few seconds. Also, running C# code isn't actually that much slower than you might think. In some cases you will actually find out that your code is equally fast in C# as in C++! And C# has a lots of cool features not supported at all by C++ (and many other languages) such as properties, attributes, partial classes, yield and lock statements, coalesce operator ??, just to mention a few. And with C# 3.5 you have support for even more nice stuff, such as lambda expressions, LINQ and extension methods.

Actually, the reason to why I'm not writing a post on why C# is better then C++ is that it's so trivial :) C# have so many things C++ misses out on, but I just felt I had to write this article so that people don't think that C++ is nonsense. Because it isn't! At least in the gaming industry, C++ is still the leading language, with the reason probably being "you have more control" and "it's fast"! And around 2009, the next version of C++ is planned to be shipped, called C++0x, which hopefully will give the language a boost to survive the future!

måndag 25 februari 2008

Visual Studio Code Snippets and Macros

In this first real post I'll try to explain something called macros in Visual Studio, and how they can make your work (programming) easier. I just recently found out about them, and realized that they resemble something I've been missing in the C++ environment of VS for a long time; code snippets! If you don't know what code snippets are, then here is a short description:

Code snippets are short keywords in your C# document, which when you double-press tab will be converted into C# code! If the code is parameterized, over for example different names or types, then these parameters will be selected first so that you can easily change them. If you for example write prop and double-press the tab key, a new property will be added to the class you are in.
prop <tab><tab>
becomes
private int myVar;

public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
where int, myVar and MyProperty are parameters which can easily be changed. There are a lot of nice code snippets to use in the C# environment, making coding easier. Just goto Tools -> Code Snippet Manager... or press Ctrl+K followed by Ctrl+B for a list of possible snippets.

But for C++ this doesn't seem to exist. I read something about code snippets being available for C++ in VS 2003, but somehow they where removed in VS 2005.

So this is where macros comes into play! With a macro you can more or less do what ever you want to do. You just create a macro, write the code for it (in VB) and then use it from the macro explorer within VS. To make it even more powerful you can bind keyboard shortcuts to these macros (Tools -> Options... -> Environment -> Keyboard). To show the currently available macros, activate the macro explorer using either Tools -> Macros -> Macro Explorer or by pressing Alt+F8. By default you will have a list of sample macros installed, which are great for playing around with and to get familiar with macros.

So, what then can you do with macros, you ask yourself. Well, for example you can write macros that automatically adds new classes, with a default header and cpp-file, based on a class name. You just tell VS to add two files to your current project, and then put some the class definition in the header, and some default implementations of perhaps constructors and destructors in your cpp-file. Or you can create a macro that cleans up headers and cpp-files, by searching in the code using regular expressions for #include "ClassName.h", and then comment this include if ClassName can't be found in the code. The possibilities are really endless!

So if you are developing in VS using C++, or actually any language supported by VS, and haven't used macros, then go ahead and try it out. It's amazing what you can do! Or if you are developing in C# and haven't tried code snippets then I really encourage you to learn about them. As have been said before: to be a good programmer, you must know your tools!

söndag 24 februari 2008

Free coffee with Gustaf and ideas of sharing knowledge

So, the idea of this blog is to try to share the knowledge I'm gaining when reading other blogs, listening to podcasts, discussing with friends over coffees, reading books or what ever. As mentioned in an episode of Hanselminutes: to become a better programmer you should try to write the knowledge down and share it with other people. So that's what I will try to do in this blog!

But not now, because it's too late :)