Skip to content

Asserts are Awesome (and Exceptions certaintly don’t replace them)

September 5, 2012

Assert vs Exception

That actually is a quite common rant and it is usually won by exception. Even Jon Skeet thinks that assert could be replaced entirely by exception. Many people will read his opinion and just fallow it and that is unfortunate. I wish everyone would use assertions more. As I see them, they have completely different purpose from exceptions.

No Room for Assert?

First lets think of why people think assert can be replaced by exception. At first glance I need an assert to check if program is not in unexpected state.

For example, we expect that some argument will not be nullptr:

void myFunction(ImportantType* importantVariable)
   assert(importantVariable != nullptr);

or some function returns not nullptr

void myFunction()
   ImportantType* importantVariable = someImportantFunction();
   assert(importantVariable != nullptr);

or our result is valid

ImportantType* myFunction()
  return someResult;

But isn’t that risky? Using or returning value that we know is not correct? It might very well screw up other calculations and that will lead to many more problems. The best we can do here is stop execution before something worse happens and go to safety where we know what to do. This sounds like a job for exception. Isn’t it better to just throw rather than try to work with something we were not expecting?

After all doesn’t assertion mean “this shouldn’t have happened”? Seems like there is no room for assert…

Not a Chance! Asserts are Awesome!

OK, so where is assert better than exception? Well there are cases when I could not live without assert and exceptions just wouldn’t do the trick. And that is in private methods.

Lets take the simplest example possible. In public method if I can’t find a file, I should throw, but that shouldn’t always be the case with private methods, for example in some cases I could assume that file is empty. Where can I do it? Well, if everywhere where I use this private method, I wrap it in try catch, just to work like nothing has been done, I can very well do the same in the private method. Without exception swallowing information that something indeed went wrong.

Suppose you have some archives you want to load to your application. Some lines of it might be corrupt or even entire archive. So we need to take care of this, we don’t want to let some unpredictable data to enter our application. But we also don’t want application to crash just because it didn’t get some semi-important data. (Lets say we’re loading road network, if some of roads are corrupt it is better just to skip them, it’s not worth killing entire application or data load process, neither it is logical to add them if we know they will contain corrupt data) So, the code could look like this:

for (std::vector<std::string>::const_iterator it = files.begin(); it != files.end(); ++it)
      DataFile dataFile = OpenFile(*it);
      for (dataRow jt = dataFile.dataRowsBegin(); jt != dataFile.dataRowsEnd(); ++jt)
         catch(Exception ex)
            //something is wrong with data line... log something...
   catch(Exception ex)
      //something is wrong with the file... log something or do something else

Well that sure looks ugly… We can move inner loop to another function, but just having try catch blocks inside a loop doesn’t look so well.

Another problem with it is that we might never notice that something is wrong in the first place unless we read logs and I don’t know anyone that looks at them unless something wrong happened. So it looks like we finally have somewhere to use assert — we can place it inside catch blocks, this way user wont be interrupted but on debug mode we will see that something did not go as expected right away!

But why do we need exceptions in the first place? We can simply assert inside local functions and declare a contract, that for corrupt file, it will log and then return empty dataFile and for corrupt line it will log and  just return.

Bottom Line

Don”t overlook assertions. They can help you spot bugs in your software much easier than exceptions. For me answer whether use exception or assert looks like this:

  • In public methods exception wins. But I still place them to check arguments just that developer using my class (most likely it’s me) would be informed that he is doing something he is not supposed to.
  • In private methods assert wins. Not all the time of course, but there is nothing I hate more than swallowed exceptions. All they do is hide bugs, while assert pops them out directly to your face.

Cartography as an Art

September 3, 2012

Just a reblog this time.

Solo Developer: pros and cons

August 31, 2012

I am leaving my current position and decided to see what I’ve accomplished and learned for past two years. For all that time I’ve been a solo developer (well to be honest, I had an intern to help me out, but for quite short time anyway). Like everything in life, being a lonesome coder in this ruthless software world had both — pros and cons.

I think this was great and vital experience in my career. It allowed me to accomplish and learn a lot as I was responsible for absolutely everything. I wouldn’t change it for anything. Here is why:

  • There is no one to turn to when you are alone. Where does that leave you? You have to find solutions completely on your own. That goes from choosing best algorithm, container, tools and languages to something like  finding out what was with that DLL problem on client machine. Thus being solo developer will, without any doubt, make you superb at problem solving.
  • If you are willing to learn to be a better coder, you will. Use Stackoverflow, programmers.stackexchange, blogs and just try to use best solutions you find. Of course, no one is stopping you to do so with the team, but being alone you are your own boss and you’re totally free to experiment. I had no mentor, so what else could I do than to be my own mentor? It forced me to read books and that, combined with numerous resources on internet, is by far the best mentor you could ever have. Have an idea? Just browse for it!
  • When working with someone else, your responsibilities are shared. You could be responsible for routing algorithms, while others work with map engine, database, etc. I had to know absolutely everything and without taking too much. Reading code becomes as easy as reading a book.
  • I have learned what I needed with GIS from ground up. That might not sound very challenging, but before, I didn’t even had an slightest idea about any of that stuff. Hell, I didn’t even know it was called GIS! If I had been working with someone more experienced in this field, no doubt I wouldn’t have learned so much.
  • I have written first unit tests, re-coded vital parts of code to drop copy-pasted code using design patterns, started using RAII, significantly increased performance for routing algorithms and included boost libraries. It’s not like I wouldn’t be able to do all that when I’m not alone, but again, I was my own boss and that gave me a lot of freedom to see what works and what doesn’t.

So what are the cons of being a solo developer? Well, firstly I think it depends on your views and experience you already have. If I wouldn’t have worked with great developers in the past to teach me and most importantly inspire me, I would have failed miserably.

But here is a single most important drawback: motivation — you have no one to share ideas. When you are stuck with some problem you only have monologue in your head instead of sharing it with others. I mean you can share it with others in the company, but will they be that interested in your whining? They have their own problems. At first it is nothing… But working alone for a year or longer can make you really miserable.

But non the less, as I’ve said, it was a really great experience and I don’t think I would have gained it if I wasn’t working alone. And now it is time to join a team and see what I have really learned during those years!

The Magical World of Buzzwords

August 29, 2012

Recently I’ve been reading some job ads. This actually is quite funny experience. Sometimes it seems that those who created an ad tried to think of every buzzword they ever had in their head.

Agile agile agile…
Everyone and everything is now agile. “Agile and scrum knowledge”… I’ve just opened few ads and all of them had this line. I think you can see this in almost every job ad. Often it might even come as a requirement before your actual coding skills. And that is the reason why I hate Agile. I mean I don’t really hate it, I think is great to work closely with people that will use the software you’re creating. But agile doesn’t mean that a group of morons can build great software only if they meet up every morning to whine how hard is the problem they are working on and that it will take much longer, because they haven’t heard of regular expressions and have to do everything manually. Agile in the job ad makes me think that the attitude of a project manager is to do all this bureaucratic stuff before actual coding.

Design Patterns
Yep, they are important, but why even bother asking for Design Pattern knowledge if the code you’re going to work has no structure at all? To be honest that is what happened in my last workplace — during interview, at least 20% of it was about Design Patterns. However the code base I’ve been working with had no design at all, just tons of copy pasted code. So if the rest of the team had no idea of how polymorphism works, why ask for Design Patterns? It didn’t stop others from working here..

Tons of frameworks
I can only ask “why?”. Frameworks are not that hard to learn, and I don’t think that the rest of the team are experts of all the 20 frameworks you’ve put on the ad. Software world is changing so fast, I’d rather employ someone with ability to learn quickly rather than with knowledge of that specific python framework.

Jira, svn, git, etc.
Who even writes this stuff? Even if I haven’t used any of them, I could easily write them on my CV, because during interview I have never heard a question about one of these. When I see these on a job ad, I immediately think that the team just learned what source control is and now they want to boast about it. I mean, you don’t write the most obvious skills on the ad, do you? And even if I wouldn’t have used git or svn or anything else before, it’s not like it takes ages to learn it.

N years of experience with some language
OK, so this is not really a buzzoword. But who cares. I can be coding for 5 years with C#/java/whatever but if I haven’t read any book and only used what I’ve learned in the university, my knowledge would be useless.

Well you can easily shove this straight into your arse. Whenever I see this in the job ad, even if it is only mentioned as an advantage, I immediately close it.

Join The Professional Team
I’ve saved the best for last. You just have to love this one, especially if you’ll get lucky enough to join a team of real pros where half of them are incapable of writing a SQL query. That’s not even the worst part, be ready for someone to be unable read error messages and just whine when it occurs. Not to mention that there will be someone that will only be able to do work that has specific steps of what has to be done. You know, someone that should have been replaced by computer a long time ago. This mostly goes for testers that write millions of test cases and then executes them manually for a week.

Some fun in CRUD

August 13, 2012

I hate crud, but who doesn’t? Also, I no matter how much as I hate it, I still need to do it sometimes. But then again, who doesn’t?

So I had this task: on map event click, all its properties should be arranged in a circle around it. Sounds like a perfect CRUD task: user created an event and added some properties to it, it is now displayed on map. Now on click, I only have to collect all its properties and display them nicely.

But how do I display them in a perfect circle? Well here is some fun from high school, use SIN and COS functions to do it. Here is an example:

Event event = GetSelectedEvent();
EventProperty[] eventProperties = event.GetProperties();

int xDelta = 0;
int yDelta = 0;
int lambda = 0;

foreach (var eventProperty in eventProperties)
    xDelta = (int)(Math.Cos(lambda * Math.PI / 180) * 200);
    yDelta = (int)(Math.Sin(lambda * Math.PI / 180) * 200);
    lambda += 360 / eventProperties.Count;
    AddSymbol(LayerId, event.xCoord + xDelta, event.yCoord + yDelta, eventProperty.Type);

It is just a small piece of code, but for some reason I was very happy to write it. Even CRUD can be fun sometimes!

Review: Working Effectively with Legacy Code. Jack of all Trades

May 16, 2012

I haven’t fully finished this book, there are some chapters left, and for some time I am not planning finishing it. So before putting it on a shelf, I am going to give it a review (and explain why I stopped reading it).

One thing to say is that I am not putting it because it is a worthless or bad reading. Actually the content on the book is quite good. It gives a lot of really great advises. But also it has few flaws. So lets start with them.

As the review title says, the book seemed to be “jack of all trades”. On one chapter it will give you a design pattern. Another may show some C++ or Java language feature, yet another one will give some testing advice and etc. Maybe it is not that bad, but what I really wanted was some ideas on how to work effectively with legacy code. All other details are not that interesting to me and they distract from the problem. If I would want advises on design patterns, I would just pick a design pattern book.

Another thing is that the further I went with the reading, the more it seemed to repeat itself. The same advice will repeated over and over again. And that is the main reason I’ve decided to stop and read something else. The more I’ve read, the less I seemed to gain from it.

Despite the issues I’ve mentioned, I feel like I have learned a lot from what I have read. I work as a solo developer and the book felt like a programming buddy. Whenever I doubted my decisions or had mixed thoughts, it would clear things up. There is, after all, huge amounts of experience written in the chapters of this book.

Another great thing is how well it is organized. Even though I was reading from cover to cover, I was also using it as a reference. Whenever I’ve seen that it has a chapter close to what I am trying to solve, I would turn to it for advises and encouragement.

Overall, it is a great book, but it could have easily been 150 pages instead of 450. It is full of great examples and advises. Author has huge experience and was able to share it well — it is easy to read, but at the same time very informative. Highly recommended, even if you will not read it all.

P.s. It is not only good for developers working with legacy code. It might give you some advises how to manage your source code that it won’t become pain to work with.

Dear future me… you’re so welcome!

May 9, 2012

Recently there has been a discussion on code and performance audit in linkedin. It is hilarious! If you can read Lithuanian I encourage you to do so, there are tons of golden quotes. They compare software development with moving bricks and producing chairs. (To be clear — I don’t call CRUD software development. As well as doing same thing over and over again. For me, software development is nothing else but problem solving with the right tools. If you’re repeating yourself non stop, that might be a problem. Solving that would be software development. Copy pasting code however is not.)

One particular quote sounds like this:

//Dear future me, you cannot imagine how sorry I am

Well, it’s a comment somewhere in the legacy code.

What scares me that this is accepted as “funny but true”. No I don’t mean that you should code perfect from the first time. Your views on design might change with experience. You might learn something new about your language. You might solve it with one code line instead of one hundred. You might think that the code smell is so intense that it gives you headache. But as long as you have that particular smelly part of code covered with tests you will thank your past self no matter how much the code sucks. Trust me on that.

I work with legacy system and I see copy-paste code everywhere. I see bad design decisions and endless methods. Single files of 5000 code lines that don’t seem to differ too much. There are singletons almost in every step. Nothing is dependent on abstractions and code is incredibly highly coupled.
But I can say this: if I take some time to put a piece of code under tests, even if it might make it uglier, since that moment, I thank and thank myself non stop. Even if the future me is only one week away, I know that guy will be happy as fuck when he finds that part of code under tests. Sometimes the guy is not even future me, it is present me and he is happy to work with that ugly piece of code that he didn’t even write!

I learn constantly and of course time to time I will come across some code that would make me think “What was I thinking?!”. But as long as it is well tested I will not blame that poor stupid old me.