Month: February 2014

Architecture: More Than Drawing Buildings

Chances are, if you are in the habit of speaking to programmers, you will hear someone referred to as an “Architect”. Surely, This person is not the designer of the building, still deeply involved with the company inhabiting it. Surely of all the places in a corporation in which to place such a person, the development team would not be the first choice.  And yet, no dev team would be complete without at least one architect.In case you haven’t figured it out, the architects I am referring to deal with the code architecture. Their job parallels that of a traditional architect in all ways but the medium. Where a traditional architect explores viable designs for the building appearance, the code architect is concerned with the appearance of the code. Just as the traditional architect can draw from Gothic, Renaissance, or Modern structures,  a code architect uses design patterns to match the desired appearance of the code. Design patterns should be familiar to those who have perused code banks before. Patterns such as the Factory Pattern, Singleton Pattern, and  FlyWeight Pattern (more here) are the frameworks off of which code architects build the structure of their application. These applications may have a unique structure by the end, but often include large sections adhering to one or more patterns.

Why do I care?

I am in a unique situation for this question. As a student, I have seen and written MANY poorly architectured programs. I am myself guilty of the monolithic class, every violations of SOLID principles known to man and beast, and cyclical dependencies galore. What sets me apart is that I have seen the error of my ways. At my first development job, I got to work with a veteran of code architecture. He encouraged me to separate concerns, abstract business logic away from models, and write an enterprise software that was maintainable and scalable. The difference in my code was astounding. No longer did I have multi-thousand line classes. No longer need I worry about changing constructors or variable names. The architecture allowed me to create concrete references, set it and forget it.

But… That’s a lot of work…

I know the pain. For instance in my current project I am designing a Pantry Manager/Recipe box/Meal Planner. If I want to make a new button on the UI that saves an item to the pantry I must follow a checklist:

My Recipe Box Architecture

My Recipe Box Architecture

  1. Create Class (in this case some thing like pantryItemModel in the Models Project)
  2. Create method in the relevant Manager (in this case the PantryManager in the Manager Project)
  3. Add method definition to Manager Interface (IPantryManager in the Interfaces Project)
  4. Create method in relevant Data Access Object (DAO) class  (PantryDAO in the Data Project)
  5. Add method definition to the DAO Interface (IPantryDAO in the Interfaces Project)

God forbid I need a new manager or DAO, because then I have to alter the Manager and DAO Factories in the FactoryProject. As you can see, the method call is passed down the chain. This seems unnecessary at a first glance; why not just write the method from the DAO in the UI? It is all about scalability. When the project grows, it is likely to change. The data fetching and saving however is likely to remain constant. By abstracting the business logic away from the data logic, changes can be made on the front end which use the same methods from further back. The structure also allows for project isolation, wherein no class knows about anything but what is needed for its function.

How could this benefit me?

Once the checklist above is complete for all data fetches and saves, the benefits become clear. Now when I want to save a new item in the pantry, I simply gather the form data into a new PantryItemModel, and pass that up the chain with something like this:

//domain call
private void savePantryItem(PantryItemModel pantryItem){
IPantryManager manager = ManagerFactory.getPantryManager();

With a set of domain calls for each user control, I can rule the WORL- ahem. I mean: I can rapidly code the UI and all gather all necessary data for display or saving. A couple long nights of setting up the architecture turns all the business logic and tweaking in to a few hours work. Mistakes happen, bosses change their minds and clients complain. Isn’t it better to change the wallpaper, rather than rebuild the wall?

Blog Stuff

I would like to formally apologize for my drop-off in posts lately, and let you know whats next. My bartenderbot project has hit a brick wall in the form of limited time. The next step is the construction of the frame for testing, and until I can find the time to hit up Home Depot for some resources, and then construct said resources, the project remains on my shelf. As such, the desire to code has manifested itself in the form of my Recipe manager thingy (which needs a name BTW) so updates on that are coming soon. Until then, grab a drink and code on.


Data Structures

Hey guys, sorry I’m a little late with an update and grasping at straws here for a topic, but I have a good excuse. For those of you who don’t know, Atlanta froze over a couple weeks ago.  Instead of being a responsible student, I let my inner child out and spent my week in the snow instead of doing work. As such, I fell behind and had to do 3 projects this week. Also, I have been doing interviews in all my free time, so I’ve got interview questions on the brain.

Strings. Always Strings.

In every single interview, the coding problem involved string manipulation. After the first interview, I intensively studied the string functions. However, after figuring out more intuitive solutions to most of the problems I learned the real important concept is Data Structures. The majority of programmers will solve a problem using a list or an array first, operating explicitly on strings or lists of strings. This allows the code to be understood easily, while still solving the problem. Problem is that they are usually not optimized at all. Using a data structure can exploit the behaviors of the structure, thus increasing efficiency while decreasing readability. For instance. My example data structure will be a hash table. I will demonstrate the verbose problem solution, and the optimized solution.

The Problem

Given a list of words, organize the words into groups by anagram.

Example :

in: [act, cat, tar, banana, rat]

out: [[act cat],[tar,rat],[banana]]

The verbose method of solving this problem involves iterating over each word and each group (nested) to discover where a word fits, or if you need a new group. This takes a very long time, but is easily readable with clear loops and order.

Readable code for anagram grouping

Readable code for anagram grouping

Its not fast, its not elegant, but it is functional.  On the contrary, a solution using a hash map is functional, fast, but very confusing at a glance. A hashmap uses a method called “hash()” to create an indexed key for data. In this case, creating a hash function which is based off of the component letters of a word allows us to map all words of the same hash value (same letters) into a single group. By exploiting the behaviour of the hash table, we can “chain” all these mapped words into lists, then return all non empty lists. With a mapping and lookup time of O(1) and a hashing time of O(n), we have a very fast function.


The moral of this post is to never let yourself be contained. A problem often has many sides, some of which could save time and resources. Programming is all about finding the unity between a problem and the desired solution in the language of logic and math. While humans are especially gifted at pattern recognition, it takes a special kind to see the reasoning behind the patterns, and teach a computer to recognize them. Sometimes a String problem is not String problem at all.

Fun with Decoders

When I posted a picture of my BartenderBot project in an earlier post, I received a comment inquiring as to the small number of pins I was using on the pi to control 8 valves. I promised a full post, and by golly I will stick by that promise. The secret of this magical pin reduction is a decoder (also called a DeMultiplexer or a DeMux).

What’s a DeMux?

Toggling a single input

Toggling a single input

A DeMux is a combinational logic circuit. It takes in a set number of “selector” bits and one “enable” bit. The output is a number of pins determined by the maximum number expressed in the number of selector bits (more on that later) where only the one corresponding to the selection is toggled when the enable bit is toggled.

Think of the number of outputs as a binary string. For instance to represent 8 unique numbers in binary, you need log base 2 of the output, which is 3. Three bits can express numbers 0-7, so choosing a binary string who’s value is equal to one of those numbers “selects” that output. Using this, you can turn on any number of inputs (n) with log base 2 selector bits and 1 enable bit.

Quick Example: If you want to turn on the third valve, we need to turn on output 2. So, we set our selector bits to 010 ( append as many zeroes as necessary to the left of that number to fill all selector bits).  Then, we turn on the enable bit.

Programming with a DeMux

Code to provide input to the DeMux

Code to provide input to the DeMux

As the astute among you may have noticed, the DeMux requires a very specific input pattern. The non-decoder method of turning on an output, one pin would be wired to each device and turned on only when the device is needed. With a DeMux, we must share pins across several valves. For instance, every odd output must turn on the least significant bit of the selector. One also must remember that in programming (and the DeMux) number series begin at zeroes, while in typical ordering, numbers start at one.  By simply subtracting 1 from the valve number and converting the result to a binary string, the states of each selector pin can be determined. The basic principle is to iterate through the binary string generated from (valveNum-1). Pins[i].state = (binaryString.charAt(i) == 1).

The pins themselves are controlled by a Java plugin called Pi4J, which allows Java objects to be made which update the GPIO pins on the pi during operation. As you have seen, the objects have fairly simple behaviour. The pins can be set on or off, true or false, high or low (all to the same end), can be pulsed, and (unused in this project so far) can listen for input.

All Together Now

Let’s tie it all together now. A recipe requires 2 oz Vodka (valve 1), 1 oz Peach Schnapps (valve 6), and 9 oz Orange juice (valve 8). For easy math, let’s assume 1 oz takes 1 s.  The recipe sends each instruction to the hardware controller, which turns on the following pins in the correct order:

GPIO17 | GPIO27 | GPIO22 | GPIO23    (time) ->  GPIO17 | GPIO27 | GPIO22 | GPIO23

0001 (2 sec) -> 0000

1011 (1 sec) -> 1010

1111 (9 sec) -> 1110

The DeMux described earlier feeds the relay board and behaves as expected. The obvious drawback here is the “One-hot” behaviour, which means only one valve can pour at a time, but for simplicity, reduced pin numbers, and no risk of backflow the benefits outweigh the disadvantages. I hope this has been a thorough explanation of Decoders, and I hope any interested parties can now make full use of these wonderful IC’s.