Why version control is a life saver…

It was late, and I’d done a long day up to that point. And I was mucking about with some inconsequential code. In fact, I was trying to delete the directory, as I’d finished what I was doing with it.

So I executed that fateful command: rm –rf parserdemo/ *

Now I’m sure almost all my regular readers will know straight away where I went wrong. I didn’t immediately. I was tired, and aching to get home, but after two minutes I thought, “that directory wasn’t that big!!” so I control-c’d it and did an ls.

It wasn’t a pretty sight. Almost every project I’d worked on had gone from my dev directory. Even more worrying was the work I was working on that morning had gone. Now I usually commit my code at the end of the day, (when I remember) so I cd’d in to the the project’s directory, looked ok, maybe I cancelled it in time, but no! I did a git status and got a nasty error message.

Fortunately for me, I actually committed the work earlier that day as I’d finished the ticket I was working on. So fortunately I could blat the directory, re-clone the project and check out against the appropriate branch and sure enough there was the code I’d lovingly written that morning.

The moral of this lesson?

Well first of all, be VERY CAREFUL using rm –rf, because it will just chomp through anything and everything if you’re not careful.

Secondly, if you don’t use version control, then do so.  It’s there for a VERY GOOD REASON.  And these days you can have your code hosted for free on github or bitbucket or any number of free source code repository sites.

Thirdly, commit your changes often. Because you never know when you need to roll back to something you did by mistake. With git this is very easy, I don’t have experience of other version control systems. I do recall using one tool that you had to check out individual files, then check them back in again against a central repository, you didn’t have the code on your hard disk the way you do with git. But I digress.

The fact of the matter is, I was tired and a wee bit irritable by that point of the day, and I hadn’t realised what I’d done until I looked at the command more carefully. But it’s the kind of mistake you’ll only make once.  Hopefully…

Advertisements

Overloading functions

I was chatting with a friend of mine the other night, and I must confess, I was in a bit of bother about whether to blog this or not.  For a while now I’ve been aware that I take a lot of the language features of C++ for granted.  I know how to use an awful lot, but I don’t really get in to the guts of it. So while I know a lot of surface stuff, I don’t think the likes of Herb Sutter and Scott Meyers have anything to worry about just yet.

But as I was chatting with Craig, I was worried that what I was going to blog on would be career limiting, after all I’ve been coding in C++ for three years now, so surely I should know more right?  Well, as ever Craig had some very sage advice, so here goes.

I came across an interesting issue a few years back in a legacy system I was working on and at the time, I just ignored it as one of those things.  I’d been coding in C++ for a few months, and the developer in question told me, “don’t worry, I’ll fix it.”  And off he went, and I went on and did something else.

Now hands up who can tell me what mistake I made there?  That’s right, I should have asked the developer if I could pair program with him as he explained what the problem was and how to fix it if it ever happened again.

So the problem was there was a pair of overloaded functions, where one took a char* and the other took a string.  And this was causing some unexpected behaviour in the code.

So this struck me again as I was walking home from work one night, and I realised I never did find out what happens in that case.  So I decided to find out.  Albeit three years later.

So, let’s suppose we have the following code:

void printNum(int num) 
{
    cout << "Print num taking an int" << endl;
}

void printNum(double num)
{
    cout << "Print num taking a double" << endl;
}

 

And we call printNum and pass it a number like say 100.  How does the compiler know which version to call?  After all it could be either an int or a double.  Well, when I ran this code and passing it 100, it printed: “Print num taking an int.”  But why?

Well when faced with this, the compiler goes through an internal sequence to work out which one to call.

  1. It gets all the functions in the current scope that has the same name as the function we’re trying to call.  It ignores the ones that don’t have the same number of arguments.
  2. If there are no matches found, the compiler will return an error.
  3. If more than one is found, it selects the best match.
  4. If there’s no clear winner, then an ambiguous function call error is thrown by the compiler.

This looks quite simple, but how does the compiler then select the best match?  The compiler works on a ratings system for the way the types are passed in the call, and the competing lists match up in decreasing order of goodness.  The list is as follows.

  1. An exact match.
  2. A promotion, so for example if you have a function that takes an int, and you pass it a char, then the char is promoted to an int.
  3. A standard type conversion. So a conversion between a double and a float for example.
  4. A constructor or user defined conversions.

So in this instance, as we’ve passed the printNum an int, we’ll get the int version back, the same way if we passed it a double like say 46.5 we’ll get the double version back. 

But what if we have something like this?

void doSomething(char* something)
{
    cout << "Something with char*" << endl;
}

void doSomething(string something)
{
    cout << "Something with string" << endl;
}

And we call it thus: doSomething(“this is a test”);

Then what version does it call?  Well, for a start, the compiler gives me a warning when I compile this.  The warning is:

compilerError

So any bets on which one’s called when we run it?

runResult

It’s the char* one.  But why?  I’m not entirely sure yet, but from what I’ve read,  there is a default conversion rule to convert String literals to char *.  I am still looking in to this one, if I’m wrong then please please feel free to comment so I know.

So if we wanted the string version, then we’d need to cast our little test string to a string. 

Well hope all that helps, feel free to comment.

Happy coding.

An interview with Scott Meyers

Unless you’re very new to C++ programming, or have been living in a cave, then you will have heard of Scott Meyers. He is the author of the best selling book Effective C++, and his latest book Effective Modern C++ has just hit the bookshelves. Scott has been a C++ consultant and trainer for at least twenty-five years. And he trained me on the new stuff in C++ in September, and so I got to carry out this interview face to face.

How did you get in to computer programming? Was it a sudden interest? Or was it a slow process?

I started programming in grade school, and they had a time sharing system, and there was a math teacher who recruited me and a couple of other people. And she thought that we might enjoy programming, which started out by playing games. This was on a teletype system with a piece of paper in it, and it was a 110 baud teletype thing. You could play still some remarkably good games on that system.

After we played some games, we thought it would be fun to learn how to program. Which was probably the math teacher’s idea, to learn how to program. And we started to do that after school, as did my friend. And one thing led to another, and before you know it you’re spending way too much time in a former cloakroom closet with a teletype until they make you to go home at six o’clock at night.

It was probably a small room as well? Probably about the size of a large wardrobe?

It was a former “cloak” room. So it was like a walk in closet that had a teletype, which made a lot of noise. It was a mechanical device, so they stapled eggshells as noise dampeners all the way around. So it was this narrow room, with two young men, and a machine that made a lot of noise. It must have smelled horrendous!

What was the first program you ever wrote? And in what language was it written in? Also is it possible to provide a code sample of that language?

I don’t remember what the first program I ever wrote was. The earliest program off hand I can remember writing was a couple of years after that, but it was a horse racing program. Which had all the sophistication you would expect from somebody who was fourteen years old.

It basically involved as I recall, several horses, that had to go a certain distance and each iteration you chose a random number that would determine how much further they went; That’s about as sophisticated as it got. But it was kind of cool, because it’s on a teletype system. You can’t show things in real time, so what I’d do was have it type out x’s–like a histogram. But it’s a 110 baud teletype, so you’d see the all the x’s, and then you had to wait before it printed out the next set of results. So there was a certain degree of suspense in trying to figure out which horse was going to win. Nothing fancy, I’m sorry.

What about a modern language? Such as C or C++?

In C, because I learned from Kernighan and Richie, I wrote Hello World. In C++ I also wrote Hello World. Because there’s a lot of merit in making sure you have all the pieces together to write computer programs.

What would you say is the best piece of advice you’ve ever been given as a programmer?

I don’t know what the best piece of advice I’ve been given is, but I’m going to turn the question around a little bit. In my youth, there came a point where I thought I knew everything. And I was working as a software developer at the time. And I made a comment about blah blah blah being impossible because of blah! And another guy looked at me and went, “you know…” and laid it out for me, that it was not impossible, and how it was not impossible and it turned out I didn’t know everything. And that was an important learning experience for me, to recognise that there’s a lot of stuff I don’t understand.

And what I’ve since learned over the years is that there’s a reason for everything. And if you look at something and it makes no sense or it seems crazy or it seems stupid, there’s a reason for it. And whoever came up with whatever you’re looking at, or whatever group came up with what you’re looking at, they had a reason for doing it. And it was probably a reasonable reason.

I’ve found that to be extremely helpful over the years, just to say “why were these things done?” Someone had the goal of achieving something good. So if you’re looking at something that’s overly complicated or doesn’t look correct, then it’s important to find out why it’s done the way it is.

You are very well known for the Effective series, how did that come about? Did anything make you decide “there needs to be one of these”?

I was working as a trainer at the time, and I was training C programmers using five day hands on courses to learn C++. This was in the early 1990’s. So C++ was a simpler language back then, there were no exceptions, no templates, so it was as simpler thing. But when you teach C programmers, C++ programmers forget how much how much has to be learned. For the poor C programmers, they don’t know what a class is, they don’t know what a virtual function is, they don’t know what inheritance is, they don’t know what overloading is, they don’t know what constructors are, what destructors are, they don’t know what references are and how they’re different from pointers. The list goes on and on.

And so I would teach these poor C programmers over the course of five days how to use C++, and by Friday afternoon, their heads were swimming. They were thinking “I’m never going to be able remember all this.” And five days is not a lot of time. So on Friday afternoon, I’d write on the whiteboard, and tell them “It’s not that hard, let’s list the stuff you really need to remember.” So for example, if you have a base class, you need a virtual destructor, or if you have a class with pointers then you need a copy constructor and an assignment operator, or you should never redefine a default parameter value, these sorts of things.

And I found that this made them feel better. So that’s how the list of items began. I taught somewhere, and I don’t recall where, and the group said “you should write a book.” And I said I’m not going to write a book. Then another place said, “you should write a book,” and at that time I was working on my PhD, and I thought “well, I could work on my PhD, which is hard, or I could write a book, which can’t be as hard as working on a PhD.” So I decided to write the book instead. It was a spontaneous decision, and the book was well received, and everything was derived from that.

If you were to go back in time and meet yourself at 14 years old, when you were in the teletype room, what would you tell yourself?

You don’t know everything. The world is more complicated than you think it is. If I learned that lesson a lot sooner, that would have been useful

If you started your career as a programmer now, what would you focus on? Would it still be C++? And which field would you be interested in working in?

I think that for me personally, so much is a matter of happenstance. So the first language I learned was BASIC. I learned BASIC because the teacher said “Why don’t you learn BASIC?” And for that matter, the reason I learned C++, was because I in graduate school, I was required to TA [be a teaching assistant for] a course on software engineering, and the professor of that course decided “we’re going to use C++, so you must learn C++”. I didn’t choose either one of those things, they just sort of happened to me.

So I’m going to turn your question around a little bit, and say if it was my goal to introduce new people to programming, then what would I do? And what I would do is something mobile. I think that mobile devices are really interesting to people, and you can do all sorts of cool stuff. And I would do something using some technology which would allow people to get a lot done really quickly, with really fast turnaround. Because I think that’s what really hooks people: I can get this stuff to work. So the Hello World for me would probably be a way to very quickly write a little application that would send a message using some technology from one mobile phone to another using giant libraries that the programmers would have no idea about how they worked..

For a lot of new developers, it’s important that they see something happening, so when I started on Visual Basic for example, you’d draw a button, write some code behind it, click on it, and something would happen, so the fact they can see what they’ve written actually does something is quite important.

I think the immediate feedback combined with high likelihood for success is what draws people in. At some point you have to get in to the nitty gritty stuff. But I wouldn’t start with C++. For one thing it’s not fun, it has no graphics, it has no networking. A lot of stuff is missing.

What would you describe as the biggest “ah ha” moment or surprise you’ve come across when you’re chasing down a bug?

The one that comes to mind is when I found out that the cause of the problem I was running in to was an instruction in my program that was comparing two floating point numbers for equality. And it hadn’t occurred to me that because two things are mathematically equivalent, that does not mean you’ll get the same result on the computer. So I spent a lot of time tracking that down, and I’ve never forgotten that.

Have you got any tips for any new programmers that are chasing down bugs at the moment.

I would say that like most things, the way you get better at it is by doing more of it. But you have to do more of it, but learn at the same time. So seek out other people who are better at it than you are, and try to continue to get new sources of information. If you’re tracking down a bug, and it’s difficult, get someone to help you. Ask other people what their ideas are, and that will help you develop an intuition of what to look for.

Do you have any regrets as a programmer? For example wishing you’d followed a certain technology more closely or something like that?

You know, I really don’t. I’d like to know more about some areas, but at the same time, I’m happy where I am. As a specific example, in the mid 1990’s when Java became very popular, a lot of people in the C++ community went “this is a cool thing!” and they moved across to Java, and I decided not to move to Java. Primarily because I thought “I’ve already learned one programming language, and the last thing I need to do is to prove that I can learn another programming language.” Which allowed me to completely and utterly miss the boat on Java. But as a result, I’ve stayed constant to C++, and I’ve learned a lot from it, so I don’t really have regrets as far as that goes.

Do you code in other languages? Such as Python or other scripting languages?

C++ is my language. It’s the only thing I do. If I were an actual programmer, I’d have to do a lot more. There are some other languages I can do a little bit, but C++ is really what I do.

From what I’ve read of your website, a lot of your work today is training and consulting, so I was wondering how do you make your code samples relevant to what the programmer may face in their everyday work?

What I try to do is to have enough contact with real programmers on a regular enough basis that I get feedback from them as to whether what I’m advocating or what I’m saying makes sense. And because I’m not a practicing programmer right now, and because I work by myself and I’m not surrounded by a bunch of other people in a company, I try really hard to stay in touch with real programmers developing real code.

My experience is if you give people advice that’s not practical, they will tell you right away. If you give them advice that’s too simple, they’ll tell you right away. For example we just spent the last two days talking about this sort of stuff, and people ask questions, people make comments, they have funny looks on their faces. And you get feedback as to whether what you’re telling them seems relevant to their job. And that’s my primary goal.

I feel I should apologise, that I typed in some of your code during the course, and it didn’t do what you said it would do.

I love that! It reminds me I was in China at one time, and I was teaching a course and it happened to be on the internals of how certain things work. And I was talking about how virtual function tables are implemented under multiple inheritance.

So I do my presentation and I go “that’s how virtual functions are implemented under multiple inheritance.” And this one guy looks up from his computer and goes “no it’s not!”

So we looked at his compiler, and did some disassembly, and it turned out that the information I had was completely accurate for one compiler, and he was using a different compiler, which did things in a different way. So this is an example of how people keep me honest. So he learned that there were other ways to do it than that one compiler he was using, and I learned that there are other ways to do it other than the compiler I was using.

So I love it when people point out stuff that I wasn’t aware of.

Are you currently a mentor?  And if so, what do you do with your mentees?

No

Did you ever have a mentor yourself?

Certainly not by that name, I certainly learned from other people, but I never had a formal relationship with someone who was supposed to help me improve what I do. And in retrospect I learned mostly from peers with more or less the amount of experience as I did, but I wasn’t a practicing programmer for all that long. I was a programmer for three years.

As a trainer, I suppose you read quite a lot? What would you say is the best book you’ve read?

Nothing comes to mind. What I will say is that I don’t read many books. I read a giant amount of blog posts, I read Stack Overflow when I get a chance, or when I’m research, I read a lot of e-mail that I exchange with other people, I read a lot of papers, I read a lot of online shorter stuff. I don’t read a lot of books. For example, we talked earlier (in the course) about Anthony Williams’ book, C++ Concurrency in Action, I didn’t read that whole book. But for example, the chapter he has in there on the memory model is just killer! So I was very pleased with that. I don’t tend to sit down and read entire books, because in the C++ area, it’s uncommon to find a book that is filled with stuff I don’t already know.

So how do you go about learning new techniques then? For example, when the move paradigm came in C++ 11/14, how did you go about learning that? I suppose I’m really asking what’s your learning style? Do you read then dive in or do you dive in or is it a mix?

It depends on what I’m trying to learn. Let’s take something like C++ 11/14, something that’s technically defined by the standard. What I normally do in those conditions is start with blog entries, where people have written overview blog entries or something like that, so I can try to build a mental model. And if I have a questions, I get the questions answered in various ways, sometimes I turn to Stack Overflow, sometimes I turn to people that wrote standardisation proposals. I read a lot of standardisation proposals. I play around with compilers too, but I have to say that when it comes to standardisation-related stuff, compilers can be helpful, but if you want to know what the standard says, then you need to know what the standard says. So playing around with code is less useful, especially with technology that is newer, because compilers may not have implemented it yet.

On the other hand, for example we had that question in the course about what happens if you have an infinite loop in a constexpr function. To me, that’s a question compilers need to answer.

So we have an update to Effective C++, will you be doing an update to More Effective C++ and Effective STL? Or are all the updates incorporated in the new book?

To be clear, I didn’t update Effective C++. The new book is called Effective Modern C++. It has completely new information, so it’s not an update of Effective C++.

Sorry

No that’s fine; actually I’m eager to get the word out about that. It’s a completely new book. It would have been a lot less work had it been a new edition.

As to the question of whether I’ll be updating any of my other books, that remains to be seen. I will say that it’s unlikely that More Effective C++ will get updated. That book is now almost 20 years old. A lot of the information is still useful, but I’m not sure at this point it’s really worth updating.

Where do you think the next big shift in programming is going to come in? I’ve noticed you’ve done some stuff with D. Do you see that as the next big thing? And for the uninitiated, what is D?

I’m not doing anything with D, actually. There are people in the D community that would like me to do something with D, people who I respect. But that’s not my plan. I was asked to give a keynote talk at the most recent D conference, that’s what I did. I went and gave a talk to the D people, and I basically encouraged them to avoid creating a language as complicated as C++, that was basically my message for them.

As for the next big thing, I’m really bad at predicting that sort of thing, so I’m not going to even try.

Finally, what advice would you offer to kids or adults that are looking to start a career as a programmer?

The people who I know who are good at programming, who are happy with their lives–that kind of stuff, they do it because they love it. And so I would say that if you are looking at it as though to say “this would make a nice career” but your heart isn’t in it, maybe you should be looking elsewhere. On the other hand, if you play around with it, if it seems fun, if you like the idea of controlling machines or if you want to accomplish something, then you should just do it. Because it can be fantastically rewarding. It’s a “Follow your heart” kind of thing. Because if you don’t like it, it’s hard!

Thank you very much for your time.

You’re very welcome.

An interview with Seb Rose

Seb Rose is well known to most ACCU members. For those who do not know who he is, Seb is an independent software developer, trainer and consultant based in the UK. He specialises in working with teams adopting and refining their agile practices, with a particular focus on automated testing.

Since he first worked as a programmer in 1980 (writing applications in compiled BASIC on an Apple II) he has dabbled in many technologies for many companies, including Linn Smart, Amazon and IBM. He has just finished writing “The Cucumber-JVM Book” for the Pragmatic Programmer’s. His website can be found at http://www.claysnow.co.uk

How did you get in to computer programming? Was it a sudden interest? Or was it a slow process?

The maths department at my school had a PDP11 and a room with 8 terminals. I spent an afternoon watching someone write BASIC and wrote my first program the next day. The head of department then gave me a few photocopied sheets from Kernighan & Ritchie’s “The C Programming Language” and I started learning more about what was happening under the surface.

A few years later I got my first holiday job working at a service station on the A3, getting paid the princely sum of 60p an hour. It sounds grim, but I earned enough to buy a record deck (anyone remember the PL-512?), which meant I needed even more money to buy albums. A neighbour put me in touch with his accountant who was in partnership with a guy in Teddington who was writing accountancy software in his attic. I went round for a chat and showed off my BASIC skills and landed the job. He apologetically told me that all he could afford to pay was £3 an hour – a 500% pay rise! I was ecstatic and I’ve been programming (on and off) ever since.

What was the first program you ever wrote? And in what language was it written in? Also is it possible to provide a code sample of that language?

BASIC. Nothing very exciting, just asking for input and printing out a response. I then took a huge leap and tried to write a text based Dungeons and Dragons game in C. It never worked, but I spent many a happy hour tinkering about with source code on huge print-outs. I returned to BASIC (compiled for the Apple II) for my holiday job and spent a lot of time doing screen layouts using 80 x 24 grids. There were some lovely hacks for positioning the cursor at a specific location on the screen which we used to access via GOSUBs whenever we needed to present output.

What would you say is the best piece of advice you’ve ever been given as a programmer?

Tricky question. Maybe the advice from Steve Freeman and Nat Pryce to “Listen to your tests.” It’s all too easy to blame a technique (or tool) that you’re trying to learn, when actually it’s your failings in other areas that are the root cause of the problem. When I find it hard to write a unit test, I remember their advice and look at the code I’m trying to test with a critical eye.

The old favourite “don’t optimise (yet)” is regularly useful. As developers we often think about performance prematurely. The “shameless green” stage of TDD encourages us to get the test working without thinking too hard about the design. It’s the “refactor” step where we improve the design of the code, but even here performance should generally be a subsiduary concern to readability. There will always be situations where you need every ounce of performance you can get, but they are few and far between in most domains, and you should only pursue optimisation once you actually have the data to show what actually needs optimised.

If you were to go back in time and meet yourself when you were starting out as a programmer, what would you tell yourself?

I’d probably tell myself: “Good choice.” It’s hard to think of a career that has so many varied opportunities or that would have allowed me to work in so many different areas. I’ve been a freelancer for most of my career, and the occasional breaks between contracts have been invaluable for learning new skills and trying different things.

I ran an organic smallholding for 12 years, at the same time as working as a contractor. I tried to have the contracts end in the spring, so that I could spend the sunny, Scottish days doing more physical work outdoors. For 3 years around 2003 I ran the organic business full-time and didn’t do any commercial programming. I actually found that I spent more time at a desk during this period than I did when I was contracting – maintaining the website and order system, generating delivery reports, dealing with customers etc.

It was a relief to be able to return to programming when, after our best year trading, the accounts showed I’d only made £12,000 from delivering organic produce.

Do you currently have a mentor? And if so, what would you say is the best piece of advice you’ve been given by them?

I haven’t got a specific mentor, but I treat most of the people I meet as potential mentors in one way or another. Recently Jon Jagger told me he spends 1/3 of his time earning money, 1/3 working on OSS and 1/3 fishing. I’ll not be taking up fishing, but this seems like a mix to aspire to.

How do you keep your skills up to date? Do you get a chance to do some personal development at work?

I spend a lot of time reading blogs and books, as well as going to conferences. In fact, you could say that my job IS keeping up to date, at least with a small segment of the industry.

Twitter is a great source of information – not the throw away one liners, but the links to blogs that I wouldn’t normally notice.

And I organise the local BCS branch events, which forces me to talk to a lot of people and actively seek out new and interesting topics and speakers.

What would you describe as the biggest “ah ha” moment or surprise you’ve come across when you’re chasing down a bug?

Working with Weblogic in the early days of EJB 1.0 we were getting inexplicable , intermittent failures. Days of investigation later, having boiled the sample code down to something really small, it became clear that there actually was a problem in the application server. We submitted a bug report and, in due course, received a patch. Months later the problem reappeared – the supplier had rolled out an upgrade WITHOUT the patch.

I remember the first time I heard you talk was at the ACCU Conference where you were talking about Test Driven Development. There has been a lot of talk of late of TDD is dead (among the more extreme things I’ve seen) (http://www.infoq.com/news/2014/06/tdd-dead-controversy) I’m guessing you wouldn’t agree with that assessment? Or is it a case of the way TDD is done, and how it’s implemented that’s the issue?

I’m still talking about TDD. My current opinion is that TDD is a technique that is generally useful, but that context is, as always, an important consideration. The arguments stem from consultants making general statements that address segments of the development community without making it clear which segments they apply to. I say more about this in my session “So long, and thanks for all the tests” which is online at http://vimeo.com/105861375

The short answer is that TDD is not dead, but neither is it a silver bullet. It’s a useful technique to have in your toolkit, but like so many techniques it’s easier to describe than do. That’s why I think all developers should learn and practice TDD, at least until they know it well enough to make a considered judgement about whether it’s useful for them in their current role.

How scary was it to go from full time developer to free-lance developer? And how long did it take for you to feel confident to go for it?

I graduated in 1987 and did my first contract in 1992. In the intervening period I did 2 full-time jobs, one for 8 months and one for 5 months. So, I think it’s fair to say that I’ve always been freelance. I guess that confidence has not been too much of a problem for me.

That’s not to say that I haven’t worried about where my next paycheck will come from. I have, and at times where continuity is more important to me, such as when my children were young, I have returned to permanent employment. Strangely, though, I’m generally less stressed working as an independent than an employee – and I don’t think I’m alone in this.

Do you have any regrets as a programmer? For example wishing you’d followed a certain technology more closely or something like that?

I wish I’d read more books and bought fewer.

Where do you think the next big shift in programming is going to come in?

I have no idea. In the nineties, when first introduced to HTML and the internet, I said the equivalent of “it’ll never catch on.” Niels Bohr is credited with saying “Prediction is hard (especially about the future)” and I’m worse than most at making predictions.

Finally, what advice would you offer to kids or adults that are looking to start a career as a programmer?

I think I’d give the same advice for any domain, not just programming. Have a go. Do something that interests you and keep trying. Qualifications may help, but enthusiasm and aptitude are by far the most important ingredients.

Effective learning…with Scott Meyers

A few weeks ago, I had the pleasure of being in London. I have always liked London, but was here for an even better reason this time, as I was attending a training course by Scott Meyers on Effective Modern C++ which was based on his forthcoming book!

I attended the course with little to no hands-on experience with the new features of C++11/14. Don’t get me wrong, I’d had a play with a few of the features, but not used any of them in anger. So for the last two days, I was sat in a class room doing some excellent learning.

First things first, Scott is an excellent trainer. He was clear, articulate and had a great way of engaging everyone in, what were at times, very complex topics. He was accessible as well, and ensured that nobody felt like they’d asked a dumb question.

As for the course, some of the material I’d come across before. Scott did a Modern Effective C++ sampler talk at the 2013 Going Native conference, the video can be found here

He also covered topics such as auto and decltype. I’ll confess, before the course, I wasn’t sure what the point of auto and decltype were. It looked like auto was a device to save typing, at least to me initially. So I had a bit of a play with auto during a break just to see it in action. So we’re clear here, this is code I’ve had a play with, so any errors in here are mine, not Scott’s. So with that in mind, let’s consider the following example:

#include <vector>
#include <string>

using namespace std;

// Let's say that this is populated...
vector<string> records; 

vector<string>::iterator rec_it;

for(rec_it = records.begin(); rec_it != records.end(); ++rec_it)
{
	// do something....
}

We want to loop over the vector that’s full of strings which we want to print out what’s in there. But to loop through the vector, there’s quite a bit of setup to do. We have to set up the iterator, and then use it in the for-loop that follows. But how much easier would it be to do this:

// Let's say that this is populated...
vector<string> records; 

for(auto rec_it = records.begin(); rec_it != records.end(); ++rec_it)
{
	// do something....
}

This loops a lot cleaner, and a whole lot simpler. Auto basically deduces what rec_it needs to be. I won’t go in to the detail of how it does this, as I’m still learning that myself at the moment.

An example that Scott did give of the use of auto, was the use of auto within a ranged for loop. Ranged for loops have been in C# and Java for a while now, but it’s good to see that they’ve made their way in to C++. The syntax in C++ is very similar to that in Java and C# too. For example:

for(const auto p&: records)
{
    …
}

The compiler will figure out what sort of object is held within the data structure records. A ranged for loop would is useful when you want do something quickly over a data structure such as printing a collection of strings from a vector.

Don’t get me wrong. I’m not going to use auto everywhere I can for the sake of using auto. As I think that would make certain aspects of the code unreadable. For me, if I want to declare an int, then I’ll explicitly declare an int. I don’t want it to be deduced.

Scott mentioned that in C++ 14, auto can also be used as a return type. I’ll confess this makes me nervous. As it can lead to multiple returns within the body of a function, and in my personal opinion makes the code a bit harder to read and understand. However I will have a play and report back on how I find it..

I also got to learn about constexpr, and I must confess that I was cynical. I was seeing the examples that Scott had, but I wondered “Why not use a ‘static const int’ rather than constexpr.” Scott explained that constexpr objects must have values that are calculated during compilation. So for example, if we were to use std::array (from the new standard) we’d have to use a constexpr to set the size of the array, otherwise the code won’t compile.

One of the fun, but somewhat scary, things that I did do however was to type in one of Scott’s code samples into my editor and hit compile. The sample in the course was thus:

class Widget
{
public:
	template<typename T>
	void setName(T&& newName) // URef or Forwarding Reference
	{ name = std::move(newName); }  // compiles but it's wrong!
	...

};

Widget w;
std::string wName(getWidgetName());
w.setname(wName);  // moves wName into w
                   // wname == &quot;&quot; (probably)

And here’s my code:

#include <string>
#include <iostream>

class Widget
{
public:
    template<typename T>
    void setName(T&& newName)
    { name = std::move(newName);}

    std::string getWidgetName(){ return "fred"; }
private:
    std::string name;
};

int main()
{
    Widget w;
    std::string wName(w.getWidgetName());
    std::cout << "Name is now set to " << wName << std::endl;
    // This is due to the string = operator, which converts double to a char
    // which is why we can do this...
    w.setName(34.3);
    std::cout << "After move, wName is now set to " << wName << std::endl;
    return 0;
}

I found that it didn’t behave in the way we expected. I showed this to Scott, it kicked off a search for what was going on. In the end it was discovered that a string has an assignment operator that takes a char, so anything implicitly convertible to a char (including double) can be assigned to a std::string, same can’t be said for the string constructor. This means that when I passed in another object, that I’d created, it would fail as the object couldn’t be converted to a char.

We also covered topics including lambdas, which was cool. I’ve not used them in any code as yet, but where would we use it? One possible use would be to do a sort of custom object, by using the lambda function as the comparator.

We also covered the concurrency API, which I was quite nervous about. I’ve still not done much with threads as of yet. But I have the course notes, so I plan to have a play. The results of which will end up on this blog soon.

If I had to change one thing, it would have been good to see the code examples being compiled and finding out what happens when you try to build it, or execute it. But I can fully understand that it’s only a two day course, and there’s only so much you can do.

If you get the chance to do this course then do it, it’s well worth it. Failing that, get on the Going Native 2013 video trail. Scott’s talk from there is worth listening to as well.

Bits and pieces…

It’s been a while since I’ve posted, and for that I am sorry.  Life suddenly got busy, but here’s a post that’s been bubbling away the last few weeks.

One of the things I’ve always been blessed with (in some sense at least) is the knowledge of my weaknesses.  I’d argue that it’s a very important skill in a Software Engineer to know where their weaknesses lie.  I’m not talking about putting oneself down and making out that you know nothing.  Not at all, I’m talking about having sober judgement about your skills as a programmer.

So recently, I had cause to come across an area I’d never dabbled with as a programmer.  I’ve been doing some experimentation work on something that required me to have knowledge of bit-shifting and masking.

For those who were brought up in C, this is probably second nature to you, and you can safely switch off now.  I won’t be offended.  For the rest of you who are still with me, the inability to understand bit-shifting and masking is not something you should be ashamed of.  It wasn’t something I was taught at University (I did an Internet Computing degree).  It’s something I’ve had to learn fairly recently.

But before I get to some code (yes I know! actual code!!) I think it’s a good idea to go over bit-wise operators VERY quickly.

So you have a bitwise AND operator (&), a bitwise OR operator (|), a bitwise Complement opearator (~) which is also known as an inverse operator.  The AND and OR truth tables are shown below.

 image

The complement operator (~) essentially flips the bits, or inverses them, so you if you had:

000000001 in Binary, and put it through the (~) operator you’d get returned 11111110.

So now we know what the truth table looks like, let’s discuss bit-mapping.  This is generally used to check whether a certain bit is set or not.  It’s commonly used with uint8_t in C++ from what I’ve seen, however it can be used with other unsigned integer types as well.

So let’s say we want to simulate an 8 switch DIP switch.  I’m sure you’ve seen them underneath various electrical appliances.  In case you haven’t, here’s an example below.

As you can see, it has eight switches on it, which allows you to configure your hardware in a certain way.  It’s often seen in remote door bells etc.

So lets say you want to check that bit 1 is set, that is the left switch.  To do that you need to use a bitmask.  So a quick word is needed on binary numbers.  They start at 1, and go up by 2 each time, and you generally write the larger number on the left, and the lowest number on the right.  So for example, for an 8 bit number, the binary values are thus:

128, 64, 32, 16, 8, 4, 2,1 which all add up to 255.

So if we wanted to check that the 1st bit was set, we’d need to check that the bit furthest to the left was set, which in this case is the 128 value.  Bit masks tend to be written in Hex.  So using my Windows Calculator in programmer mode (no shame in that either by the way!!) The hex of 128 is 80.  But we also need to decide what sort of mask we’re going to use.

So if we want to check that the first bit is set in our switch, what sort of bitmask do we need?  An OR based one?  Or an AND based one?  In this instance we need to use an AND based mask.  So the mask in binary would look something like this:

10000000 so for example:

10000001 – Original value
10000000 – Our mask:
===================
10000000 – Result

The mask ONLY checks the bit or bits we’re interested in.  It ignores everything else.

So how do we represent that in code?

Well, like this:

bool checkBit(uint8_t value)
{
	bool returnValue = false;

	if((val & 0x80) == 0x80)
	{
		returnValue = true;
	}

	return returnValue;
}

So what’s going on here?  Well it’s a very simplistic program that simply tests that a bit is set using the bitmask.  So the if statement places a mask over the value, and compares it against the expected result.

So that’s a simple example.  Let’s say we want to print out a number in binary.  There isn’t an easy way to do this in C++, so we have to roll our own.  This brings bit shifting in to the mix.

Bit shifting is basically shifting a bit one way or the other.  There are two bitwise shift operators in C++, >> for a right bitwise shift, and a << for a left bitwise shift.  So to print a binary number from a normal number, we need to shift a bit, and using a mask, check if it’s a zero or a one.  Then based on that, add it to an output stream.  It sounds complicated, but it’s not that hard once you get the hang of it.

In code it looks a little something like this:

#include <iostream>
#include <sstream> // for stringstream

using namespace std;

// For now we print 8 bit numbers.
string printBinary(uint8_t val)
{
	stringstream outputStream;
	//uint8_t lastBit = 0x80;
	for(int i = 1 ; i <= 8; ++i)
	{
		// Check what we have in the first bit.
        if((val & 0x80) == 0x80)
		{
			outputStream << 1;
		}
		else
		{
			outputStream << 0;
		}
		// Now shift everything 1 to the left.
		val = val << 1;
	}
	return outputStream.str();
}

int main(int argc, char* argv[])
{
	if(argc != 2)
	{
		cout << "Usage: ./binPrint <number between 1 and 255>" << endl;
		return (1);
	}
	// We don't put an endl here as we want it on the same line.
	cout << "Printing out binary value of " << argv[1] << " : ";

	// Convert the char to a uint8_t
	uint8_t value = atoi(argv[1]);
	cout << printBinary(value) << endl;
	return (0);
}

So what does this code do?

Well, it loops over an 8 bit number checking what the first bit is.  Based on the result of the mask, it appends it to the end of a stringstream so that a formatted binary string is outputted.  So for example if I want to print out the number 8 in binary, it would come out as: 00001000.

Another thing to note is that we grab the value BEFORE we do the bit-wise shift.  And we’ve got to be careful when shifting to the left, becuase if we’re checking the first bit like we’re doing in the code here, then we could shift things off the end, so we’ve got to make sure we nab the bit we want and THEN dot he bitshift.

Please do feel free to play and have a go.  It’s honestly the best way to learn.  I’m in the process of re-writing my binary printer now to cope with any bit number from uint8_t to uint64_t which is quite a challenge.  I may post that up here once I’m done.

Bjarne stroustrup – An Interview

In 2013, I heard Pete Goodliffe talk about becoming a better programmer, and he lined up a panel of experts about how to become a better programmer. Having heard the talk, I endeavoured to put as much of it as I could in to practice. During one of the intervals, I had a chance meeting with Bjarne Stroustrup who was gracious enough to agree to be interviewed for my blog. I was also encouraged to publish it in the ACCU magazine (details at the bottom of the blog post), so here we are.

If you’re a C++ programmer, then Bjarne Stroustrup won’t need any introduction at all. However, if you are new to C++, then Dr Stroustrup is the designer and the original implementer of C++. He is currently a Managing Director in the technology division of Morgan Stanley in New York, a Visiting Professor in Computer Science at Colombia University, and a Distinguished Research Professor in Computer Science at Texas A&M University. His best known published work is The C++ Programming Language which is currently in its 4th edition.

How did you get started in computer programming? Was it a sudden interest in computing? Or was it a gradual process?

During my last year of high-school, I had to decide whether to go to university and if so what to study. I decided to study mathematics because I was pretty good at that in high school, but I wanted a practical form of mathematics, some kind of applied math. That way, I would be able to make a living doing math after graduation, rather than becoming a teacher. So, I enrolled in “Mathematics with Computer Science” in my home-town university (Aarhus University) because I mistakenly thought that “Computer Science” was a form of applied math. It was good that I was wrong about that because I wasn’t as good at math as I thought at the time (though being a poor mathematician is better than not being a mathematician) and I absolutely loved computers science – and especially programming – when I eventually was introduced to it in my second year at university.

What was the first program you ever wrote? And what language did you write it in?

In my first Computer Science course, we learned several languages and wrote tiny programs in those. I don’t remember those exercises, though. The primary language taught was Algol60. The first program I do remember was a small graphics program written in Algo60. It was probably my first program that was not a set exercise. It connected points on a super-ellipse to draw pretty pictures. The “user interface” allowed me to specify the parameters for the super-ellipse, the number of points, and the number of lines. From a programming point of view, it combined math with graphics..

What would you say is the best piece of advice you’ve ever been given as a programmer?

Just one piece of advice? “Test early and often.” But maybe that’s just my own variant of the old Chicago advice about elections.

Try not to be too clever: Bugs hide in complex code. Be clear and explicit about what your are trying to build, and how. By “explicit,” I mean “write it down in good clear English that others can read.” Articulating a design is important and helps you when it comes to construct test cases and write assertions. Always think about how a piece of code should be used: good interfaces are the essence of good code. You can hide all kinds of clever and dirty code behind a good interface if you really need such code.

If you were to start your career again now, what would you do differently? Or if you could go back in time and meet yourself when you were starting out as a programmer, what would you tell yourself to focus on?

I think I would have taken a year off to travel the world and improve my interpersonal skills. Had I known that I’d spend most of my career writing in English and giving talks in English, I might have paid more attention in my foreign language classes. On the other hand, I have found topics with no apparent practical use (such as literature, history, and even philosophy) at least as useful as many specific technical skills. It is good not to have too narrow a focus. Bertrand Russell: “The time you enjoy wasting is not wasted time.”

What was the biggest “ah ha” moment or surprise you’ve experienced when chasing down a bug?

I don’t think this question applies. I dislike debugging and my usual reaction to finally finding a bug is “How could I be daft enough to write that!” Alternatively, “What was he/she thinking? Often, as simple invariant would have caught the problem early or a slight restraint on “cleverness” would have avoided the problem altogether. What I enjoy is to design and to express my designs in code. Sometimes, the realization of a design can be amazingly beautiful. “Getting it” with the STL (Alex Stepanov’s handiwork) was an “Aha!” moment. Discovering how to express the STL better with concepts comes close.

A lot is said about elegant code these days. What would is the most elegant code you’ve seen? And how do you define what elegant code is?

I’d say that one of the best answers I’ve seen for what makes elegant code, is something I’ve read from ACCU’s own Roger Orr:

}

Just that closing brace. Here is where all the “magic” happens in C++. Variables get destroyed, memory gets released, lock get freed, files get closed, names from outside the closed scope regain their meaning, etc. This is where C++ most significantly differs from other languages. It is interesting to see how destructors – an invention (together with constructors) from the first week or so of C++ – have increased in importance over the years. So many of the modern and most effective C++ techniques critically depend on them

With the advent of C++ 14 upon us, where do you see C++ going in the future? Is there anything you’d like to see, or something you’d wish you’d done differently?

For the future, I’d like to see better concurrency support, concepts (requirements for template arguments), and increased simplicity. I’d like to explore the idea of simplicity within C++ with features such as range-for loops, auto, and libraries that make simple things simple. “Within C++, there is a much smaller and cleaner language struggling to get out” (and no, that language is not C, D, Java, C#, or whatever). I’d like to explore what such a “much smaller and cleaner language” might look like in general and how it could be embedded into C++.

The essence of C++ is that it provides a direct map to hardware and offers mechanisms for very general zero-overhead abstraction. A future C++ should be better at both. This precludes simple imitation of many modern ideas and trends. We can learn a lot from other languages (and always have done so), but direct import of language features is non-trivial.

The “time machine question” is easier to answer because it has no effect on reality. We can’t change the past and even if we could, I’m pretty sure I’m no smarter than 1980s-vintage Bjarne and he had a much better feel for what was possible at the time. Even the best time machine would not allow me to compile C++14 on a 1MB, 1MHz, 1985 computer. If I could have dropped the “concepts Lite” design on Bjarne’s desk in 1987, we might have avoided a lot of problems. At that time, I was looking at ways of constraining template arguments, so I would have recognized the importance of the ideas. Furthermore, the complexity and compile-time overheads are minimal so I could have implemented “concepts lite” well using 1980s technology. Of course, working from first principles, I would not have chosen the C declarator syntax or two-way conversions between fundamental types, but to fix those, you would need to take the time machine a few years further back for a chat with Dennis.

With technology moving so fast these days, where do you think the next big shift in computer programming is going to be?

Hard to say; there are so many different kinds of programming. I’m not even sure what the last big shift was. Dynamic languages? Object-Oriented Programming? Functional Programming? XML? Virtualization? C? Generic Programming? I’m pretty sure I could point to areas where each of those answers would be quite reasonable – as well as areas where each would be ludicrous. The field of software development is just too huge and diverse for simple generalizations.

In the parts of the C++ world that I know best, my guess is that the improved support for concurrency in C++17 (various higher-level models of concurrency beyond the basic threads-and-locks level) will cause major changes and that concepts (staring with “concepts lite”) will complete generic programming’s move into the mainstream. That combination, coming on top to the improvements provided in C++11, should completely change the way C++ is used.

I say “should” rather than “will” because I fear that many will hold back out of fear of novelty, for lack of intellectual flexibility, or because of constraints from old code bases. People are more likely to see the risks and complications of a change than to appreciate the risks and costs incurred by using outdated tools and techniques. Maybe, I’m being a bit less optimistic than I should be: people who have used C++11 tend to complain bitterly when they have to go back to C++98. Significant progress has been made and we can now write simpler and better code than we used to. Many people know that and they are not going to accept “the old ways” forever.

Finally, do you have any advice for any kids or adults who are looking to start out as a programmer?

Don’t just program. Know what problems you want to solve using programming. Don’t rush into programming. Work on your communication skills. And don’t forget to have fun – you are much better at things you enjoy doing than things you consider tedious. Learn to see the beauty in elegant and efficient code!

A Tour of C++, for people who wants to quickly know what C++11 is, and his textbook for beginners: Programming: Principles and Practice using C++, which now uses C++11 and some bits of C++14 is available now from your usual book reseller.

This interview was published in the July edition of the ACCU’s CVu magazine.  If you haven’t considered joining the ACCU (Association of C and C++ Users) then I fully encourage you to do so.  It’s a community of developers who code in a wide range of technologies, and hosts a fantastic annual conference every year.  For more information go to www.accu.org

Dealing with rejection….

It was with some surprise that I saw this on Twitter last night…

irisTweet If you’ve checked my blog roll, then you’ll know that I’m a reader of Iris’ blog.  And this post surprised me.  Now, I don’t know Iris at all, but this post sounded like it was flat.  And indeed, if you read the blog post in question.  (Just click on the picture).  And it was difficult reading that post, especially when you can see the passion Iris has in her previous posts, and her enjoyment of programming is clear to all. 

However, it reminded me of when I was trying to become a programmer way back in 2006.  Until that point, I’d be pursuing a call to the priesthood in the Church in Wales, but that door closed, and looking back now, I’m very thankful for that.  But at the time, I was working as a pastoral assistant for a small Welsh speaking church, which involved preaching once a month, visiting the elderly folk of the parish, (who knew exactly how to make a young lad blush…) and general admin stuff. 

But that job came to an end. The Church were generous in the parting gift they gave to me, and with it, I bought a desktop computer, monitor, keyboard and mouse all from e-bay and started to learn to code again.  It had been a while, (I graduated from University in 2004) so I had a lot to learn, and Java had moved a long a bit since I last coded in it.

So I started writing lots of little bits and bobs to try and get my coding skills back up to scratch.  At one point I wrote a Point of Sale system in Java using a database backend, I wrote a small project manager program which I didn’t quite get round to finishing.  And generally coded all morning, while in the afternoon, I’d fire off my CV to companies looking for Junior Developers.

I’d been doing this for about several months.  I did everything I could to get myself a programming job, heck, I even went to London at an hour’s notice for a job interview. 

But in that seven months, all I heard constantly was “No, you don’t have enough experience!”  Now let’s be clear here.  I was applying for a JUNIOR Developer position.  And yet these companies were saying no.  I saw one job advertising for a Junior Developer with 5 years experience.  I’m sorry but what you’re doing is trying to get a decent developer at a Junior Developer rate, and frankly I’m not going to go for that!

It all came to a head when I was encouraged to phone one company, oddly enough in the town I now reside in (hahaha), and the chap at the end of the line asked “What experience have you got in ASP.NET?”  I was honest and told him that I didn’t have all that much experience, but had a keen mind and was willing to learn.  He responded with “well, we need an experienced developer really, sorry”  At which point, I must confess I lost it.  I responded by yelling at the man “How the hell can I get experience if nobody’s even give me a chance to gain any?” at which point I slammed the phone down.

Probably wasn’t my finest hour.  However, it got me thinking, “Okay, how do I get experience if nobody gives me a chance?”   So how can developers starting out, get the experience they need?  As not all degree courses give the option of a year in industry.

Kick off your own open source project.

One of the things you can do is kick off your own open source project.  This is even easier these days, and there’s a massive variety of things you can do.  You can write a mobile app, a web app framework.  The only limit here is your imagination.

Contribute to an Open Source Project

Another option is to join a project that’s already running.  This has the benefit of enabling you to work with other developers all over the world.  It’s also an excellent way to find a mentor too, someone who will take the time to help you improve as a programmer.  The best thing with this is that you can get as involved as you like, and you can also choose an area to specialise in.  Want to write unit tests?  Great! Go for it, want to get involved on the documentation?  Cool, projects are screaming out for folks to do the documentation.

Have realistic expectations.

This is a tough one.  We all want to be the rock star developer, but we’ve got to start at rock bottom.  For example, it took me three years to get a job as a programmer.  I started by stacking shelves at a local supermarket.  From there I worked for a small local software company doing technical support, and from there to my current job as a fully fledged software engineer.  So sometimes it’s going to take a while to get there, and once you’re there, you’ve not made it.  Oh no!!  It’s then the work really starts!  There’ll be stuff to pick up, books to read, certain procedures to follow etc. 

Don’t get disheartened by rejection, allow the folks around you to help you.

This is a really hard one. I got knock back after knock back after knock back, and it’s so easy to think you’re not good enough.  I kept all my rejection letters for a bit, but I’ve since shredded all of them.  But I am also blessed that I have parents who love me enough to kick me up the ass when I needed it, and I did quite a few times while I was applying for programming jobs.  On the flip side, they were also brilliant at encouraging me when I’d had a rough one.  My mum heard me yell at that guy on the phone and she commented drily “you won’t get far yelling at them…”  Of course she was right, but she also understood why I was so angry as well.  When I mentioned it to my dad, he just laughed, he was surprised I’d do such a thing to a potential employer. 

The people around you want to you help, but sometimes they don’t know how.  Just remember that they’re supporting you and they care about you.  I couldn’t see it at the time when I was going through all this, but I am grateful beyond words that they supported me through this.  And not just my parents, I have some friends from my time in Aberystwyth (you know who you are), who gave me project suggestions and stuff I could look at writing, or provide me with guidance on setting up Wireless networking on early versions of Ubuntu. 

And the support didn’t stop once I landed a programming job either.  Over the last five years I’ve been working as a professional developer, I’ve had the privilege of being mentored by some brilliant developers, they know who they are.  They’ve provided me with clarity of vision when I’ve been too blinkered or too stupid to see what’s going on. 

This is not an exhaustive list, but it’s the stuff I learned during one of the hardest times of my life.  If I can encourage you in any way, is that it was worth it.  There is a light at the end of the tunnel, and once you get there, you’ll look back and see how much you’ve grown through it all. 

I would also love to hear about your experiences in going through something like this.  Please feel free to comment.

From brain to keyboard…

“Yeah I can do that in no time!”  Those were the words that should have rang alarm bells in my head.  My mentor at work had issued me a challenge from a well known competitive coding site, and in my head it didn’t take any time at all for me to do the arithmetic of what I had to do.

The tricky bit came to when I had to convert what I intuitively knew in my head, to C++ code.  And it’s tricky.  So the problem is basically, you’re given a number (N), and you have to find the least amount of steps to turn N in to a Fibonacci number.

Now for those who’ve never seen a Fibonacci number before, it’s basically a sequence of numbers where the last number is the sum of the two previous numbers, so this is a Fibonacci sequence:

0,1,1,2,3,5,8,13,21,34,55,89….. and so on.  You get the idea.  So if I gave you say…19 you’d know instantly that the nearest Fibonacci number to it is 21.  But try writing that in code.

This is something that I’m not as quick as everyone else at doing, I tend to over-think and over-complicate things.  But that’s is why I do this deliberate practice, so I can become better at it.  So my first stab at the program was a bit of a mess I must confess, this is what my code looked like initially….

int find(int f)
{
    int fib = 0;
    int currentNum = 1;
    int previousNum = 0;
    int loop = 0;
    static int currentGap = 0; 

    while(loop != f)
    {
        fib = currentNum + previousNum; 
        previousNum = currentNum;
        currentNum = fib;
        cout << "Fib: " << fib << endl;
        currentGap = f - fib; 

        int tempGap = f - currentGap;
        // cout << "Current Gap: " << currentGap << endl;
        // cout << "Temp Gap: " << tempGap << endl; 

        if(tempGap <= currentGap)
        {
            cout << "Gap is " << currentGap << endl;
        }
        ++loop;
    }   
}

 

As you can see from this, it was quite a messy piece of code.  It certainly wasn’t well thought out.  I’d just sat at my keyboard and hacked away at it, which isn’t what I should be doing as an engineer right?

So I stopped writing code for about an hour and started writing the steps on paper.  As can be seen.

notes

This helped take my mind off the syntax, and on the concept on how I’m going to do this.  So the final code looked a lot tidier and more compact, so the result is as follows:

int find(int f)
{
    int returnVal = 0;
    int first = 1;
    int second = 1;
    while(second < N)
    {
        second = first + second;
        first = second - first; 

        // cout << "Second: " << second << " : first " << first << endl;
    } 

    int val1 = N - first;
    int val2 = second - N; 

    if(val1 < val2)
    {
        returnVal = val1;
    }
    else
    {
        returnVal = val2;
    }
    return returnVal;
}

This is something I really need to work on to become a better programmer, and it’s only by practising I am going to get better at doing this.

Concepts not syntax!!

If I could go back in time, and give myself any piece of advice, it would be this. “Don’t worry about the syntax of the language, concentrate on getting the concepts right!”

For example, here is a for-loop in C++:

for(int i = 0; i &lt; max_limit; i++)
{
    // do something with i
}

Now here’s the Java equivalent,

for(int i = 0; i &lt; max_limit; i++)
{
    // do something with i
}

Or how about Visual Basic?

For number As Double = 2 To 0 Step -0.25
    Debug.Write(number.ToString & " ")
Next

Sadly I only learned this a few years back (I’ve only been coding professionally for five years, so am still playing catch-up) But when I learned this lesson, I found it was far easier to pick up stuff in other languages relatively quickly.

For example, I’m currently writing stuff in C# at home, which is VERY similar to Java (I know, old news…) So it means I don’t have so much of a curve to learn, as I already know how to declare an array, or a vector or a for loop or while loop.

And that’s what I’d encourage each new coder to do. While it’s tempting to dive in to your language and learn everything there is to know about it, and trust me, that IS a good thing. If you’re starting out, I’d suggest that you make sure you got the concepts solidly in your mind.

In five years, I have coded in: (in no particular order) C++, Java, Bash, Python, C, C#, Visual Basic (yup), and Perl. And I can tell you that learning the syntax is a doddle once you know the core concepts.

Now don’t misunderstand me at this point. Of course you should learn the syntax and the semantics of your chosen language, however the point I am making is don’t get so focused on the syntax, that the concepts pass you by! That’s the mistake I made!

Please note I’m specifically focussing on languages such as C, C++, Java and their ilk here. Of course there are markup languages like HTML, CSS, XML that have their own syntax, but they are beyond the scope of this blog post.

As ever, would welcome thoughts or comments!

Happy coding