Properties in C#

I’m a new C# programmer. I’m using it for a project at work. Doing an ASP.NET MVC project. So far I’ve been very happy with the language. It has some nice stuff built in. ASP.NET MVC is pretty nice too. It’s almost as easy to use as rails. So, all in all, I’m pretty happy, but today I ran into something stupid.

I have a method that is trying to do a TryUpdateModel(model, new[] {"prop1", "prop2"}); call and my model wasn’t getting updated. I checked out the associated FormCollection and sure enough my values were in it. The problem was in how I was defining my model.

public class MyModel
{
   public int prop1;
   public DateTime prop2;
}

Can you see the problem?

It took some digging, but it turns out that prop1 and prop2 as defined above are not properties. They are public members of the class MyModel. In order to be properties you need to assign them getters and setters like so:

public class MyModel
{
   public int prop1 { get; set; }
   public DateTime prop2 { get; set; }
}

My frustration is that prop1 and prop2 from my perspective as a consumer don’t really change with the new definition. It seems weird I should have to do that. I’m a new C# programmer and I totally believe that in 3 months more of working with this language I might become a purist and understand the reason to have these things behave differently, but for someone new to the language this isn’t the most intuitive approach.

Sleeping your Mac with a Microsoft Ergo 4000 Keyboard

One of my friends, who will remain nameless for the purpose of this discussion, convinced me start playing around with a Microsoft Natural Ergo Keyboard 4000. I got one at work, then I bought one for the home and I’ve been pretty happy with it. There are just a couple of things missing from my standard mac keyboard.

Firstly, on my old computer, I used to be able to hit the a keyboard combination to get my machine to sleep. I believe it was something like Cmd – Shft – Eject. Well, the Microsoft keyboard doesn’t have Eject. So I’m out of luck there. It does, however, have a set of buttons reserved for favorites. So I decided to code up a little AppleScript and bind it to one of these keys. Here’s the script, and I just saved it as an editable application. Then you can go into the preference pane for the keyboard and assign the whichever key you want to this script. Good luck.

1
2
3
tell application "finder"
   sleep
end tell

Handspringman.com

For those of you who have known me for more than, say, five years, you know that one of my original web properties was handspringman.com. Unfortunately, due to issues with the way domain registration works, it slipped out of my control. At the time it was prohibitively expensive to reposes (somewhere in the several hundred dollar range).

Well, good news, it’s coming home. I recently checked it’s availability on GoDaddy and was able to procure it relatively inexpensively. I will do my best to put something up there soon.

Modified JustSimple WordPress Theme

I’m not much of a PHP guy, but I chose WordPress for this blog because I feel it is the most stable, well refined, yet easy to use blogging tool out there. Once the platform was decided I started looking for themes that worked well. I finally found something that I really liked when I stumbled on Ciaran Walsh’s blog. The theme is called JustSimple.

It’s a great theme, and I enjoy it on my site, but there areas where it has come up short. Mostly in styles for certain elements. I started a simple github project for my changes to JustSimple Project. One such change I’ve made is to add support for Definition Lists. Terms are bold and definitions are padded left.

If you want, you can download the theme from github (with a shameless use of the definition list):

Zip Format
Zip File
Tar Format
Tar File

C++ Coding Standard: The If Block

Almost two months ago I went to a CocoaHeads meeting during Macworld. They had Mike Lee talk. His presentation was about “Pimping Your App”. There were a bunch of interesting points, but one thing really stuck in my head. Mike was talking about how is a messy person in his life. His car is messy. His room is messy. His desk is messy. Everything is messy, except his code. HIs code is crystal clean, squeaky even. As a programmer you need to make sure your code is consistent and clean. Ever since I have been thinking about standardizing the way I write code. This is the first post in hopefully a stream of posts about quality code.

Yesterday, there was a discussion in the office about code quality. There were many points discussed, topics like line length, white space, and my personal favorite “if” statements. I have a track record of being incredibly inconsistent with my “if” block. The basic if block is the following:

if(foo) {
  //...
}

The “if” statement by itself is really not that big of a deal. It’s when you start adding “else if” and “else” clauses that it becomes complicated. The problem for me is twofold. Firstly, I’m inconsistent. The type of blocks I use on larger sections of code is different from the blocks I use on smaller sections of code. Secondly, my desire for consistency is at odds with my crazy, cooky desire to have code look aesthetically pleasing.

The Condensed If Block

I sometimes use the following style of the if statement:

if( foo ) {
   //...
} else if( bar ) {
   //...
} else {
   //...
}

This block is very condensed. You throw the braces for each clause on it’s own line. I feel that it this type of statement makes it clear and easy to really make the if statements a smaller part of the code. On trivial if blocks, I really like this approach. Where it suffers is in more complex if statements. If the ifs and else ifs fit really just blend into the code, sometimes making it easy to miss them. Okay, so if I’m looking at the code in detail, not a big ideal, but if I’m just giving it a quick glance over I might miss something. Also, if the “if” statement line is long enough, it could easily blend into the line below it.

The Almost Condensed If Block

This one is a take on the Condensed If block. It is actually just really poorly formatted “if” statements, but I often find myself using this one:

if( foo ) 
{
   //...
} else if( bar ) {
   //...
} else {
   //...
}

All we are doing here is moving the opening brace from the end of the if statement to the next line. The rest of the code follows the condensed. So, I really like this approach because the first “if” block is clearly separated from the rest of the code. It’s clear that we are are entering an “if” statement line. The remainder of the statements don’t take up too much space. The closing brace, the else if/else, and the following opening brace are all on the same line.

The downside of this approach is that it looks inconsistent. Why does the initial “if” statement get one extra return, and all the subsequent lines statements get jammed into one line? It’s not functionally different, and it might in general be more appealing to me, but consistency is also important. I have started to shift away from using this style.

The Intermediate If Block

This one has more white space:

if( foo ) {
   //...
}
else if ( bar ) {
   //...
}
else {
   //...
}

This approach has gives you a little bit more separation of the control statements from the code. For some reason, though, I just feel it looks weird to write the close brace on its own line but then incorporate the opening brace on the same line as the control statement. Still feels inconsistent.

White Space Heaven If Block

The following block is the last if style I’m going to talk about:

if( foo ) 
{
   //...
}
else if( bar )
{
   //...
}
else 
{
   //...
}

This block takes up a very large amount of space, everything gets its own line. It is probably the clearest of all the examples above, but the trade off is that your code is now three lines longer for each else statement. This extra space means that you can theoretically fit less code in the same amount of screen space.

Additional Concerns

There are a couple of additional concerns when working with if blocks. For example, if you are chaining “if” blocks, how much space should you provide.

// What I don't like
if(foo)
{
   //...
}
if(bar)
{
   //...
}

// What I prefer
if(foo)
{
   //...
}

if(bar)
{
   //...
}

I have run into some people who prefer the first option above with no space between each block. The reason I dislike this so much is that depending on the method of “if” syntax you use, you second if block could look identical to your else blocks. As your code gets large and complex, it is important to make it as easy to discern different control paths that might be executed, and in this case, white space is really your friend.

Another concern is the ternary operator. This operator is basically a simple “if/else” block which fits on one line.

double number;
if(foo)
    number = 3.1415;
else
    number = 2.71828183;

// As opposed to
double number = foo ? 3.1415 : 2.71828183;

Ternary operators are great for doing assignments as in the one line above, but be careful with trying to do too much in one line. My general rule is the line is getting really long, or I’m doing multiple clauses in my condition I tend to shift away from ternary operator.

Conclusion

The problem with all of this is that my mind changes depending on where I am in, what I’m working on and what I plan to be doing with my code. I’m learning towards using the condensed form of the “if” block in the future for the simple reason that I can fit more lines of code in less space (not to mention that some pointed out it was the K&R way, too). Bottom line, whatever method you choose, you should really stick to it as best you can for each project. If you open up a file in a project that was edited by someone else, you should probably follow their precedence.

Stupid std::vector Class

The Standard Template Library in C++ is nice to provide us with a bunch of different container classes so we don’t have to re-invent the wheel every time we write new code. One of the classes is called “Vector”, if you aren’t familiar with it, you might not get too much out of this post. But basically, it is a dynamically growing array. Meaning it has contiguous memory and can be indexed like a regular array. It’s a great class and I use it all over the place, but for the second time in one week I find it lacking.

I’m working on some code where I have two vectors of the same type. I want to concatenate one on the end of the other.

  std::vector firstVector;
  std::vector secondVector;

  // I want to do the following, but its not legal
  firstVector.append(secondVector);

This doesn’t work. There is no append method for std::vector. It turns out that the correct code for this is:

  std::vector firstVector;
  std::vector secondVector;

  firstVector.insert(firstVector.end(), secondVector.begin(), secondVector.end());

This frustrates me. Append seems like a logical function to include. I’m relatively new C++ developer, having been working in the language intensely for only about a year. My guess is I will reverse my opinion over time, but it just seems like an append() makes sense.

There is also the potential benefit, depending on the implementation of std::vector. Insert requires you to pass in three iterators. Because an append function would have access to the internals of each vector you wouldn’t necessarily need to do the look up of each iterator, which might save a few lines of code. These lines of code might be dwarfed by the amount of code you would need to check the parameter being passed to an append function, I’m not sure.

Regardless of whether or not it is more efficient, I still feel like append() makes sense, conceptually and I would like to see it in future versions of the STL.

(again, I reserve the right to change my opinion in the not too distant future)

Leap Year Spells Trouble for Zune Users

On December 31st, all 30GB Zune users woke up to their music players not working. In a rarity for Microsoft problems, the source for for the problem was found. There is a good explanation of the problem here.

There are two lessons to be learned from this: 1) be careful of your looping conditions. 2) Try and write your code in small snippets that are testable, and write tests! A simple iteration through the total amount of days including a leap year would have caught this bug.

Just FYI, I’m not saying I would have been good enough to catch this, but it is worth writing down so I try to remember for myself.

The Address of Monkey

Have you seen the following C code sample:

	char x = 1;
	char c = x["monkey"];

Do you know what it the value of c is? Don’t read on unless you want to know the answer and why. The value of c is ‘o’. Why? Well, I wrote some code to start playing around with this. The answer seemed simple, but here were some suggestions about why the answer is ‘o’:

  • 1 is the index into the string “monkey”
  • There is some magic with math of memory on the stack for the compiler used
  • Something else is happening

Okay, it seems relatively trivial now, but when I looked at it it wasn’t. Other people were putting up ideas so I tested them out. Here is my silly test code:

#include 

void initial_test()
{
	char x = 1;
	char c = x["monkey"];
	
	printf("What is c:%cn", c);
}

void different_index()
{
	char x = 2;
	char c = x["monkey"];
	
	printf("What is c:%cn", c);
}

void space_allocation()
{
	char x = 1;
	char v = 'd';
	char c = x["monkey"];
	
	printf("What is c:%cn", c);
}

int main(int argc, char** argv)
{
	initial_test();
	different_index();
	space_allocation();
	
	return 0;
}

/* Output:
What is c:o
What is c:n
What is c:o
*/

What is actually going on here is really just the associative property of addition. I was telling a friend that I would understand “monkey”[x], but not the other way around. This is the quote from my friend (who wishes to remain nameless):

I mean, technically it’s base_address + sizeof(datatype)*index. since sizeof(char) == 1, it’s just base_address+index. 1+addressof(“monkey”) or addressof(“monkey”) + 1.. they both work

In the end it was just a fun little exercise.

MFC’s Radio Button Hack

Disclaimer: I am a mac user, but a windows programmer.

MFC is Microsoft’s old Window framework. Basically it is an object oriented wrapper around the traditional Win32 programming environment presented by Microsoft to help develop windows. Win32 is many years old, and so is MFC. Microsoft’s new frameworks, .NET and WPF (Windows Presentation Framework) are supposedly better than MFC, but I have yet to play with them.

MFC has tools for many different types of controls, from buttons to dialogs, windows, and menus. MFC allows the user to create the button, override some basic functionality, provide message callbacks and otherwise manipulate the application. Buttons are particularly interesting because the base class for buttons actually provides a ton of functionality for many different types of buttons. From this one class, you can get push buttons, check boxes, radio buttons, owner draw buttons (the programmer handles the rendering of these buttons), etc.

A Group of Radio Buttons
A Group of Radio Buttons

I have several problems with this class design, but today I just want to talk about my gripe with Radio Buttons. The term radio button comes from the buttons on old car radios, where only one button could be pushed at any one time. Radio buttons on a computer form, are by definition grouped with other radio buttons so that only one in the group can be selected at any one time. Any time a user selects another button in the group, the previously selected button should become unselected.

Taking this even further, logically, you should only use a radio button in certain situations. You have several options, usually less than 10, and you want the user to select from one of them. You should be able to have a default option set, and this choice should somewhat make sense. This functionality is very similar to a drop down box. In a drop down, you have a bunch of options (please put them in some order), where the user should select only one item. The difference in use between radio and drop downs depends on your application, but in general, you can put more items into a drop down. Drop downs will take up less screen real estate, but not all the choices may be obvious to the user, and sometimes the user may select the first option that seems relevant rather than looking through the whole list. In a radio group, all the options are present at the start.

This brings me to my gripe. MFC radio buttons are just the same as any other CButton. The way you define that a radio button is a radio button is by passing a style flag that is either BS_RADIOBUTTON or BS_AUTORADIOBUTTON. The difference is that auto radio buttons will look to be part of a group. This group is defined by ORing the BS_AUTORADIOBUTTON style with WS_GROUP for the first element of a group. All subsequent radio buttons will be part of that group until you create another WS_GROUP.

This upsets me because radio buttons in a group are associated with the other buttons in that group. They shouldn’t just be loosely coupled like this. It puts a lot more responsibility on the programmer to understand how the grouping is done. If you look at the picture above, you will notice it is from my Mac. In Interface Builder, Apple does not provide you with individual radio buttons, it instead provides an object called a “Radio Group”. This group is a collection of radio buttons that handles all the magic I wish existed in MFC. To be fair, Apple’s implementation is pretty new, they have redefined the way to create code on the Mac no less than 8 years ago with release of OS X. Microsoft’s MFC is much older than that and they have new technologies out there which probably better handle this problem. My issue is simply that I am working with legacy code here, and am incredibly frustrated by the lack of UI thought that went into designing this library in the beginning.