Archive

Posts Tagged ‘programming’

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

Context Sensitive Keywords

April 17, 2014 2 comments

Update: Thanks to Chris’s insightful comment, the title of this post should have been “Context Sensitive Identifiers“. “override” and “final” are not C++ keywords; they are identifiers with special meaning.

If maintaining backward compatibility is important, then introducing a new keyword into a programming language is always a serious affair. Introducing a new keyword that is already used in millions of lines of existing code as an identifier (class name, namespace name, variable name, etc), can break a lot of product code and discourage people from upgrading their compilers and using the new language/library features.

Unlike other languages, backward compatibility is a “feature” (not a “meh“) in C++. Thus, the proposed introduction of a new keyword is highly scrutinized by the standards committee when core language improvements are considered. This is the main reason why the verbosity-reducing “auto” keyword wasn’t added until the C++11 standard was hatched.

Even though Bjarne Stroustrup designed/implemented “auto” in C++ over 30 years ago to provide for convenient compiler type deduction, the priority for backward compatibility with C caused it to be sh*t-canned for decades. However, since (hopefully) nobody uses it in C code anymore (“auto” is the default storage type for all C local variables – so why be redundant?), the time was deemed right to include it in the C++11 release. Of course, some really, really old C/C++ code will get broken when compiled under a new C++11 compiler, but the breakage won’t be as dire as if “auto” had made it into the earlier C++98 or C++03 standards.

With the seriousness of keyword introduction in mind, one might wonder why the “override” and “final” keywords were added to C++11. Surely, they’re so common that millions of lines of C/C++ legacy code will get broken. D’oh!

But wait! To severely limit code-breakage, the “override” and “final” keywords are defined to be context sensitive. Unless they’re used in a purposefully narrow, position-specific way, C++11 compilers will reject the source code that contains them.

The “final” keyword (used to explicitly prevent further inheritance and/or virtual function overriding) can only be used to qualify a class definition or a virtual function declaration. The closely related “override” keyword (used to prevent careless mistakes when declaring a virtual function) can only be used to qualify a virtual function. The figure below shows how “final” and “override” clarify programmer intention and prevent accidental mistakes.

final keyword

override keyword

override final

Because of the context-specific constraints imposed on the “final” and “override” keywords, this (crappy) code compiles fine:

final and override

The point of this last code fragment is to show that the introduction of context-specific keywords is highly unlikely to break existing code. And that’s a good thing.

Auto Forgetfulness

January 15, 2014 1 comment

The other day, I started tracking down a defect in my C++11 code that was exposed by a unit test. At first, I thought the bugger had to be related to the domain logic I was implementing. However, after 4 hours of inspection/testing/debugging, the answer simply popped into my head, seemingly out of nowhere (funny how that works, no?). It was due to my “forgetting” a subtle characteristic of the C++11 automatic type deduction feature implemented via the “auto” keyword.

To elaborate further, take a look at this simple function prototype:


SomeReallyLongTypeName& getHandle();

On first glance, you might think that the following call to getHandle() would return a reference to an internal, non-temporary, object of type SomeReallyLongTypeName that resides within the scope of the getHandle() function.


auto x = getHandle();

However, it doesn’t. After execution returns to the caller, x contains a copy of the internal, non-temporary object of type SomeReallyLongTypeName. If SomeReallyLongTypeName is non-copyable, then the compiler would have mercifully clued me into the problem with an error message (copy ctor is private (or deleted)).

To get what I really want, this code does the trick:


auto& x = getHandle();

The funny thing is that I already know “auto” ignores type qualifications from routinely writing code like this:


std::vector<int> vints{};

//fill up "vints" somehow

for(auto& elem : vints) {

//do something to each element of vints

}

However, since it was the first time I used “auto” in a new context, its type-qualifier-ignoring behavior somehow slipped my feeble mind. I hate when that happens.

Categories: C++11 Tags: , ,

Staying Sane

November 16, 2013 Leave a comment

Standardization is long periods of mind-numbing boredom interrupted by moments of sheer terror – Bjarne Stroustrup

In his ACCU2013 talk, “C++14 Early Thoughts“, Bjarne Stroustrup presented this slide:

Staying Sane

By using “we” in each bullet point, Bjarne was referring to the ISO WG-1 C++ committee and the daunting challenges it faces to successfully move the language forward.

Not only do the committee leaders have to manage the external onslaught of demands from a huge, dedicated user base, they have to homogenize the internal communications amongst many smart and assertive members. To illustrate the internal management problem, Bjarne said something akin to: “There is no topic the committee isn’t willing to discuss at length for two years“.

committee Pic

In order to prevent being overwhelmed with work, the committee uses this set of grass roots principles to filter out the incoming chaff from the wheat:

Cpp Guiding Principles

I have no idea how internal conflicts are handled, nor how infinite loops of technical debate are exited, but since the all-volunteer committee is still functioning and doing a great job (IMO) of modernizing the language, there’s got to be some magic at work here:

Static If Concepts Lite

Management Idiots And Programming Idioms

October 20, 2013 Leave a comment

In TC++PL, Bjarne Stroustrup introduces the concept of a class hierarchy with this simple business world example:

BS Class Hierarchy

Temporary and Employee base class “objects” get paid by the company to do work that directly creates value. Manager objects inherit an Employee’s responsibilities and encapsulate new, manager-specific, behaviors; like monitoring/commanding/reprimanding non-manager Employees, Temps, and Assistants. Proceeding down the inheritance tree on the right, a Director object inherits the behaviors of both the Manager and Employee classes while adding new “directorial” behaviors.

When BD00 saw Bjarne’s inheritance tree example, he said to himself “Dude, you got it wrong. If you wanted to model the real world, here’s what you shoulda presented“:

BD00 Class Hierarchy

It woulda added a touch of edgy humor to the book, dontcha think?

When I write my first programming book, I’m gonna have diagrams like that and code fragments like this in it:

Access Convenience

I’m thinking of hatching a kickstarter.com project and titling the hybrid book something like “Management Idiots And Programming Idioms“. What would you name it, and would you buy it?

mipi

The Right Tool For The Job

October 5, 2013 Leave a comment

The figure below depicts a scenario where two targets are just about to penetrate the air space covered by a surveillance radar.

Surv Volume

The next sequence of snapshots illustrates the targets entering, traversing, and exiting the coverage volume.

radar scenario

Assume that the surveillance volume is represented in software as a dynamically changing, in-memory database of target objects. On system startup, the database is initialized as empty. During operation, targets are inserted, updated, and deleted in response to changes that occur in the “real” world.

The figure below models each target’s behavior as a state transition diagram (STD). The point to note is that a target in a radar application is stateful and mutable. Regardless of what functional language purists say about statefulness and mutability being evil, they occur naturally in the radar application domain.

tgt std

Note that the STD also indicates that the application domain requires garbage collection (GC) in the form of deallocation of target memory when a detection hasn’t been received within X seconds of the target’s prior update.

Since the system must operate in real-time to be useful, we’d prefer that the target memory be deleted as soon as the real target it represents exits the surveillance volume. We’d prefer the GC to be under the direct, local, control of the programmer and not according to the whims of an underlying, centralized, virtual machine whose GC kicks it whenever it feels like it.

With these domain-specific attributes in mind, C++ seems like the best programming language fit for real-time radar domain applications. The right tool for the job, no? If you disagree, please state your case.

Two Opposing Ideas

October 3, 2013 1 comment

If you didn’t already know it, I’m a fan of the C++ programming language. Of course, not everybody feels the same way. There are many smart people who are among the “haters“.

C++ is a horrible language. It’s made more horrible by the fact that a lot of substandard programmers use it, to the point where it’s much much easier to generate total and utter crap with it. – Linus Torvalds

When I read anti-C++ tirades like Linus Torvalds’ emotionally charged attack, it always stings a little at first. But then I eventually step back from the “emotional-me” and remember (thanks to the teachings of Byron Katie and Eckart Tolle) that the world will never be the way I “demand!” it to be. The length of time it takes me to disengage from abstract thought-storms like these and return to earth is proportional to how deeply I’m attached to one side of the debate stomping around in my head.

“The test of a first-rate intelligence is the ability to hold two opposing ideas in mind at the same time and still retain the ability to function.” – F. Scott Fitzgerald

Java  creator James Gosling, Haskell‘s Bartosz Milewski, and Go creator Rob Pike are three of the more prominent people in the anti-C++ camp.  As expected, they have agendas to promote: advocating their own favorite programming languages at the expense of C++.

Ironically, these rants by smart and well known people can be construed as tributes to C++. That’s probably why this is one of my favorite Bjarne Stroustrup quotes:

There are just two kinds of languages: the ones everybody complains about and the ones nobody use.

Cpp Siege

Pragmatically Feasible?

September 17, 2013 6 comments

From the MISRA web site:

The Motor Industry Software Reliability Association (MISRA), is a collaboration between vehicle manufacturers, component suppliers and engineering consultancies which seeks to promote best practice in developing safety-related electronic systems in road vehicles and other embedded systems.

While browsing through the MISRA C++:2008 standard, I came across this not-unexpected requirement:

No Heap

I don’t know enough about the standard to know if it’s true, but I interpret this requirement as banning not only the use of “new/delete“, but also as banning the use of the dynamically managed STL container abstractions (vectors, lists, sets, maps, queues) and, hence, the many standard library algorithms that operate on them. I wonder what the MISRA Java specification, if there is one, says about dynamic memory allocation.

If my interpretation of 18-4-1 is correct, then the requirement can severely jack up the cost, schedule, and technical risks of any software component that is required to be compliant with the specification. For non-trivial applications requiring more than low-level, statically allocated arrays…..

Complexity is pushed out of the language and into the application code. The semantics of language features are far better specified than the typical application code. – Bjarne Stroustrup & Kevin Carroll

Because of the safety-critical nature of embedded automotive software, I can understand the reasoning behind the no-dynamic-memory-allocation requirement. But is it pragmatically feasible in today’s world; especially since software components keep getting larger and commensurately more complex over time? In other words, is it one of those requirements that doesn’t scale? Is it too Draconian?

For those C++ programmers who work in the automotive industry and happen to stumble upon this blog (which will probably be none), what has been your experience with this MISRA requirement and some of the other similarly unsettling requirements in the specification? Are “waivers” often asked for and granted? Is it an unspoken truth that people/companies pay public lip service to the requirement but privately don’t comply?

misrable

Follow

Get every new post delivered to your Inbox.

Join 438 other followers

%d bloggers like this: