Programming

Notes On Writing Testable JavaScript Vol 1

When writing JavaScript, I am a big fan of minimizing functionality and variables exposed publicly, which we all know to be good practice. However, this leads to anonymous functions and functions hidden within closures.  So….

How Do You Test That?

How exactly do you test private methods in JavaScript?  To answer that you should ask yourself, should I even be testing them independently or can I write tests for the exposed functionality and still achieve code coverage?  If the answer to that question is “yes,” write tests for the exposed functionality that inherently test the underlying private functions and stop there.  If the answer is “no, I really need to test this function.”  There are a few approaches.

Member Variables For Testing Only

This approach involves creating member variables intended for testing and testing alone.  This method relies on the build process to remove the variables before going to production.  While this process works, I believe it has a code smell to it.  You are polluting and bloating the code base with needless variables.  If you are interested in the approach, here is an article about it.

The Real Question: Should It Be There?

Is the fact that you are asking this question an indicator of a code design issue?  Perhaps the code is in violation of the Single Responsibility Principle?  I’ve recently experienced a little epiphany associated with this.  I realized that a collection of private functions that I was hiding actually belonged to a separate object as public functions.  This refactoring drastically reduced the code complexity, made it more maintainable, and enabled small, important functions to be separately tested.

 

 

 

 

 

Posted by Chad Dotson in Programming, 1 comment

Make It Easy

Building a successful product is usually complicated business.  With any luck a project will have an automated deployment process.  This however is only part of the equation.  Another significant part would be an automated build process.

Long Term Success

Long term success means making it easy for new people to get started in the weeks/months/years following a project’s startup.  Imagine the following project in two different scenarios.

The project is a large scale application with several dependencies.

Scenario 1 (No automated configuration and build process):

  1. Check out project from source control.
  2. Perform configuration needed for dependencies.
  3. Build / Install each dependency separately.
  4. Perform configuration needed for product build.
  5. Build product.

Scenario 2:

  1. Check out project from source control.
  2. Build product.

Which of those scenarios is more straight-forward and easiest to work with?  It’s pretty easy to see that scenario 2 is the best.

Memory and Documentation

In addition to helping new team members get started,  automated builds can serve as a form of long term memory.

“How do I do that?” becomes “press build.”

“How does that work?” becomes “check the build script.”

Posted by Chad Dotson in Key Concepts, Programming, Software Engineering, 1 comment

My Swift App – An Ongoing Experiment

Work is progressing on my first iOS app written in Swift.  I think that I might have a rudimentary alpha product ready to start testing in a few weeks.  Based on my experience with it so far, here are some of my thoughts, observations, and concerns.

  • Developing in Swift is as the name implies, “Swift.”  I didn’t know anything about Objective-C nor Swift before I started my app and I think I’m making decent progress given the amount if time I’ve had to work on it.  Given proper resources, I believe its possible to progress Swift apps from concept to production in a matter of weeks.
  • Language resources (documentation and examples) are still pretty sparse.  Get ready to learn a little Objective-C if you need help with API calls because that is where the majority of the help you will find will be.
  • The iOS 8 Simulator doesn’t save location privacy settings,  That means that every time you run an app that requires location privileges, you have to edit the settings again.  Based on what I’ve read, this issue has existed for some time in the beta code.
    This was due to user error.  You have to use either the location manager’s requestWhenInUseAuthorization or requestAlwaysAuthorization functions paired with the right entries in your projects Info.plist file.  The reason mine wasn’t working was I had erroneously edited the plist file associated with the unit tests.

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Use location when open?</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>Use location always?</string>
  • Perhaps the biggest issue is that Xcode cannot refactor Swift code.  To me this seems like a giant shortcoming of the editor.  Hopefully Apple will push an update soon to correct this.
  • While storyboards are powerful, some of the functionality is not so discoverable.  The auto-layout functionality took me awhile to find and not without searching the net.  I think they maybe onto something, but I do tend to like the way Visual Studio makes similar functionality “findable” from the properties panel.
  • As of Xcode 6.0.1 and iOS Simulator 8.0, AVSpeechSynthesizer doesn’t appear to work at all.
    var mySpeechSynthesizer:AVSpeechSynthesizer = AVSpeechSynthesizer()
    var myString:String = "This is a test."
    var mySpeechUtterance:AVSpeechUtterance = AVSpeechUtterance(string:myString)

    When executed in the iOS simulator, the code results in “Speech initialization error: 2147483665”.  I’ve seen a few work arounds on the net, but I don’t believe any of them actually work in Swift.

Posted by Chad Dotson in Programming, Software Engineering, 2 comments

Swift – A Quick First Impression

Swift and Xcode 6

Late last week Apple released Xcode 6 to the general public.  I’ve been waiting for the opportunity to try out Swift, so I started working on an idea I’ve had.

General Thoughts

This is probably a general iOS development comment, but the way you link items on the storyboard to class members seems odd to me (having done a lot of C# development in the past).  However, it does have its advantages.  Counter to the Microsoft environment, it does seem to encourage better design and discourage the worse of some bad habits.

Compared to Android

Its been awhile since I worked with Android, but when I did developing for the platform was disastrous.  Setup of the environment (Eclipse) and the emulator was time-consuming and not so straight-forward.  With Xcode, its all on rails.  You can have a “Hello World” app up in the simulator in 2 minutes.

Problems

The language does seem to be a little wordy at first glance maybe that opinion will get better as I get more experience with it.  While the official Apple documentation is now complete with Swift equivalents to Objective-C,  examples both official and third party are pretty few and far between it seems.

To be continued…

Posted by Chad Dotson in Programming, 0 comments

Comparing Node.js and Python on the Raspberry PI

Picture of my simple led circuit connected to the Pi.

Picture of my simple led circuit connected to the Pi.

Programming on the Raspberry Pi

Python seems to be the more popular language for writing programs on the Raspberry Pi.  However, it is far from the only language: Python, C, C++, Java, and Ruby are some that are automatically supported out of the box.  As it turns out Node.js is also supported.  Perhaps, just based on my preconceptions, I didn’t originally consider JavaScript when interfacing directly with hardware.  The goal of this article is to compare functionally equivalent sample programs written both in Python and JavaScript.

 

The Goal

I decided to make the scope of the problem created for this article as small as possible.  Given that the goal will be to create simple circuit diagram consisting of a LED and then to write a program that makes the LED flash for a specified period of time.

 

Simple LED circuit diagram

Simple LED circuit diagram

Hardware

With the Pi, a circuit that will make a LED flash is relatively simple: Consisting of just a LED and resistor.  I arbitrarily selected pin 7 on the Pi for this build.  I’ve included a diagram of it on this page.

 

Software

As the goal states, the following two implementations do nothing except toggle an LED at half the specified duration (0.5s) and automatically shutoff after 60 seconds.

 

Python

Since Python is the more traditional programming language for the Raspberry Pi, let us start with it.  The Rpi.GPIO module I used can be installed via pip.  Before you read the code sample, let me point out some things about the implementation.  Could it have been done simpler given that the problem was just to make the LED flash for a certain amount of time?  Yes, but I wanted to create something of an asynchronous process that could be controlled from outside its execution context.

import RPi.GPIO as GPIO

from threading import Event, Thread, Timer

class ImprovedThread(Thread):
    def __init__(self, *args, **kwargs):
        super(ImprovedThread, self).__init__(*args, **kwargs)
        self._stopEvent = Event()

    def stop(self):
        self._stopEvent.set()

    def is_stopped(self):
        return self._stopEvent.isSet()

    def wait(self, duration):
        self._stopEvent.wait(duration);


class LEDFlasher(ImprovedThread):
    def __init__(self, pin, duration):
        super(LEDFlasher, self).__init__(target=self._flashLED)
        self.setDaemon(True)

        self._pin = pin
        self._duration = duration
        self._state = False

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self._pin, GPIO.OUT)

        self.start()

    def _flashLED(self):
        while not self.is_stopped():
            GPIO.output(self._pin, self._state)
            self._state = not self._state
            self.wait(self._duration/2)

flasher = LEDFlasher(7, 0.5)
Timer(60, flasher.stop).start()

flasher.join()

GPIO.cleanup()

 

JavaScript

I used pi-gpio to interface with the GPIO on the Pi in JavaScript.  It can be installed via npm. It makes use of gpio-admin so that your script doesn’t have to run as sudo.  Follow the installation instructions provided here and it should get you setup.  Note that due to differences int the languages, it was not necessary to thread (web workers) the solution.

var gpio = require("pi-gpio");

function flashLED(pin, duration) {
    return setInterval(function() {
        gpio.open(pin, "output", function(err) {
            gpio.write(pin, 1, function() {
                setTimeout(function() {
                    gpio.write(pin, 0, function(err) {
                        gpio.close(pin);
                    });
                }, duration/2);
            });
        });
    }, duration);
}

var intervalID = flashLED(7, 500);

setTimeout(function() {
    clearInterval(intervalID);
}, 60000);

 

The Findings – I was surprised

When I started writing the JavaScript side of this article, I was mainly doing it to gain experience working with JavaScript on the Pi.  I did not expect to come out of it vastly preferring it over my python implementation.  I find the Python implementation above to be to wordy and overcomplicated.  It just seems that the amount of code needed to achieve the same results is excessive.  Perhaps this is because of the problem scope and implementation.  The problem posed here was a simple one, where a functional solution is superior to an object-oriented one.  Could the Python code above be rewritten into something a bit more functional? Sure!  Are there problems that an object-oriented Python or JavaScript implementation would be the better solution for?  Definitely.  The lesson to take away: be open to working outside your comfort zone and pick solutions to problems based on their fit for the problem not your comfort level with them.

I’ve created a copy of the code as a Gist that is available here: https://gist.github.com/chaddotson/570501a3e3dcfe8928c8

Posted by Chad Dotson in Key Concepts, Programming, Raspberry Pi, Software Engineering, 8 comments

Everyone’s A Coder

Question:

Are we headed to an era where everyone should know how to write at least some rudimentary code?

 

Learn to Code

Today, there are many sites on the internet offering to “teach you to code.” Two of which are KhanAcademy and CodeAcademy.  These sites offer a selection of topics that can be worked through in the span of a few hours.  Can it be done?  Sure.  Matter of fact, I think they are good resources to get you started.

Differentiating Computer Science

Computer science is more than just coding.  Wikipedia defines computer science as the following:

Computer science is the scientific and practical approach to computation and its applications. It is the systematic study of the feasibility, structure, expression, and mechanization of the methodical procedures (or algorithms) that underlie the acquisition, representation, processing, storage, communication of, and access to information, whether such information is encoded as bits in a computer memory or transcribed in genes and protein structures in a biological cell. A computer scientist specializes in the theory of computation and the design of computational systems.

Simply put, Computer Science is more than programming, though most computer scientists do write code.  On the topic of code, colleges don’t so much focus on languages as they do the theory, math, and algorithms.  This allows graduates to quickly assimilate new languages and ideas.

Does a product (or code) have to be perfect?

The answer is a pretty resounding “No,” but bad or inefficient design might harm long term viability.  In terms of a startup, I’d say a Software Engineer should become involved soon after completion of the MVP if not before.

Can everyone be a coder?

Yes!  I believe that in the future everyone should know how to write at least some code.  Right now, JavaScript and Python are the best candidates that could be learned by all.  With it leaning in JavaScript’s favor with Node.js.  Though, if you have serious aspirations to getting a career writing code, I suggest a formal degree.

 

Posted by Chad Dotson in Software Engineering, 0 comments

No Comments – A Failure Twice

Everyone that writes code has encountered or written their fair share of undocumented code.

A failure twice?

I was encouraged to write this article because of something I read about the pinball game that once was included with windows.  According to the article on MSDN, the pinball game was removed due to a bug that should have been fixable.  However, the overall qualify of the code made repair impossible and the game was removed from the distribution.  Two major items can be taken from this:

  • Failure 1: The could should have been self-documenting / few comments required.
  • Failure 2: Code not easily understood should have been commented.

Properly commented code can be tricky!

In college they push you to comment your code while not stressing that over documentation is also bad.  I remember writing programs that had comments on almost every line for assignments.  In the end it doesn’t buy you anything, it just restates the obvious and clutters the solution.  In the workplace, comments and whether or not the code needs them are hit and miss.

Some notes about comments:

  • Many comments are an acknowledgement of your failure to communicate.  Write better self-documenting code.
  • Outdated or wrong comments are worse than no comments.
  • Consider refactoring code that’s not self-documenting.  I find one of the biggest places this can be done is extracting methods from if statements.
  • Choose a good, descriptive names.  I’m a little wordy in my names, but in the end most of my code can almost read like a sentence.

Remember

The code is your best documentation.  Think about what you want to communicate with it and how to be as clear as possible.

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

Node.js vs Python vs PyPy – A Simple Performance Comparison

NQueensGraph

IMPORTANT NOTE: The NodeJS algorithm had a slight discrepancy in it.  See this article for a correction to the performance comparison section of this article.

The Algorithm

Yesterday, I decided to try translate my algorithm for calculating N-Queens to JavaScript.  I’ve implemented the same single-thread, brute force, recursive algorithm in many different languages with the biggest difference being the syntax of the language.  Once I completed the JavaScript Implementation, I ran the program with the latest version of Node.js.

The Findings

I knew Node was fast but it still surprised me.  As you can see by the included charts, the performance difference between Node.js and out-of-the-box Python is pretty significant.  Its not until the algorithms complexity and recursion depth hit certain limits that Node.js’s performance starts to falter.

Node.js and CPython – What’s The Difference?

You might ask what is behind this performance difference.  The answer is actually pretty simple.  It all boils down to how the code is being executed.  Node.js uses the V8 JavaScript Engine (Wikipedia | Google) written by Google and a part of the Chrome Browser.  V8 includes a just-in-time compiler that compiles the JavaScript to machine code before execution and then continuously optimizes the compiled code.  Python is a bytecode interpreter; meaning that the default interpreter (CPython) doesn’t execute Python scripts directly.  Instead, it first generates a intermediate file that will later be interpreted at runtime.

Ways To Get Better Performance

If you want to use Python, we can overcome the differences between Node.js and vanilla Python by using PyPy, an alternative implementation of Python that includes a just-in-time compiler.  For the algorithm I wrote, you can see a pretty good performance boost over Node.js when using PyPy.

Special Notes

  • I’ve placed my source on GitHub at the following url: https://github.com/chaddotson/puzzles
  • This is just with one type of algorithm, the best solution might and probably does change depending on what type of application you are researching.  For webserver performance, Node.js is slightly better than PyPy running Tornado.
  • This algorithm is a simple brute force algorithm, there are many faster and better ones out there.
  • At a board size of 15, Node.js could no longer run the algorithm due to its maximum recursion limit.
memory_usage
memory_usage_chart

Edit – A Follow-Up

The original focus of this article was shear performance, but I’ve received a question regarding the memory footprint of the 3 methods.  I think that is a very good and valid question.  So, I reran the tests to capture the peak memory utilization by each.  For this test I used “/usr/bin/time -l” to capture the maximum resident set size.  While this isn’t exactly the peak amount of memory utilized by the algorithm, it is sufficiently close to report on.

New Findings

Upon rerunning the tests for capturing memory utilization, I found that for the most part memory utilization contrasts performance.  A higher memory utilization isn’t really unexpected, if you think about it.  Essentially, the jit is sacrificing memory for performance.  In most cases, this isn’t really that bad.  Using a jit is just a cheap way of boosting performance of code written in an interpreted language.  The boost in performance, speed of which it was written and the maintainability of it outweigh memory utilization concerns in many cases.

The Oddity

As you can see, I’ve included a chart covering all the solutions for boards 8×8 to 14×14.  During most increments in board size, the memory utilization seems to increase exponentially; however, when we hit the 14×14 board size we see all the cases level off at relatively the same memory utilization of around 300 MB.  At this time, I really don’t have a good answer for this.  I could certainly speculate, but I’d rather not until I know more.

 

Posted by Chad Dotson in Programming, Software Engineering, Technology, 28 comments