Posted tagged ‘Object Oriented Programming’

Learning notes from a C++ n00b – Part 1

August 25, 2010

I am primarily a Java developer. My college decided in my sophomore  year to switch from C/C++ to Java for most of the classes. While it did give me a very good foundation in Java development, it created a bit of a gap in my education. While I’ve done work in C in the past, I haven’t had the opportunity to work on a serious project in C or C++. Since my goal is always to learn a language a year, starting now C++ will be that language. It should be exciting.

Get excited by vintage letterpress

I'm excited. Are you excited? You're probably not. You're probably thinking "Why don't you already know C++? What sort of developer are you?" Well to find out, you should keep reading!

This post is the beginning of a series describing my process of exploration and discovery into the wonderful world of C++ from the perspective of a Java programmer. I imagine that some people who know C++ and Java are getting out popcorn waiting for the inevitable meltdown with dealing with things like memory leaks, makefiles, platform differences, and probably a bunch of other common issues I know nothing about. While that may eventually be the case, I’m not there yet.

Immediately, one of the biggest departures between Java development and C++ development is the change in IDE. For Java development I’m a big fan of IntelliJ IDEA. Java has a lot of import statements that involve very long package names and an IDE like IDEA tends to take care of that for you. Refactoring, like changing method or class names, is easy since I don’t need to manually find all usages and change them. Autocomplete and click jumping to method or class definitions is also very handy. The integrated debugger is useful when needed, and I like that it can easily import maven pom files as projects. While I’m definitely a proponent of being able to program in your language without an IDE (you shouldn’t let your IDE program for you), it still can be a useful tool at times.

My new IDE for C++ is vim. Ok, I don’t know if I’d really call it an ‘IDE’ exactly, but it’s my editor. I like vim overall, and I’ve been an avid user of it for about 7 years, so I can maneuver my way around. After reading about ctags, I wrote a script to generate them so that I can use it to jump between functions and methods. I’m pretty sure I’m not using it correctly however, as I have a tags file in each directory and I think the editor doesn’t always pick up all of the tags files I want. I have no idea how to use a debugger, and dealing with import statements is still a pain. Overall though vim is very fast and never hiccups unlike IDEA, so that’s a plus.

Another large departure from Java development is going from maven to makefiles. In Java I can create a maven pom.xml file to list all of my dependencies and plugins. Maven supplies a natural file structure that I can use to arrange my files into packages and place external resources in a place where the classpath will pick it up. There are tools to automatically create stub maven projects that I can just jump into and start coding. I can have any tests in my test directory automatically run just by calling mvn test. I can compile my project using mvn compile, and I can package it all up into a nice jar or war file by using mvn package. These are all default things that come with maven. It takes care of running the javac command to compile my code. It also sets up a testing environment for running tests. A very handy tool.

So makefiles. Makefiles sort of remind me of ant. I never really got into ant because it’s fairly verbose. It requires you to be more explicit in telling the system what to do and how to do it. Really though, makefiles are a bit less useful than ant, as they seem to be more like elaborate shell scripts that use the make utility to run. I still have to put in all of the g++ commands, along with lines of what libraries and other sources to give to the linker. Dependencies have to be accounted for manually. Tasks like clean or test have to be defined along with instructions for what those things actually do. There is no standard setup with clean interfaces for running tests or setting up your file structure. The main positive aspect that makefiles have over maven pom files is that a single makefile can generate several different deliverables (pom files only create a single jar).

I know that there are tools such as autoconf and automake that is supposed to make makefiles more portable to deal with library issues, but they’re not very easy to use. The GNU tool chain has a fairly extensive manual, but it feels like one needs to read the entire thing before even getting started. I haven’t had the time, so the GNU tool chain hasn’t entered my arsenal yet. I’m still not sure how to deal with the library distribution issue, but I’m sure that will come with time.

This is the book I'm currently learning C++ from. It doesn't get into the surrounding tool chain like make or the compiler much, but it's still useful for the language itself.

I’ve only been really looking deeply into C++ for a week or two now, and there are a lot of questions that pop into my mind. I have certain philosophies dealing with programming that I’ve gained over the years. A lot of those practices have been fueled by ideas from the Pragmatic Programmers. Others I have developed on my own. I’m still uncertain as to how to incorporate some of these ideas in my C++ development.

The first and most important of these is unit testing. Java has some very standard unit testing frameworks with JUnit and TestNG. Boost has a library for unit testing C++, and so does Google Test, but I have yet to delve into either of these deeply. Also I’m not sure if there’s a standard way of running tests like you can find with Java. Making sure that each test is in its own section in a makefile doesn’t seem very appealing. Hopefully I’ll find a nice way to easily unit test code (including using mocks), I’m just not there yet.

Also, how do you profile C++ code? I’ve used a tool called yourkit for Java which works very well. I know that there must be profilers for C++, but I don’t know what they are or how to use them. Similarly, debugging is an area that is still very grey. I know that there’s gdb, but I haven’t found a good tutorial on how to use it or how to integrate it into vim or some other editor to set breakpoints and see variable values.

And honestly, while I understand the basic concepts of pointers, I’m still unsure as to when to use them and how to fully utilize their functionality. In Java everything is done by reference (except primitives) and there’s a garbage collector when items go out of scope. When passing any object to a method, it can be modified by that method. I still need to learn a bit more about how scope effects both objects created on the heap and other objects in C++.

Overall there has been a lot of learning in the short time that I’ve been playing around with C++. While I’ve used Objective-C in the past for some iPhone programming, I haven’t really seriously taken on any projects in C++. The learning experience has been great, and quite a bit of fun. While most people would probably argue that makefiles are really annoying to set up, I’ve been enjoying the learning process of figuring out how to use them and creating working builds. My tests have all been small at this point, but they’re sure to grow in size. That said, I know I still have a lot to learn. I shall be delving deeper into the Boost libraries and doing multi-threaded programming with some asynchronous socket connections. I’ll be sure to update again after having gained a bit more experience.

Reusable Javascript: Write your own libraries

December 11, 2009

JavaScript is such an interesting language in that it is both extremely popular and hated at the same time. It is the most used programming language in the world, thanks to its inherent involvement in web programming. It is the sauce behind AJAX, and creates the dynamic aspect of dynamic web pages. It’s easy to pick up and write, requiring no compiler and running on any system that has a web browser. Unfortunately this has generated a stigma of it not being a ‘real’ programming language. Often even professional programmers will treat JavaScript in a more backhanded manner than they would code written in Java, C, Perl, Python, Ruby, or one of the many other compiled and scripting languages.

JavaScript, or ECMAScript as it is technically known as, is often written in a very procedural fashion. If you’re lucky you may see it being used as a functional language, when a developer decides to write functions at all. Rarely will you see it generated in a true object-oriented fashion. This is unfortunate because JavaScript has support for great object-oriented programming. Objects can be created through prototypes of other objects, allowing you to create “classes” through merely building a base object from scratch and then cloning it via prototypes.

A lot of JavaScript is created as one-off functions or scripts for a single purpose. Many developers are rebuilding their same wheel multiple times in the same application or even web page. While there are great libraries that showcase how useable pluggable JavaScript can be (take a look at the fully open sourced YUI library some time), very few developers abstract their business logic in a way that is reusable.

I think the problem mostly stems from the ingrained thought of the coupling between JavaScript and the web browser. People tend to write JavaScript for a specific web page, rather than to perform specific functions. A reapplication of the MVC pattern can be quite helpful here to separate concerns and promote reusability. I think this shows greatest when dealing with AJAX/Web Services.

Many applications are using AJAX to create more interactive, faster, and user friendly applications (we’ll ignore the back button concern for now). Web designers love AJAX because it creates a great feel for the users due to instant feedback and the lack of page loading. Web programmers dislike AJAX because it makes writing programs more difficult and can cause a lot more work. However, by separating some of the JavaScript code into distinct units you can reuse common functions across many pages.

Here’s an example:

WIDGET = {} // we use this as a namespace
WIDGET.removeRowFromTable = function() {
   var selectedItem = WIDGET.getSelectedItem();

   if (selectedItem != null) {
      var callback = WIDGET.getCallback(WIDGET.callbackDelegate);
      var postData = "itemId=" + selectedItem;

      YAHOO.util.Connect.asyncRequest('POST', 'removeRowFromTable.do', callback, postData);
};

/**
 * Override this method to change what to do on response (view stuff for response)
 * o - JSON object of response data
 */
WIDGET.callbackDelegate = function(o) {
   // Update view by removing row, maybe supplying text box to the user of what happened
   window.alert("The WIDGET.callbackDelegate method should be overridden per view.");
};

WIDGET.getCallback = function(successFunction) {
   return {
      timeout: function(o) { //default timeout function },
      success: successFunction,
      failure: function(o) {
         // default failure function. You could also change getCallback to pass this in if you want
         // to customize your failure.
      }
   };
};

This file can be part of your base “AJAX action” javascript which provides the actual actions to perform your AJAX commands. You can then use another javascript file to declare custom versions of WIDGET.callbackDelegate which will overridden the already declared version, just make sure that your new file is placed in your HTML file after the first one. By declaring default visual response to be alerts you will know what methods you should override on each new page.

Douglas Crockford, a fellow Yahoo and a member of the ECMAScript standards group has done a series of webcasts that describe some additional best practices of JavaScript that many developers may not practice. He also wrote a book that’s valuable to check out.