Singletons with controlled destruction

I’m not going to debate about why one should or should not use singletons. I’m only going to provide an improvement for the singleton. One of the problems with singletons is that they use a static member. The problem with static members is that they can be destroyed in any order on application exit. If you have more than one singleton, and have dependencies between them, you want to control destruction of the singleton on application exit.

The differences between this and the Super Simple Singleton I previously posted about a couple of years ago are:

  1. The instance is a member of the class, not a function.
  2. There is a destroy() function

The destroy function allows for controlled destruction of the singleton, which is a million times better. When your application exists, and you have more than one singleton and they are dependent upon each other, who knows which one will get destroyed first. This gives you a lot more control over it.

Where to put doxygen comments

I’m awesome
This is an “ah ha!” moment for me. For some reason, I felt that it was better to place all of my function method comments inside the cpp files instead of the header file. I felt it was cleaner, and it looked nicer because the header file was nice and compact and formatted neatly. You could glance at the class and immediately determine what public function methods you were supposed to use.

I am no longer awesome like I thought
Well, until I realized that, after you compile the library and distribute it with the header file, there are zero comments for the end user on how to use the API, unless you’ve built the doxygen comments already and also distributed it. This makes it a hassle for the developer who now has to go onto a website or open a .chm file for documentation. It’s rather clumsy.

There is a nasty trade off for this though. If you put all the comments in the header file, the user may now have to scroll around just to find the public API. It may not be nice and neat anymore and it feels cluttered to me. Maybe you can use visual studio’s “#region” stuff to help though.

Put doxy comments inside the header file for the end user, not the cpp file, where no one will be looking or possibly even have access to. Alternatively, put the comments in the cpp file, but make sure you’ve built the doxygen documentation for the API. I say the header is better because the developer won’t have to jump out to a website to get documentation. Another rason is because you can mouse over a function in visual studio and it gives you a synopsis of it with the tool tip. Yay.

Early-outs for n00bs

Sometimes I see people code something up like the following:

This situation has numerous problems.

  1. It’s difficult to read.
  2. The cohesion is terrible. If you trace a debug log to one of the debug statements, it is no where near the failure. So you have to sloppily figure out which if failed.
  3. It can get complicated.

At first it may seem that you can just pull all of the if statements together like this:

It’s pretty clear what the problem is. We simplified the statement, but we lost all our debugging information.
If one of the ANDed statements fails, we still have to check which one in the “else” clause.

Enter “Early-out”. The concept of an early-out is simple. Just check for negative conditions instead of positive ones.

  1. It keeps the errors together with the failure check.
  2. It makes the code easier to read
  3. Its easy to tell if you forgot something
  4. Use this method to check input arguments passed to the function

It’s simply a matter of reorganizing the code.

So all we did was reorganize the code, got rid of the “elses,” and changed the boolean logic to != instead of == on all if statements. This is a good way to make sure you’re testing all of your parameters for valid input before you actually execute any code… They’re called early-outs because they attempt to exit out of the function as early as possible. This avoids any unnecessary processing (that’s the theory any ways.)

Testing at Microsoft

I was a contract employee at Microsoft, an SDET I. While I was there I learned quite a lot about testing, and I really believe it made me a much better programmer. Although my time there was short lived, I managed to retain some of my testing knowledge, and I hope to share that with you now. So I’ll quickly and briefly cover the basics of testing. I’m not talking about unit testing either. I’ll break down the types of tests you have into different categories. There may be more.

  • BVT (Base verification tests)
  • –Positive test cases
  • FVT (Functional verification tests)
  • –Positive Test Cases (Tester tests for expected failures )
  • –Negative Test Cases (We catch unexpected failures during testing (hopefully) )

BVT (Base Verification Tests)
These are the basic tests performed to show that the operation is basically working. Sometimes you just want to run the BVT tests because they’re faster and shorter. Example:

It is short and to the point. TEST is a simple macro that checks if the return value of the function is equal to the second parameter. It checks to see if 2*2/1 == 5. Nothing more. It is fast, but it doesn’t check everything. This test is also called a positive test case. A positive test case consists of passing in valid data, and expecting to get a valid result.

FVT (Functional Verification Tests)
The FVTs are a much more in depth testing stage. It consists of a much more thorough testing of the functions, in both quantity, and quality. FVTs consists of the BVT tests as well. So they may be duplicated, but this isn’t necessary. In some cases, the FVTs consists of modifications to the BVTs.
From the example above:

As you can see, we now have a lot more test cases and they’re broken up into positive and negative test cases. We may want then to be in separate functions too, but I didn’t do that here. Our positive test cases have a lot more cases and are simple modifications to the BVT.

The FVT also consists of our negative cases, where, if the function fails, (gives an invalid result the user can’t use) it needs to fail in an expected and deterministic way. Under no circumstances should it crash. When it crashes, this is an “unexpected failure,” and is usually caught very soon, since your tests will also crash. This is the most common unexpected failure. I can’t really think of any other right now.

Also, all of the negative test cases will fail in this scenario because nothing in the function is being thrown. And our tests are expecting it to throw the correct exceptions. When testing, it’s important to test common boundary values. In the example above, good things to test are 0, -1, 1, INF, -INF, NaNs, and other such things. When writing code, it’s important to check for the same boundary conditions immediately at the top of the function.

One final note before I leave. These are NOT unit tests. Unit tests sometimes overlap the BVTs, but they are written by the developer who wrote the code (in this case the Calc function). So they are not written by the tester (or SDET).

Const qualifier reminder

Just a reminder how const-ness works. If I remember correctly.

Math trickery for 1D & 2D arrays

Once upon a time, there was a language that didn’t have 2 dimensional arrays. This greatly upset the programmer. Fortunately, the programmer was swift in the art of arithmetic and overcame this obstacle easily.

Lets say for example, we only have access to a 1 dimensional array data structure and it has 50 elements in it.

Lets break this array up into 10 rows and 5 columns to make a grid. So how do we get access to a position say data[4][3]?
There are two things I’m going to teach you now:
1) Retrieve the column & row numbers from a linear index counter.
2) Retrieve the index from a row & column numbers.

Before I continue, i want you to notice that the row and column numbers are zero based. So they start at zero, not one.

Lets do #1 first:

Read the rest of this entry »

Things you can do to make your code better

I got most of this list from some other place on the internet, but I felt there could be more added to it.
I’ll continue to add to this list as I think of things or come across things.

  1. Test Driven Development Really Is Worth It
  2. Don’t Rely On Comments Too Much: Make Your Code Self-Explanatory
  3. Don’t Let Exceptions Disappear Into A Black Hole
  4. Don’t reinvent the wheel. Use libraries when possible because you know they work.
  5. Code like you will reuse the code for other projects.
  6. Learn what good design should look like an emulate it until you see why it is good design (and what you dislike about it).
  7. Too many newbies like to over-engineer just to pretend to be smart or having fun with resume-driven-development. In other words, implementing every pattern in the book or putting bayesian filters in every corner of the code should be avoided if they aren’t needed. Debugging, testing, maintenance will be all easier, not mentioning performance.
  8. Have your code reviewed often.
  9. Be wary of code smells (Class too big, method too big, method with too many arguments, Ask don’t Tell etc).
  10. Enforce standards by using checkstyle / PMD, cobertura / emma, findbugs, etc within maven build cycle to make sure code in repository is adhering to a certain quality standard.
  11. Make sure it meets the quality standard for the project.
  12. Just keep it simple. Functions should be short and sweet, and do just one thing. They should fit on one or two screenfuls of text (the ISO/ANSI screen size is 80×24, as we all know), and do one thing and do that well.
  13. Test, test, test.
  14. You will see how many times you will have to tradeoff between design and schedule. Forgive yourself but remember to refactor whenever possible.
  15. Use Standard Annotation Language (SAL) if you are using C or C++, to prevent bugs and make your code robust. It is found in the book “Writing Secure Code for Windows Vista.”
  16. Code with contracts (partially enforced with SAL).
  1. Avoid global mutable state, such as static variables and static singletons.
  1. Make your methods small and well named.
  1. Simple Design
  1. Adhere to SOLID Principles

Simple coding tips 01 – Naming functions

Simple tip: Naming functions


Note how each function name begins with a verb and usually, each function ends with a noun. Naming your functions this way helps you think more clearly about what you’re doing and helps other people understand your code more thoroughly.

A Few Code Snippets

Periodically I’ll stumble across a small but useful piece of code. I have a small list right now, but as I stumble across them, I’ll post them here. Note: I do not take credit for any of this code.

Pausing your application


Convert any data type to a std::string object

Test if a float is zero or near zero

EPSILON is a #define that is something small, like 0.002f
Note, I will repost, I just realized that serendipity can’t handle angle brackets…