Inherited Problems

When developers first begin learning object-orientated programming inheritance usually stands out more than any other language feature or practice. It’s introduction can come in many flavors, my favorite of which is the shape hierarchy. An abstract base class, Shape, has many derived concrete classes like Triangle, Circle, and Square. Shape itself has methods for calculating area, or perimeter that the derived classes can provide implementations for1. It’s one of many possible examples (another is the Animal hierarchy) that demonstrates how inheritance, coupled with other practices like polymorphism and encapsulation can create powerful models of behavior and data.

In my experience, the real value and purpose of inheritance begins to get cloudy after that first introduction. In fact, I personally have used inheritance incorrectly for most of my career. More often than not it’s used as a mechanism to reuse code. How many of us have written or seen classes like this:

  • AbstractEntity
  • AbstractController
  • AbstractService
  • AbstractRepository

I’ve written classes just like these, adding methods that can be overridden in derived classes (AbstractEntity.saved, etc..) and gone on my merry way, happy that I’m reusing code and providing extensible points in the code base, completely unaware that I’ve laid the foundation for a future problem. In fact, these can sometimes start as interfaces masquerading as abstract classes. When you apply inheritance to only reuse code, you’re not doing so in order to create a polymorphic hierarchy, where different instances in the hierarchy can be substituted for one another. In the shape hierarchy an instance of a Shape can be a Triangle or a Square and the two are interchangeable. A non-developer would agree the two are members of the same hierarchy. That is not always the case if you have an AbstractController or AbstractEntity who’s reason for existence is to provide a repository for reusable methods to derived classes. In other words, there’s no behavioral or classifiable relationship between the types in the hierarchy outside of them residing in the same layer or functional area of the application (Controllers, Domain, Services), there’s only an implementation-level relationship.

Now there’s a coupling nightmare in the works as code living in the base class begins to grow, instantly bestowing behavior to all derived classes that many times they need to augment because the behavior doesn’t apply or the logic for applying that behavior is subtly different. So more abstract classes are introduced in the middle of the hierarchy (AbstractPersonEntity, AbstractTaggedEntity. AbstractAdminController), so that we can keep things DRY. What happens when a particular derived class needs to reuse code from two of these inner abstract classes, say a taggable person? Nope, many modern OO languages disallow multiple inheritance2. Suddenly inheritance isn’t paying off at all.

Inheritance is one of the most abused patterns in object orientated programming. Many of us have used inheritance as a mechanism to keep things DRY and reuse code. Odds are, it was the wrong choice. What to do? Composition. If a particular behavior is common and needs to be reused, create a class that can be used. These classes always have a well defined interface and can have multiple implementations the rest of the system can take advantage of. A controller for editing people can use a repository that performs heavy auditing, an entity that can be tagged can defer to the reusable tagging code lying in a TagSet class. As this is applied throughout the code it becomes clearer how certain implementations are solving common problems, and if changes to one particular part of the system need to occur, they can be made in isolation much easier. Code re-used via composition benefits from a much narrower contract than large, complicated abstract base classes and it’s much easier to test and make changes to than if it were sitting among a dozen other concerns.

  1. My simplified shape example is also kind of awkward in that Shape as described isn’t providing behavior, though the example could be expanded upon so that it does in a reasonable way.
  2. Not to imply that I consider multiple inheritance a good solution.
Advertisements

DFRobot 4WD Encoders

My latest robotics platform is the DFRobot 4WD, a respectable step up from the Tamiya Tracked Chassis I was using before.. The second thing I bought after the platform itself was the standard Wheel Encoder Set that everyone probably buys when they get the chassis. This has proven to be a pretty valuable lesson in what to look for in encoders.

Installing them was pretty easy and didn’t pose any serious problems. On my pair the spacers that set them away from the gearbox were too short and so I trimmed down some spacers I already had. My real problems started when I tried using them… Basically, I don’t think they’re good for anything but very rudimentary feedback. They simply don’t have the resolution I would like, especially at lower speeds.

To squeeze more resolution out of them I made some encoder wheels with 16 divisions instead of 10. I used the program mentioned in this article and had Kinkos print them onto some transparencies for about $1.50. I tried a few different resolutions, including some very optimistic ones and 16 was the best. You can see that I doubled up two copies as that felt stronger and was sure to block out any imperfections each wheel had from the printing. Right now I’m happy enough as I’m using fast enough speeds so that I get enough ticks per cycle to produce feedback on. I’ve been considering ways to move the wheel to the motor shaft itself, before the gear reduction where it’ll be moving much more (maybe too much!), especially at lower speeds. Not sure it’s possible yet, as that will be a very tight fit. Anyway, though it may go without saying, don’t expect the world from these encoders and if you’re already considering a more serious solution you may just want to skip to that.

Kitchen Table Robotics

This past Christmas was an Arduino Christmas for me. I got a couple of Arduinos and some accessories and it’s taken off into quite an obsessive hobby, completely taking over my kitchen table (We live in a small apartment). Anybody who gets into electronics through the Arduino will probably decide to build some kind of robot at some point in their adventures. For me the goal was to provide some kind of structure to my electronics/microcontroller tinkering. Similarly, when I’d like to learn a new programming language or framework, I pick a project to implement. To test the waters I picked out the cheapest kit/parts I could find and dove into seeing what I could do with it.

Basic Platform

I started with the Tamiya Tracked Vehicle Chassis and the Tamiya Twin Motor Gearbox. Eventually I swapped out the motors for the higher voltage Solarbotics RM3 and picked up a couple of Tamiya Universal Plates to support the electronics and batteries.

A tracked chassis seemed easier to start with due to the differential drive. To learn as much as possible along the way I decided to build my own basic motor controller based on the SN74410. I then added some back-emf sensing after stumbling upon this post. The post explains the details, but basically on each motor there’s a pair of voltage dividers connected to an analog pad on the Arduino. Every 100ms the software stops the motors, pauses for 2ms so things can settle and then samples the voltage on that motor for 2ms more. That average is proportional to the physical speed of the motor and with some calibration we can match speeds of the motors, among other things.

Power

My brother in law is addicted to RC helicopters so I consulted him on some LiPos. He suggested a receiver pack because my current requirements weren’t insane. I went with the Zippy FlightMax 2100mAh 2S which has worked great. For charging I got the Thunder AC6. I wasn’t interested in anything more serious until I was sure I’d get my moneys worth and so far it has worked great. Because I fried one of my voltage regulars due to a polarization mishap I grabbed a set of Anderson Powerpoles and attached those to the batteries and made a few utility cables. I’m very happy with them, though I wish they were a little smaller as they’re kind of big for my needs. Also, I used solid core hookup wire on power system and next time I’d use stranded for the extra flexibility, frequently disconnecting and connecting the battery is annoying with rigid wires. Also, I’m using the Pololu D24V6AHV to step the battery voltage down to 5V to drive the Arduino instead of using the on board linear regulator.

Tread Encoder

I attempted a simple encoder system using SparkFun’s SEN-09299. I mounted them under the second story of the chassis, hoping the beam would sneak through the tiny holes in the tread allowing me to see them tick by.

Unfortunately, this proof of concept didn’t produce a reliable square wave as the tread moved. I think there’s still merit to the idea though, especially if the photo interrupter could be mounted tighter to the tread so that the IR isn’t leaking around  the outside. I opted to just hold off until I could do a proper encoder on the motor’s shaft.

Pololu IMU

I’m a big fan of Pololu. They’ve got a ton of very useful stuff on their website with great documentation. It’s also nice that they’re nearby (Las Vegas, I’m in Southern California) so everything arrives quickly. I picked up their MinIMU-9 to toy around with, you can see the part mounted on the picture below.

With the help of their sample code I pieced together a feedback loop to maintain a heading. This was very successful as it would do a great good job of turning back to its original heading if bumped off course, for example. It’s a great little board, especially with the DCM library they link to on their site. I’ve since broken the MinIMU-9 and an ATMega328P out onto a separate, configurable board that’s running the DCM algorithm and can speak I2C. I’ll do a post on that later.

Final Product And Thoughts

Here are a few more pictures of the robot. It’s been dismantled now so that I could use the parts, as is the circle of robot life.

You may have noticed the IR detector on the servo in the front for obstacle detection. That’s just a tiny peak into the autonomous behavior I’m getting into now. More on that in a future post.

So yeah, that’s about all I got on this project, hehe. I’ve already bought my next platform, the DFRobot 4WD so there will be more to come on that. I’ve also gotten out of the motor controller business and am using an off the shelf one so that I can focus more on autonomous behavior. Making my own simplified/naive one was great fun though.

Lexy – A web UI for LXC.

In my free time I’ve been throwing together a web console for managing LXC containers called Lexy. If you’ve never heard of LXC, please check out my previous post or a lot of this won’t make much sense. My goal was to build a UI for easily creating and starting new containers. Once that was working, I wanted the ability to create reusable configuration which took me into the world of Puppet and Chef. I’ve been using Lexy on my local server for a few weeks and so I figured I should get some more eyes on it.

Features

Lexy lets you:

  • Create and configure containers (networking, fstab, etc…)
  • Manage SSH keys associated with containers (like EC2)
  • Start/Stop LXC Containers
  • Manage “user data” scripts (again, like EC2) that are executed at startup.
  • Recycling of containers – nuking and recreating them.
  • Display running processes and the containers syslog.

Here’s some key points on its implementation:

  • Web application in Sinatra.
  • Background application using stalker, for actually manipulating the containers.
  • Data managed by DataMapper and stored in SQLite by default (background process has read-only access)

Container Provisioning

To eliminate some of the magic behind what’s being done, here’a description of the steps Lexy takes when creating and configuring a new container:

  1. Unpack the included rootfs image (ubuntu-10.10.tar.gz)
  2. Generate LXC configuration file and fstab file.
  3. Setup container paths (UI allows host directories to be easily mounted)
  4. Configure SSH keys for the root user.
  5. Configure networking (/etc/network/interfaces, /etc/hosts with container name)
  6. Configure startup scripts (run via rc.local)

There’s a heavy bias here on Ubuntu, it’d be nice to support other root filesystems in the future, but that’s not something I’m intending on adding myself.

I don’t have any big plans feature wise right now. What it could use are some better installation docs. Things aren’t too difficult to get running after you’ve got LXC setup.

Lexy is on github.

LXC is Awesome

I don’t think I can stress how excited I was after discovering Linux Containers. With all of the attention being given to cloud computing and virtualization I’m surprised more people haven’t been talking about LXC. If you haven’t heard of them, here’s a good description from the docs:

Linux Containers take a completely different approach than system virtualization technologies such as KVM and Xen, which started by booting separate virtual systems on emulated hardware and then attempted to lower their overhead via paravirtualization and related mechanisms. Instead of retrofitting efficiency onto full isolation, LXC started out with an efficient mechanism (existing Linux process management) and added isolation, resulting in a system virtualization mechanism as scalable and portable as chroot, capable of simultaneously supporting thousands of emulated systems on a single server while also providing lightweight virtualization options to routers and smart phones.

If you’re convinced of the benefits of virtualization, you’re probably already interested. Many of the benefits of virtualization apply to linux containers, as well as a few others:

Fast and Easy

Once you’ve done the initial footwork, setting up new containers is very simple and as easy as tweaking some configuration and uncompressing the archive containing the container’s root filesystem. Once a container is running, all of the processes in the container are visible from the host machine, so tools like ps and htop will show you everything that’s going on.

Resource Efficient

Unlike virtual machines, containers don’t need to be given fixed amounts of memory or CPU. Unless you’re taking advantage of the overcommitting features available in most virtualization technologies you’re fairly confined on how you can divide resources among virtual machines. With linux containers you have far more control and flexibility. Simply create containers and allow the operating system to divide resources appropriately. You can also use process limits to gain any extra control you may want.

Useful

I’ve found several uses recently for LXC and I’ll be posting more about them in the future, here are just a few:

  1. A platform for developing Chef/Puppet scripts.
  2. Throw away servers for experimentation.
  3. Configuring and testing cluster configurations.

As a work-from-home software engineer with a single server machine beside my desk it’s made my life much more comfortable.

Links

Hello world!

Hey there! So, this post marks my tentative return to blogging. Once upon a time I was a .NET developer (ASP.NET MVC, NSB, MonoRail, NHibernate, etc..) who had the time to write the occasional post. Then, I became very busy. Now, I’m a Java developer (at a new job!) who has more free time and would like to give this blogging thing another try. Currently, I’m planning to talk about Java, Spring, Ruby, Linux, System Administration, and… well… let’s just say software engineering in general and all things ancillary to that. Stay tuned.