Chad Dotson

A small town Computer Scientist / Software Engineer. Chad enjoys writing Python and JavaScript as well as tinkering with his Raspberry Pi and Arduino. When not programming, he enjoys Photography (especially lightning) and Sci-Fi.
A small town Computer Scientist / Software Engineer. Chad enjoys writing Python and JavaScript as well as tinkering with his Raspberry Pi and Arduino. When not programming, he enjoys Photography (especially lightning) and Sci-Fi.

Knowing When You’ve Wrote Crappy Code

Note: This article was kicked off by one I read over at LosTechies.

We write lots of code, statistically speaking some of it is what we’d deem as “crappy.” If you’re doing things right and progressing in your career and your understanding; your definition of “crappy code” should change over time.  This is very important concept for a good Software Engineer, its one of the ways we get better.  We recognize our past coding mistakes and work to better them.

Dangers of Crappy Code:

  • It could hide technical debt.  “I don’t really know how or why this works, but here it is. Done.”
  • You’ve not taken the time to make what works, right.  This potentially leads to bloated code, duplication, and an overall poor product quality.
  • Is it robust?
  • It is, potentially, not very reusable.
  • Can I hand this code off to someone else and they understand it?

Preventing Crappy Code:

The prospect of writing crappy code should not prevent you from getting a project working.  However, it is very important to make it as right possible before committing the code changes to the repository.

  • Write self-documenting code.  Some developers may scoff at this statement, but self documenting code is very possible in just about any language.  Remember comments are your failure to communicate.
  • Remember to refactor, refactor, and refactor.
  • Ask for the opinion of a peer.  This should be someone you consider qualified enough to give an opinion.
  • Use “TODO” comments so your thought process is not lost and it will serve as a reminder that you must still make something right.  This doesn’t prevent crappy code from making it into a project but it documents its existence.

What To Do When You Find Crappy Code:

For the sake of this topic, lets assume you run across some crappy code 2 years into maintenance of a software product.

  • Identify why it is “crappy.”
  • Does it work or has it unknowingly introduced bugs into the system?
  • Perhaps leave a NOTE comment in the code, especially if it can add insight into the function of the crappy code.
  • Only change the code if it is within the scope of your current task.  Remember that it has worked for 2 years and changing it now could potentially introduce error.  If you do end up changing the code, attempt to make it right before you finish.  Also make sure to update your unit tests.

Are you Ready?  A Simple Test

Review a code base that you wrote 2 years ago.  Did you find “crappy code?”  The answer should almost certainly be a “Yes.”

 

Posted by Chad Dotson in Doing Things Better, Key Concepts, Programming, Software Engineering, 5 comments

The Flood of Social Media Posts – Whats Wrong, How To Mitigate It, How To Fix It

What’s Wrong

Since its creation, social media has taken off at an exponential rate.  Each day more and more people are creating accounts and contributing to the feed.  Facebook is the service most readily adopted, mainly because of the people already on it.  In the case of Facebook, lets say that the typical user has 200-300 friends and lets say that just a quarter of those (50 of 200) are enthusiastic posters (2-3 posts/day).  That equates to somewhere north of at least 100 posts per day then add to that the posts from your other friends.  Lets make a guess of an overall total of 200 posts/day on just that one social media outlet.  Facebook’s solution to the inundation of posts is the top posts vs recent posts feature.

Skip to the services that I think are the most susceptible to inundating users with content: Twitter and Pinterest.  As a user of Twitter, it seems that I have trouble following over 40 people.  Once upon a time I followed near 90 people and found that useful posts actually got buried in the noise.  Pinterest on the other hand seems to violate all that is good with respect to UI design; it is way to busy and your eyes don’t follow any particular lines.  Liberal use of pinterest’s follow feature can unintentionally muddy the content you see.

Tips On Dealing With It

I think the only way to fix usage of Twitter is to limit the number of people you follow.  Pick high quality, low post rate users.  This will improve the overall quality of content you get.  For Pinterest, limit the number of users or boards you follow.

How To Fix It

How do you fix being inundated with content?  Facebook is certainly trying to fix it via their “Top Posts” feature.  The top posts feature attempts to make guesses about what you want to see based on your interests, what you’ve looked at in the past, and probably other metrics (and controversial stuff such as a recent study).  Even though I don’t care for their current top posts feature I believe Facebook is on the right track.  It all boils down to the ability to listen to everything but only pay attention to what your interested in, even when you may not 100% know yourself.

I think the ultimate “Top Posts” algorithm would take into account the following:

  • What you’ve looked at in the past. (Given)
  • Users would be given preferred tags based on what they view.
  • It would tag each post and each would receive an initial ranking based on the types of posts the user normally make.
  • The initial ranking score given to a user’s posts is a function of how well their posts have done in the past.
  • Each post’s rank is updated in each of its tags as people view them based on their rank in the tag category.

Up Next: I may decide to make a post discussing a theory of how people leave one service and adopt another.

Posted by Chad Dotson in Misc, Ramblings, Tips, 0 comments

Apple’s Magic Mouse – A Software Engineer’s Perspective

Over the past month I’ve been trying to make the transition from my old windows environment to an OSX environment.  Part of the transition involved buying a Magic Mouse.  Apple’s Magic Mouse is definitely a very interesting device.  It is a very accurate mouse with the added capability of a gesture enabled touchpad.  While I like it, the negatives are over powering the positives… at least for me.

  • It seems too small, at least for my hand.
  • While you can scroll by using the integrated trackpad, there is no out of the box concept of a middle click.  I don’t use that when coding, but I sure use it alot when browsing the web.  I was able to get it back by installing the 3rd party tool “BetterTouchTool.”
  • The integrated trackpad is over half of the device.  I find that I mistakenly activate it alot.
  • The single action of the device whether right or left clicking is irritating.  Maybe its just the size of the device that makes this seem irritating.

While I think it maybe great for some people, I’m not sure they are great for everyone.  While I am not going to get rid of mine, I am starting to use my old Microsoft Mouse more often again.  About the only thing I miss about the Magic Mouse is the trackpad scrolling.

Posted by Chad Dotson in Ramblings, Technology, 0 comments

Isolate, Understand, Implement

Isolate, understand, implement: three very important things to remember when adding, modifying or replacing features on a project.  The first step is to isolate the feature.  Hopefully, your project is designed in such a way that once the code is isolated it is in a single place.  The next step is understand.  Meaning understand what the code currently does.  Run the unit tests.  Make sure you know without a doubt why the code works and what the code does.  Also understand any effects that your changes might have.  And finally, implement the new code or changes.  During this phase you’ll modify the unit test set as appropriate, make the necessary changes to the code base, and ensure that the application is stable before pushing it back to your repository.

Posted by Chad Dotson in Doing Things Better, Key Concepts, Programming, Software Engineering, 0 comments

Generating JSON Documents From SQLite Databases In Python

Special Note

This article assumes that you do not wish to use a more sophisticated ORM tool such as SQLAlchemy.

Some Setup

Let’s start with a Q&D sqlite database given the following sql.

create table sample(column1 INTEGER, column2 TEXT, column3 TEXT, column4 REAL);
insert into sample(column2, column2, column3, column4) values(1, "Record 1 Text A", "Record 1 Text B", 3.14159);
insert into sample(column1, column2, column3, column4) values(2, "Record 2 Text A", "Record 2 Text B", 6.28318);
insert into sample(column1, column2, column3, column4) values(3, "Record 3 Text A", "Record 3 Text B", 9.42477);

You can create the sqlite database given the following command.

$ sqlite3 sample.db < sample.sql

Some Different Methods

For this example we want each record returned via the sql select statement to be its on JSON document.  There are several ways of doing this.  All of them solve the problem reasonably well but I was in search of the best way.  In checking python.org, I discovered that the sqlite connection object has an attribute falled row_factory.  This attribute can be modified provide selection results in a more advanced way.

Method 1 – My Preferred Method

From the python docs, we find that they already have a good factory for generating dictionaries.  It is my opinion that this functionality to should be more explicitly enabled in the language.

In this method, we override the row_factory attribute with a callable function that generates the python dictionary from the results.

# https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.row_factory

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

 Method 2 – Almost As Good As Method 1

This method is just about as good as method 1.  Matter of fact, you can get away with this one and be just fine.  Functionally, the methods are almost identical.  With this method, the records can be accessed via index or via column name.  The biggest difference is that unlike method 1, these results don’t have the full functionality of a python dictionary.  For most people, this might be enough.

con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

Putting It All Together

The following code snippet will extract a group of dictionaries based on the select statement from the sqlite database and dump it to JSON for display.

The Code

#!/bin/python

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

connection = sqlite3.connect("sample.db")
connection.row_factory = dict_factory

cursor = connection.cursor()

cursor.execute("select * from sample")

# fetch all or one we'll go for all.

results = cursor.fetchall()

print results

connection.close()

 The Results

[
    {
        "column1": 1,
        "column2": "Record 1 Text A",
        "column3": "Record 1 Text B",
        "column4": 3.14159
    },
    {
        "column1": 2,
        "column2": "Record 2 Text A",
        "column3": "Record 2 Text B",
        "column4": 6.28318
    },
    {
        "column1": 3,
        "column2": "Record 3 Text A",
        "column3": "Record 3 Text B",
        "column4": 9.42477
    }
]

 

 

Posted by Chad Dotson in Programming, Tips, 3 comments

First Impressions of Rust

Today I finished my first program written in Rust 0.10.  As with my article on Dart earlier this weekend I’m going to rely on Wikipedia for short intro for what Rust is.

The goal of Rust is to be a good language for the creation of large client and server programs that run over the Internet.[13] This has led to a feature set with an emphasis on safety, control of memory layout and concurrency. Performance of safe code is expected to be slower than C++ if performance is the only consideration, but to be comparable to C++ code that manually takes precautions comparable to what the Rust language mandates.[14]
Wikipedia

My first Rust program followed the same pattern that some of my other coding exercises have followed, that is implement an N-Queens puzzle solver.  While not terribly complicated, the puzzle does force an introduction to several important aspects of the language.  Since this was my first take on Rust, I am sure that my implementation isn’t great.

I found Rust to be an interesting language.  One of the more interesting opinions I developed about it was that it really prevents developers from doing something stupid.  That’s probably why it gets high marks for safe, concurrent code.  If I were to compare Rust to any other languages, I would say that it is syntactically similar to Scala and C++.  The strictness of the compiler does make learning the language a little more tedious than some other languages, but nothing that can’t be overcome.  I am probably a little biased on that point too since I’ve been writing a lot of Python lately.

On performance, I did noticed that it was about 60% faster than a architecturally similar python n-queens script I wrote.  I guess that’s not entirely unexpected from a compiled language.  I really want to figure out Rust’s threading capabilities.  That should greatly improve performance of the puzzle even more since it parallelizes well.

Rust has some serious potential and I predict as the language progresses, we will see more apps being written in it and more libraries available for it.  I for one will be continuing to tinker with finer details now that I have this program done.

Links:

Posted by Chad Dotson in Programming, 1 comment

First Impressions of Dart

Today I finished my first Dart tutorial.  For those that don’t know what Dart is, Wikipedia has a nice synopsis that I’ve included here.

Dart is an open-source Webprogramming language developed by Google. It was unveiled at the GOTO conference in Aarhus, October 10–12, 2011.[4] The goal of Dart is “ultimately to replace JavaScript as the lingua franca of web development on the open web platform”,[5] but Dart currently relies exclusively on its cross-compilation to JavaScript feature in order to run in mainstream browsers. Dart is intended to address issues with JavaScript that Google engineers felt could not be solved by evolving the language, while offering better performance.[5] Google works on Dart to help it build more complex, full-featured client-side Web applications.[6]

Dart is a class-based, single inheritance, object-oriented language with C-style syntax. It supports interfaces, abstract classes, reifiedgenerics, and optional typing. Static type annotations do not affect the runtime semantics of the code. Instead, the type annotations can provide documentation for tools like static checkers and dynamic run time checks.

Wikipedia

While the tutorial was simple and designd to be completed in about an hour, I found it a worthwhile and informative endeavor.  It was just enough to give an introduction to the language and syntax.  As the above snippet from Wikipedia states, Dart cross-compiles into JavaScript and should be familiar to people who know another C-style language.

I have a high degree of experience with object-oriented design, C++, and JavaScript and Dart has left me with a good first impression.  I believe an important aspect of Dart is that it could be used to bridge the gap between C-style languages and JavaScript for programmers who do not have a lot of JavaScript experience.  I do not believe that Dart will ultimately replace JavaScript, as Google hopes.  JavaScript, while it has shortcomings, is ultimately very powerful and flexible.  Dart’s ultimate utility will be something akin to CoffeeScript that is making it easier and less tedious to write JavaScript.  In the coming weeks I may delve further into Dart, though up next I will probably do a tutorial or two on Rust.

Links: Dart 1-hour tutorial

Posted by Chad Dotson in Programming, 1 comment
My First Raspberry Pi Project

My First Raspberry Pi Project

View of the whole setup

View of the whole setup

Almost every year, I try to select a fun project to do while off for Christmas. This year the project I selected was based on Raspberry Pi.  Specifically I decided to build a device that would, when motion is detected, find the range to the motion using an ultrasonic rangefinder, take a picture using the camera module, and finally email me the results.

After just a few hours of work, I had separate proofs of concept working for each sensor written in Python.  A short time after, I started combining all the proofs of concept into a consolidated script which I got working.  Right now I am perfecting the classes for interfacing with the range finder and the motion detector and I am currently using picamera 0.8 for interfacing with the camera module.  I’ve included a link to the git repository I’m using for source control below.

Equipment:

  • Raspberry Pi Model B
  • Raspberry Pi 5MP Camera Board Module
  • HC-SR501 Human Sensor Module Pyroelectric Infrared
  • SainSmart HC-SR04 Ranging Detector Mod Distance Sensor
  • 5 180 ohm resistors
  • Breadboard and miscellaneous connectors

Source Code: https://github.com/chaddotson/PiPy

 

Posted by Chad Dotson in Featured, Hobbies, Neat Stuff, Raspberry Pi, 0 comments