Archive

Posts Tagged ‘programming’

And In The Beginning…

September 30, 2014 5 comments

I’m on my second pass through Bjarne Stroustrup’s “The Design And Evolution Of C++“. In the book, which was published exactly 20 years ago in 1994, Bjarne discloses all of the “whys” and “hows” that drove the growth of C++ up to the time of the book’s publication.

DE Cover

 

In the beginning, before there was C++ there was the even-more-nerdly-named “C With Classes” (CWC). Bjarne’s motivation for creating CWC was, as many inventions are, rooted in frustration:

This was exactly the kind of problem that I had become determined never again to attack without the proper tools. – Bjarne Stroustrup

The problem Bjarne refers to in the above quote was: “the task of exploring if/how the UNIX kernel could be distributed over a network of LAN-connected computers“. The preceding “never again” problem was for achieving his Ph.D. thesis at Cambridge University: “to study alternatives for the organization of system software for distributed systems“. Notice how the word “distributed” appears in both problems – and this was way back in the 70’s when bell bottoms were in fashion and prior to the rise of multi-core processor technology.

How To Unix

Even though he didn’t say why he chose the tool for his Cambridge Ph.D. thesis project, Bjarne used Nygaard and Dahl’s Simula programming language to code up a program for “simulating software running on a distributed system“. If you already know the history of C++, you won’t be surprised at Bjarne’s feelings for Simula or why he imported some of its key features into CWC:

It was a pleasure to write that simulator. The features of Simula were almost ideal for the purpose, and I was particularly impressed by the way the concepts of the language helped me think about the problems in my application. The class concept allowed me to map my application concepts into the language constructs in a direct way that made my code more readable than I had seen in any other language. The way Simula classes can act as co-routines made the inherent concurrency of my application easy to express.

Class hierarchies were used to express variants of application-level concepts. The use of class hierarchies was not heavy, though; the use of classes to express concurrency was much more important in the organization of my simulator.

During writing and initial debugging, I acquired a great respect for the expressiveness of Simula’s type system and its compiler’s ability to catch type errors.

In the above book quotes, we see the “whys” for:

  • The appearance of the “Classes” word in “C With Classes“.
  • CWC’s’s support for an object oriented programming style
  • CWC’s static type system.

In contrast to Simula’s elegant expressiveness, its compile time and runtime performance were abysmal (garbage collection + runtime type checking + built-in concurrency = slooow). The runtime performance was so poor that Bjarne had to rewrite his simulator in low-level BPCL at the last second in order to get any meaningful results out of the program to stuff into his Ph.D. thesis.

Although there were several other pragmatic reasons for the appearance of the “C” in “C With Classes” (flexibility, ubiquity of available compilers, direct mapping of data to the hardware, simple linkage and runtime systems), performance ultimately drove the decision to use the well known and proven C language as ground zero for CWC – despite its funky syntactic quirks and unsafe features.

Curiously, support for concurrency was provided in CWC’s very first library in 1980. Concurrency appeared in the form of a tasking library and built-in support for two special functions recognized by the preprocessor: call() and return(). If defined by the programmer for a class, these functions would get implicitly invoked prior to entry and prior to exit of every class member function except for the constructor/destructor. They were required by the monitor class in the tasking library to acquire and release a lock for precluding data races.  Interestingly, the call() and return() functions were later removed because “nobody used them but me“. We’d have to wait until 2011 for concurrency to return to C++ in the form of new libraries.

On exiting this post, I’d like to show you this e-mail exchange with Bjarne regarding the possibility of a book sequel in the near future:

DE Sequel

Why not join an e-mail campaign to get Bjarne started on D&E II? So, go ahead. E-mail Bjarne like I did and plead with him to start penning the sequel. The 20 year trek from 1994 to 2014 has got to be filled with as many great “hows” and “whys” as D&E I.

Categories: C++ Tags: , , ,

Live Instructor, Or Live Code?

September 25, 2014 Leave a comment

I’m currently taking an in-house course on Java programming. The material is being presented in standard lecture fashion where the instructor sequentially walks through a series of static powerpoint slides and explains what the code snippets on each slide are doing.

In parallel to the in-house class, I’m also taking an online Java video course taught by Paul Deitel in the comfort of my home. The 36 hour course is available to me through my pricey (but outstanding) safaribooksonline subscription:

Deitel

Other than in the lesson video intros (e.g. the one above), you never see Mr. Deitel on the screen. Like many educational videos you can watch for free on YouTube and Kahn Academy,  you see code and a yellow circle highlighter that Paul dynamically steers around  the screen as he explains what the code is doing.

live code

Even though the standard “live instructor” teaching method enables the student to ask a physically-present instructor questions in real-time, I find the video “live code” method much more flexible and effective for the following reasons:

  • You can see the instructor dynamically interacting with the IDE (in this case Eclipse).
  • You can learn at your own speed by replaying lesson snippets that you didn’t fully grasp the first time. (I’m not so smart, so I use this feature all the time).
  • The instructor can compile/run the code in front of your eyes and connect the code with its output by switching between the console and the code editor as needed.
  • The instructor can intentionally insert bugs in the code and step through the debugger.
  • The instructor can switch between the code and detailed online documentation as needed.

Regarding this particular course, I’m thrilled with Mr. Deitel’s work. He’s very thorough, shows great empathy for the student, and he dispassionately points out the differences between Java and C++ as they emerge throughout his code examples.

As I learn more details about Java, I’m confirming what everybody has been saying about the language since its inception: it is a smoother and easier to learn language than C++. However, I (still) don’t like:

  • Centralized garbage collection (I prefer C++’s RAII idiom and smart pointers for localized garbage collection).
  • The fact that all methods are virtual by default.
  • The fact that every user-defined reference type inherits from class Object.
  • The fact that a whole other layer of software, the JVM, sits between user code and the operating system.
  • The fact that Java” steers” programmers toward designing deep, complicated inheritance hierarchies regardless of whether that style fits the application.

Regarding the last point, the mental steerage toward a pure OO programming style is subliminally catalyzed in the way that the JDK library packages are designed and the proliferation of large frameworks in the Java community.  The obsession with deep hierarchies reminds me of Microsoft’s horrendously complicated old MFC framework for writing Windows GUI applications.

I’ve personally seen the effects of a fixed OO mindset in Java programmers who subsequently learn and write C++ production code in my domain: distributed real-time event systems that are naturally “flat“. The code ends up being overly complicated, hard to understand, and very few methods in the deep trees end up being called. The end result is that the “smoothness” of the language is nullified, developer time is wasted on unnecessary code, and the code is hard to maintain.

 

Categories: technical Tags: ,

Spike To Learn

September 22, 2014 5 comments

As one of the responsibilities on my last project, I had to interface one of our radars to a 10+ year old, legacy, command-and-control system built by another company.  My C++11 code was required to receive commands from the control system and send radar data to it via UDP datagrams over a LAN that connects the two systems together.

Radar CC

It’s unfortunate, but we won’t get a standard C++ networking library until the next version of the C++ standard gets ratified in 2017. However, instead of using the low-level C sockets API to implement the interface functionality, I chose to use the facilities of the Poco::Net library.

PocoNet

Poco is a portable, well written, and nicely documented set of multi-function, open source C++ libraries. Among other nice, higher level, TCP/IP and http networking functionality, Poco::Net provides a thin wrapper layer around the native OS C-language sockets API.

Since I had never used the Poco::Net API before, I decided to spike off the main trail and write a little test program to learn the API before integrating the API calls directly into my production code. I use the “Spike To Learn” best practice whenever I can.

Here is the finished and prettied-up spike program for your viewing pleasure:

#include <string>
#include <iostream>
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/DatagramSocket.h"
using Poco::Net::SocketAddress;
using Poco::Net::DatagramSocket;

int main() {

	//simulate a UDP legacy app bound to port 15001
	SocketAddress legacyNodeAddr{"localhost", 15001};
	DatagramSocket legacyApp{legacyNodeAddr}; //create & bind

	//simulate my UDP app bound to port 15002
	SocketAddress myAddr{"localhost", 15002};
	DatagramSocket myApp{myAddr}; //create &amp; bind

	//myApp creates & transmits a message
	//encapsulated in a UDP datagram to the legacyApp
	char myAppTxBuff[]{"Hello legacyApp"};
	auto msgSize = sizeof(myAppTxBuff);
	myApp.sendTo(myAppTxBuff,
                     msgSize,
                     legacyNodeAddr);

	//legacyApp receives a message
	//from myApp and prints its payload
	//to the console
	char legacyAppRxBuff[msgSize];
	legacyApp.receiveBytes(legacyAppRxBuff, msgSize);
	std::cout << std::string{legacyAppRxBuff}
	          << std::endl;

	//legacyApp creates & transmits a message
	//to myApp
	char legacyAppTxBuff[]{"Hello myApp!"};
	msgSize = sizeof(legacyAppTxBuff);
	legacyApp.sendTo(legacyAppTxBuff,
                         msgSize,
                         myAddr);

	//myApp receives a message
	//from legacyApp and prints its payload
	//to the console
	char myAppRxBuff[msgSize];
	myApp.receiveBytes(myAppRxBuff, msgSize);
	std::cout << std::string{myAppRxBuff}
	          << std::endl;

}

As you can see, I used the Poco::Net::SocketAddress and Poco::Net::DatagramSocket classes to simulate the bi-directional messaging between myApp and the legacyApp on one machine. The code first transmits the text message “Hello legacyApp!” from myApp to the legacyApp; and then it transmits the text message “Hello myApp!” from the legacyApp to myApp.

 

loopback

 

Lest you think the program doesn’t work :) , here is the console output after the final compile & run cycle:

PocoTest Output

As a side note, notice that I used C++11 brace-initializers to uniformly initialize every object in the code – except for one: the msgSize object. I had to fallback and use the “=” form of initialization because “auto” does not yet play well with brace-initializers. For who knows why, the type of obj in a statement of the form “auto obj{5};” is deduced to be a std::initializer_list<T> instead of a simple int. I think this strange inconvenience will be fixed in C++17. It may have been fixed already in the recently ratified C++14 standard, but I don’t know for sure. Do you?

Old School, But Still Relevant

August 14, 2014 Leave a comment

“A distributed system is one in which the failure of a computer you didn’t even know existed can render your own computer unusable.” – Leslie Lamport

I’ve always loved that quote. But that’s only one reason why I was overjoyed when I stumbled upon this article written by Turing award winner Leslie Lamport: “Why We Should Build Software Like We Build Houses”. The other reason is that what he wrote is old school, but still relevant in many contexts:

Most programmers regard anything that doesn’t generate code to be a waste of time. Thinking doesn’t generate code, and writing code without thinking is a recipe for bad code. Before we start to write any piece of code, we should understand what that code is supposed to do. Understanding requires thinking, and thinking is hard.  – Leslie Lamport

I recently modified some code I hadn’t written to add one tiny feature to a program. Doing that required understanding an interface. It took me over a day with a debugger to find out what I needed to know about the interface — something that would have taken five minutes with a spec. To avoid introducing bugs, I had to understand the consequences of every change I made. The absence of specs made that extremely difficult. Not wanting to find and read thousands of lines of code that might be affected, I spent days figuring out how to change as little of the existing code as possible. In the end, it took me over a week to add or modify 180 lines of code. And this was for a very minor change to the program. – Leslie Lamport

New age software gurus and hard-core agilistas have always condescendingly trashed the “building a house” and “building a bridge” metaphors for software development. The reasoning is that houses and bridges are made of  hard-to-reconfigure atoms, whilst software is forged from simple-to-reconfigure bits. Well, yeah, that’s true, but… size matters.

In small systems, if you discover you made a big mistake three quarters of the way through the project, you can rewrite the whole shebang in short order without having to bend metal or cut wood. But as software systems get larger, at some point the “rewrite-from-scratch” strategy breaks down – and often spectacularly. Without house-like blueprints or bridge-like schema to consult, finding and reasoning about and fixing mistakes can be close to impossible – regardless of which state-of-the-art process you’re using.

rebuild

Multiple, Independent Sources Of Information On The Same Topic

July 3, 2014 1 comment

I can’t rave enough about how great a safaribooksonline.com subscription is for writing code. Take a look at this screenshot:

Five Books Open

As you can hopefully make out, I have five Firefox tabs open to the following C++11 programming books:

  1. The C++ Programming Language, 4th Edition – Bjarne Stroustrup
  2. The C++ Standard Library: A Tutorial and Reference (2nd Edition) – Nicolai M. Josuttis
  3. C++ Primer Plus (6th Edition) – Stephen Prata
  4. C++ Primer (5th Edition) – Stanley B. Lippman, Josée Lajoie, Barbara E. Moo
  5. C++ Concurrency in Action: Practical Multithreading – Anthony Williams

A subscription is a bit pricey, but if you can afford it, I highly recommend buying one. You’ll not only write better code faster, you’ll amplify your learning experience by an order of magnitude from having the capability to effortlessly switch between multiple, independent sources of information on the same topic. W00t!

Game Changer

June 16, 2014 1 comment

Even though I’m a huge fan of the man, I was quite skeptical when I heard Bjarne Stroustrup enunciate: “C++ feels like a new language“. Of course, Bjarne was talking about the improvements brought into the language by the C++11 standard.

Well, after writing C++11 production code for almost 2 years now (17 straight sprints to be exact), I’m no longer skeptical. I find myself writing code more fluidly, doing battle with the problem “gotchas” instead of both the problem and the language gotchas. I don’t have to veer off track to look up language technical details and easily forgotten best-practices nearly as often as I did in the pre-C++11 era.

It seems that the authors of the “High Integrity C++” coding standard agree with my assessment. In a white paper summarizing the changes to their coding standard, here is what they have to say:

Game Changer

Even though C++’s market niche has shrunk considerably in the 21st century, it is still widely used throughout the industry. The following chart, courtesy of Scott Meyers’ recent talk at Facebook, shows that the old-timer still has legs. The pending C++14 and C++17 updates virtually guarantee its relevance far into the future; just like the venerable paper clip and spring-loaded mouse trap.

Black Duck Chart

An Intimate Act Of Communication

May 19, 2014 2 comments

Take a look at these three state machine models for intimately developing a chunk of functionally cohesive software:

TDD DDT

The key distinguishing feature of the two machines on the right from the pure TDD machine on the left is that some level of design is the initial driver, informer, of the subsequent coding/testing development process. Note that all three methods contain feedback transitions triggered by “learning as we go” events.

In my understanding of TDD, no time is “wasted” upfront thinking about, or capturing, design data at any level of granularity. The pithy mandate from the TDD gods is “red-green-refactor” or die. The design bubbles up solely from the testing/coding cycle in a zen-like flow of intelligence.

Personally, I work in accordance with the DDT model. How about you? For newbies who were solely taught, and only know how to do, TDD, have you ever thought about trying the “traditional” DDT way?

BTW, I learned, tried, and then rejected, TDD as my personal process from “Unit Test Frameworks“. Except for the parts on TDD, it’s a terrific book for learning about unit testing.

Since “design” is an intimately personal process, whatever works for you is fine by BD00. But just because it’s “newer” and has a lot of rabid fan-boys promoting it (including some big and famous consultants), don’t auto-assume TDD is da bomb.

Design is an intimate act of communication between the creator and the created. – Unknown

Follow

Get every new post delivered to your Inbox.

Join 469 other followers

%d bloggers like this: