How to Interview a Company as a Candidate

September 28th, 2013
Recently a friend asked me what I look for when considering a new job.

When I interview for a new software engineering job, I’m usually participating in two interviews at once. The company is interviewing me, and I am interviewing the company. Both interviews are equally important to me.

Sometimes I am nervous about appearing over confident in interviews, but getting answers to the questions I enumerate below is very important to me. Getting a job offer feels great, but how will it feel 6 weeks from now when you realize this new job isn’t a good fit for you after all?

Questions I ask the software engineers

Most interviewers will ask if you have any questions, usually toward the end of the interview. For professional courtesy, I make it clear at the beginning of the interview that I’ll have several questions to ask. Often, the interviewer prefers to answer these at the beginning, and I prefer that too, because it helps me give better responses when it’s my turn to answer questions.

1. How do you know what to work on each day?

The purpose of this question is to identify dysfunction. I want to get answers from 2 or 3 engineers at least. If a company says they follow a certain development process, but the engineers don’t talk about the process, that’s a sign of dysfunction. If you get different answers from different engineers, that’s another sign of dysfunction.

In a high quality team, I get consistent answers to this question. Every developer knows the process, and the process is light weight enough to be supportive of the engineers rather than oppressive to them.

Example of a good answer (there are many others): “We do two-week sprints wherein each engineer commits to a set of features and bug fixes to deliver. Each day we report progress on our commitments to each other. We have an amazing product manager who interfaces with customers to prioritize the features and bug fixes.”

Example of a bad answer (there are many others): “I come into the office in the morning and resume working on the previous day’s tasks. Most days, I get interrupted with an emergency. I work on whatever is most important each day.”

2. What do you use for revision control?

Good tooling is a strong indicator of a good team. If a team is using a 10-year old revision control system, they are probably using a bunch of other outdated tools. Furthermore, they probably don’t value efficiency gains that can be achieved by good tooling.

Here are the kinds of answers I get to this question:

No revision control I almost never hear this answer, but if you do, run away from the job.

CVS, RCS, Visual Source Safe Old, outdated tools. This team probably has serious problems.

Subversion Not as bad as CVS, but the team has not seen the light of modern revision control systems.

Git, Mercurial, Darcs, Bit Keeper, Bazaar. Any of these is a satisfactory answer for me.

3. What do you like about working here?

Strong answer: I get a lot of satisfaction from the work I do.
Strong answer: We have a lot of fun at work.
Strong answer: I love working with really smart co-workers.
Strong answer: Management really respects engineering.

The more good answers the better. I don’t have to get all these answers, and some people are not naturally “gushy”, so this one can be a tough call.

If I hear these kinds of answers, and very few from the strong answer list, I get nervous:

Weak answer: It’s a steady job.
Weak answer: I don’t have to work very hard.
Weak answer: There is not a lot of pressure to deliver.
Weak answer: (silence)

I don’t automatically consider it a bad company if I hear those weak answers, but if those are the only answers, I definitely look elsewhere.

4. Do you write unit tests?

If a team gets excited when I ask about unit testing, that is a very good sign. If they come up with excuses for why they don’t write tests, especially bad excuses (we don’t have time), that is a very bad sign for me.

If the engineers tell me they write unit tests, and they are able to tell me metrics about their tests, such as how long they take to run, how many they have, and about their code coverage metrics, that is very attractive to me.

If I get the sense that I will be working in a large, old, untested codebase at this company, I am very unlikely to work with them.

I give bonus points for doing test driven development, but I penalize for dogma. If the engineers tell me that they usually write tests first, but they aren’t religious about it, that’s a good sign to me. This tells me they value testing, but they realize that every rule has an exception, and they are pragmatic about it. Teams who choose a methodology such as TDD but don’t tailor it to their team are generally more dogmatic than I like. However, teams who throw out ideas like TDD without ever trying them are equally dogmatic in my view. This is doubly true if they make unsubstantiated assertions about unit testing without having evidence to back them up.

Several follow-on questions I ask to get a feel for their testing culture:

  • How many integration tests do you have vs. unit tests? (do they even know the difference)
  • Do you have acceptance tests
  • What testing framework(s) do you use?

5. Do you have continuous integration?

The best software development teams I know use tools like Jenkins, Travis, and Buildbot. If the team has no continuous integration, I try to gauge whether they are familiar with the concept at all. If they aren’t, this is a bad sign in my experience. Having a continuous integration system means that the team probably believes in automation, which is usually a very good sign in my experience.

6. What do you measure?

This is an open-ended question meant to find out if the team has put effort into measuring aspects of their software. For web development teams, the answers tend to focus on performance metrics like server response times, request throughput, and client-side responsiveness. But the discussion can go to things like number of users who speak different languages, browser breakdown, cache hit/miss rates, and a myriad of other topics. If the team hasn’t taken the time to measure any of these things, it can be an indicator that they don’t use real data to inform their decisions. They may be premature optimizers. I value a team that uses real, measured data to make decisions, especially about performance, but it applies to so many things.

Other sub-topics to which this question can lead:

  • How long do your builds take? Are you making them faster?
  • How long do your unit tests take to run?
  • About how many lines of code do you have? (this isn’t a terribly useful number, but I like teams who know data about their code)
  • How many bugs do you have in your bug tracker?
  • How long do your bugs take to fix (min/max/typical)?

If the interviewer even knows answers to many of these questions, it’s a good sign that the team is high quality. If they have no idea why they would even care about any of these measurements, it could be a negative indicator.

7. How do you find and fix bugs?

A strong team usually has dedicated testers. A really strong team has impressive test automation. Some teams are too small for either of these things, but that doesn’t necessarily mean they are a bad team. When I ask this question, I’m trying to get a feel for their process. Is their hair always on fire because bugs come flying in? Do they have a sane process for finding bugs? Do they rely on users to find bugs, or do they try to ship bug-free software (as much as is possible anyway)?

This usually leads to these sub-topics:

  • How do you prioritize your bugs?
  • What bug tracker do you use? (and what do you hate about it)
  • What bug trackers have you used in the past? (and what do you hate about them)
  • Do you use Excel to track bugs? (nooo)

8. What collaboration tools do you use?

In my experience, high functioning teams use lots of collaboration tools. They often use chat services (IRC, HipChat, Jabber), code review services (Gerrit), and of course, the venerable-but-showing-its-age Email. I am looking for indicators that each developer knows what the other developers are doing. I’m not looking for insane levels of detail, but more for a general awareness. Also, I like to see cool integrations with collaboration tools. The simplest example is an automatic email sent any time there’s an automated build failure. Another example for web-dev teams is automated error logging services that notify the team’s chat room when serious errors occur, or when key metrics cross a certain threshold. Collaboration integrations are usually pretty easy to set up, and a team who has taken the time to do so shows promising vision.

9. What frameworks do you use?

I like to hear that teams are using the latest and greatest frameworks in their development. If they are building a UI using Motif, I usually am not interested. I am especially happy to see that teams have made contributions to open source projects that they use. Also, if the team is reinventing the wheel rather than using readily available tools to help them build their product, I get nervous.

10. When can we pair?

I’ve never actually done this, but my friend has. I think it’s a fantastic idea. If you want to learn almost anything about the team, go work with them for a half day. It might require you to sign an NDA. If the team is even willing to consider this idea, I think it’s a very good sign.

Questions I ask managers

1. When was the last time you wrote code?

I like managers with a strong technical background. No offense to my MBA friends, but I’ve found the managers I really like are those who have done what I do.

2. How did you become a manager?

I like managers who chose to become a manager because they truly enjoy it and have a knack for it, rather than being forced into it. I also like it when managers seem to be focused on serving their team. My favorite managers are those who focus on making life better for their team, rather than “managing up”. They see themselves as a helper and protector for their team.

3. How do your engineers know what to work on each day?

Since I ask the engineers this same question, I like to compare the manager’s answer to see if they match. If they don’t match, it can mean there’s dysfunction. The worst kind of dysfunction is unrecognized dysfunction. I believe it’s the manager’s job to identify disparity like this and fix it.

4. What is your team’s biggest challenge right now?

They usually answer that it’s a shortage of staff. Because this is a common and obvious answer (they are hiring after all), I like to ask for their second biggest challenge. I’m looking for red flags like slipping schedules, product quality problems, and interpersonal drama. You’ll know the red flags when you see them. Every team has problems, so the answers you get will depend on several factors:

  • The manager’s awareness of problems
  • The manager’s willingness to be honest with you
  • The seriousness of the problems on the team

5. How do you measure your team members’ individual performance?

A clueful manager will have a good technique for doing this. The best managers will carefully gather feedback from the whole team when assessing an individual team member’s performance. A bad manager will simply make a call based on their own observations, without consulting the team.

6. Do you do annual performance reviews?

I like to work for managers who value giving feedback and helping their team members improve.

7. Do you do annual salary increases?

I like to know that my compensation will be adjusted to match my contribution to the company, and that we’ll take an official look at it at least once a year. For companies where it applies, I like to ask about equity. Will you give me stock options? Will you give me more stock options every year?

Questions I ask company leadership

I don’t always get to talk to the company’s senior leadership, especially for larger companies, but when I do, I take it as an opportunity to assess the company’s financial viability. I’m not really qualified to do this, but there are some obvious problems that I can sometimes discover in an interview. Also, I like to know what the top-down culture is like, because this information can tell me how the company values its engineers, both positively and negatively.

1. How are you funded?

I’m trying to gain insight into the money behind the company. If they are funded by venture capital, private equity, public stock, or self funded via revenue, I want to know it. Often I can figure this out before the interview pretty easily, but company leadership will often add insights that I can’t find via Google.

2. Are you profitable?

If profitable, great! If not profitable, what’s your plan for becoming profitable? Some startups have a plan for this, while others are looking for an exit via acquisition or IPO. Whatever the case, I want to know. Sub-topics that can come from this question:

  • Historical revenue for the past few quarters/years
  • Risks to profitability like competition, surprise expenses, and surprise revenue shortfalls

3. What is your opinion on outsourcing?

I want to know if the job I’m applying for is likely to get outsourced in the future, or if the job could turn into a position managing outsourced engineers.

4. Tell me about the company culture.

This is another question I use to reconcile the engineers’ perspective against leadership’s perspective. I’m looking for discrepancies as a sign of dysfunction, and I see consistency as a sign of, well, consistency. I want to know if senior leadership is out of touch with the in-the-trenches employees. I also want to see if the leadership has solid vision that is well communicated. My favorite companies to work for have a strong, shared vision.

5. What assurance do you have that this company will be successful?

With this question I’m looking for real evidence, not just marketing hype. If senior leadership gives me actual numbers, like revenue, market size, and capitalization, that is a good sign. Also, if I can verify this information from other sources, that is an even better sign. On the other hand, the numbers may indicate something very bad, like a one-month runway with no funding on the horizon.

6. Tell me about your reporting structure.

For me, the best answer to this question is a simple one. If the person can draw a simple org chart that explains the reporting structure, I am satisfied. If they start talking about a matrix, I get nervous.

Conclusion

Interviews are bidirectional. Make sure you get everything out of the experience you need to know to make an informed decision if you are fortunate enough to get an offer. Good luck!

Communication Between Directives in AngularJS

December 17th, 2012

Warning: This article is long and thorough. If you’re in a hurry, you can skip straight to the final product here:

http://plnkr.co/edit/6KxHY8ZpE83Z2PeNWlYi?p=preview

Prerequisites to this article

Before reading this, get to know these AngularJS terms. You don’t need too much depth, but you need to know what they are:

You should also peruse the Angular Developer Guide, but don’t feel bad if a lot of the jargon does not make much sense at first.

Step 0: Roadmap

We’re going to create two custom directives that communicate with each other. We’ll really dig deep into the first directive, explaining every line of code as we go.

Then we’ll glue the directive to a controller via a scope object.

Lastly, we’ll create a second directive and glue it all together.

Step 1: A basic directive, dissected

For this example, we’ll create a custom search box that can be placed in our app with a custom <my-search-box> element. This directive causes Angular to convert <my-search-box> in your HTML into <span>My Custom Search Box</span>. This is not useful yet, but it will become immensely useful as we grow this concept in a few paragraphs.

We’ll create a file called “app.js” with this content:

angular.module("MyApp", []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      replace: true,
      template: '<span>My Custom Search Box</span>'
    };
  });

Let’s walk through each line of that directive:

angular.module("MyApp", []).

This line declares a new module called “MyApp”. The empty array to the right can contain the names of other modules on which this module depends (this is where you would put AngularUI modules for example if you want to use AngularUI). In this case, this module happens to be our “main” application module, but Angular really doesn’t know that from this line of code. That happens in the HTML with <html ng-app="MyApp">. Also, you only declare your main application module once, even if you have many directives. There are ways to look up your module if your code spans multiple files, or you can just create a global variable to reference your module and use that when building your directive.

  directive('mySearchBox', function() {

Here we are declaring a new directive. Notice that we camel case the directive name. When Angular encounters <my-search-box> in the HTML, it will normalize that into “mySearchBox” to look up the directive. Thus, “mySearchBox” is called the “normalized” name.

    return {

Angular expects the directive function to return an object with properties that describe the directive.

      restrict: 'E',

This tells Angular that “my-search-box” must be an element. Angular directives can also exist as HTML attributes, HTML class names, and even HTML comments (!). It’s okay if this doesn’t make sense yet.

      replace: true,

This tells Angular to fully replace <my-search-box> with the directive’s template HTML. Alternatively, Angular can add the directive’s template HTML to the <my-search-box> element as a child element. For our example, we want Angular to fully replace <my-search-box> because <my-search-box> is not a valid HTML element name. You can imagine wanting Angular to simply augment an element with child elements in some scenarios, but not this example. We’re effectively creating a “widget” that can be instantiated and reused in our HTML.

      template: '<span>My Custom Search Box</span>'

This is the directive’s HTML template that will be rendered by the browser. I don’t recommend using hard-coded template strings in your directives like I’ve done here. I do it this way to make the example clear. Normally, I use the templateUrl property and serve the HTML as a “partial” from my web server. Angular caches these partials, and you can even pre-load them when your app loads. This way, I can use server-side template technologies for things like localization. Although, for the best performance, I recommend that you serve these partials statically from a CDN or other fast caching service.

Now we can use this directive in our HTML like this:

<html ng-app="MyApp">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body> 
      <my-search-box></my-search-box>
  </body>
</html>

When you visit that page in your browser, you’ll see “My Custom Search Box” if all went well above.

So far this is a pretty useless directive, but we’are about to take it to the next level.

Step 2: Giving your directive its own scope

Each instance of a directive has its own scope. And of course, the scope is a child of the enclosing scope where you instantiated the directive in the HTML. For example, if your directive exists inside a <div ng-controller="MyController">, then your directive’s scope will be a child of MyController‘s $scope.

For example, the following HTML uses two <my-search-box> elements. Angular gives each <my-search-box> its own independent scope:

  <body> 
      <my-search-box></my-search-box>
      <my-search-box></my-search-box>
  </body>

Let’s define our directive’s interface to the outside world using the scope property. Our interface will have two values: searchText and isSearching. We will use searchText to store the user’s search text that they enter into an <input> box, and we’ll use isSearching to tell the directive when a search is in progress.

angular.module("MyApp", []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        searchText: '=',
        isSearching: '='
      },
      template: '<span>My Custom Search Box</span>'
    };
  });

Did you see the scope = {...} property above? That defines the public elements of this directive’s scope. Notice how we used '='? That tells Angular that we want a scope variable to have two way binding to the outside world. This is part of the directive’s HTML interface. This allows callers to use our directive like this:

<my-search-box
  search-text="someScopeVariable"
  is-searching="someOtherScopeVariable">
</my-search-box>

In other words, the directive allows outside callers to bind their own scope variables to this directive’s searchText and isSearching variables. This is how you communicate with the directive from the outside world.

The variables someScopeVariable and someOtherScopeVariable come from the enclosing scope, which usually is managed by a controller outside the directive. If, for example, we had <div ng-controller="MyController"> enclosing <my-search-box>, then someScopeVariable and someOtherScopeVariable would be managed by MyController.

In the code above, the search-text gets normalized into searchText in the directive’s scope. Likewise, is-searching becomes isSearching.

When we assign search-text="someScopeVariable", we are telling Angular to bind this directive’s searchText scope variable to a scope variable from the enclosing scope called someScopeVariable. Any time the enclosing scope’s someScopeVariable changes, the directive’s scope variable searchText will also change. And it works in the other direction too. Any time the directive changes its searchText variable, Angular will automatically change the enclosing scope’s someScopeVariable to match.

These scope variables are useless unless we also make them visible somehow, so let’s modify our template HTML to use them. While we’re at it, let’s make this actually look like a search box instead of a simple piece of text:

angular.module("MyApp", []).
  directive('mySearchBox', function() {
    return {
      restrict: 'E',
      scope: {
        searchText: '=',
        isSearching: '='
      },
      controller: function($scope) {
        $scope.localSearchText = '';
        $scope.clearSearch = function() {
          $scope.searchText = "";
          $scope.localSearchText = "";
        };
        $scope.doSearch = function() {
          $scope.searchText = $scope.localSearchText;
        };
      },
      replace: true,
      template:
      '<form>' +
        '<div>' +
          '<input ng-model="localSearchText" type="text" />' +
        '</div>' +
        '<div>' +
          '<button ng-click="clearSearch()" class="btn btn-small">Clear</button>' +
          '<button ng-click="doSearch()"    class="btn btn-small">Search</button>' +
        '</div> ' +
        '<div ng-show="isSearching">' +
          '<img ng-show="isSearching" src="http://loadinggif.com/images/image-selection/3.gif" /> ' +
          'Searching...' +
        '</div>' +
      '</form>'
    };
  })

Remember, I suggest you use templateUrl instead of template when your HTML starts to grow like this.

Now we have a search box form that lets the user enter some search terms, which we store in the directive’s scope as localSearchText. Notice that we didn’t put localSearchText in the scope: {…} definition, because it needs no external binding. In other words, this is a “private” scope variable that the directive uses to store the human text input until we are ready to actually do the search. This is because we don’t want every single keystroke to initiate a search. Only when the user clicks the “Search” button.

Notice also that we added a controller with controller: function($scope) {...}. This code defines a typical controller so our directive can take action in response to user input, like button clicks with ng-click.

This HTML also provides a “Clear” button to zero out the search box and a spinner to show when the search is in progress. The directive relies on outside callers to tell it when a search is in progress by setting the isSearching variable to a “truthy” value.

After making these changes to app.js, our page should look like this:

Now that directive is finished. Notice it doesn’t do much. It requires an outsider to stimulate it into action.

Step 3: Creating a Controller

Let’s create a controller that communicates with the directive we wrote. This isn’t strictly required to allow two directives to communicate, but in most cases it will be necessary because someone has to glue them together with the business logic specific to your application. This is a job well suited to an Angular controller.

Let’s make a simulated city search that allows the user to search for cities. Because it’s an example, the search will always return the same results.

<div ng-controller="CitySearchController">
  <h1>Search for Cities</h1> 
  <my-search-box search-text="citySearchText" is-searching="isSearchingForCities"></my-search-box>
</div>

And the accompanying controller, which I placed in app.js:

function CitySearchController($scope, $timeout) {
  $scope.$watch("citySearchText", function(citySearchText) {
    $scope.citySearchResults = [];
    if (citySearchText) {
      $scope.isSearchingForCities = true;
      $timeout(function() {
        // simulated search that always gives the same results
        $scope.isSearchingForCities = false;
        $scope.citySearchResults = ['New York', 'London', 'Paris', 'Moab'];
      }, 1000);
    } else {
      $scope.isSearchingForCities = false;
    }
  });
}

This controller’s $scope.citySearchText and $scope.isSearchingForCities variables are bound to the directive’s scope variables searchText and isSearching because of the HTML attributes that we specified on <my-search-box>.

This controller is pretty basic, so I won’t describe every line of code. All it does is $watch() for changes to citySearchText and get some fake search results with Angular’s $timeout service.

Because of Angular’s excellent isolation-centric design, this controller would be very easy to write unit tests for, but that’s another article.

When you visit the page, you should now see a search box. If you enter some text into the input box and click “Search”, you’ll see a spinner for 1 second, which then disappears:

Step 4: Finally add a second directive

Now we’re ready to add another directive. For this example, we’ll create a search results directive. This directive has almost the same public interface (i.e., scope) as the <my-search-box> directive, with one extra variable: the actual search results that caller wants to display.

It looks like this:

 directive('mySearchResults', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {
        isSearching: '=',
        searchResults: '=',
        searchText: '='
      },
      replace: true,
      template:
        '<div ng-hide="isSearching">' +
          '<h4 ng-show="searchResults">Found {{searchResults.length}} Search Results For "{{searchText}}":</h4>' +
          '<ul ng-show="searchResults">' +
            '<li ng-repeat="searchResult in searchResults">' +
              '{{searchResult}}' +
            '</li>' +
          '</ul>' +
        '</div>'
    };
  });

Everything should look familiar from your study of the first directive. There are no new concepts here. Let’s use our directive in our HTML:

  <div ng-controller="CitySearchController" style="margin: 20px">
      <h1>Search for Cities</h1> 
      <my-search-box search-text="citySearchText" is-searching="isSearchingForCities"></my-search-box>
      <my-search-results is-searching="isSearchingForCities" search-results="citySearchResults" search-text="citySearchText"></my-search-results>
    </div>

Now your page should show some search results after clicking the “Search” button and waiting for 1 second:

Just to prove that there is indeed zero coupling between the two directives and the controller, I added a second controller and a second instance of each directive to search for fruits, which you can see in the plunk below.

The Finished Product

Here it is: http://plnkr.co/edit/6KxHY8ZpE83Z2PeNWlYi?p=preview

Conclusion

From the sheer length of this article, you may think that this is complicated, but the reality is that it only took me about 30 minutes to whip together the working example in the plunk.

Main points I hope you took from this article:

  • Directives are easy to create.
  • Directives have their own scope
  • Directives can communicate with the outside world via HTML attributes
  • Directives encourage loose coupling
  • Directives encourage reuse and UI consistency
  • Directives are easy to test (well, this is a future article)
  • Controllers can use directives with zero coupling
  • The Prime Directive has nothing to do with AngularJS (bummer)

AngularJS is too humble to say you’re doing it wrong

December 2nd, 2012

For years, web application developers have used DOM manipulation tools like jQuery to control their user interface. Astute developers have taken it to the next level with client-side templating tools like Mustache and Handlebars.js to build sophisticated user interfaces on the client side.

And then AngularJS came along.

And we all realized we’ve been doing it wrong.

Way wrong.

The Old Way

Remember before you discovered AngularJS? Back when your code was organized like this:

  1. HTML that defines your page
  2. JavaScript that downloads AJAX data
  3. HTML that defines a client side template
    (yeah, this: <script type="text/html">...</script>)
  4. JavaScript that renders the client-side template
  5. JavaScript that injects the rendered template HTML into the DOM

You thought that was pretty cool. “Hey look,” you said, “I’ve off-loaded template rendering to the browser!”. Yeah, you were pretty cool.

But then AngularJS showed you how you were wrong. You could accomplish the same client-side magic with a lot less code.

The New Way

Under AngularJS, your code can be organized like this:

  1. HTML that defines your page and client-side templates inline
  2. JavaScript that downloads AJAX data

How does that even work? I mean, you’ve got like less than half of the bullet points now.

The answer: Data Binding.

Data Binding is the secret sauce of AngularJS (along with a couple dozen other delicious spices and condiments). Oh, and it’s not a secret at all. The code is actually pretty easy to read, despite being pure magic awesomeness on environmentally-friendly steroids.

Shall We Do Show-and-Tell?

The old way

This should be very familiar. You’ve got an HTML page, and you want to add some dynamic content with a client-side template:

Here’s the page HTML:

<html>
  <body>
    <div id="my-list-of-animals">
    </div>
  </body>
</html>

Let’s use Handlebars for the client-side template:

<script id="animal-template" type="text/x-handlebars-template">
  <div>
    <div>{{animalName}}</div>
    <div>{{favoriteFood}}</div>
  </div>
</script>

And you need some JavaScript to download the AJAX data, render the client side template, and inject it into the DOM:

$.get("/api/animals/", function(response) {
  var source = $("#animal-template").html();
  var template = Handlebars.compile(source);
  $.each(response, function() {
    var html = template(this);
    $("#my-list-of-animals").append(html);
  });
});

Put all that together somehow, and wow, that’s a lot of code to do something that should be very simple.

That covers all 5 bullet points above. You’re still cool, right?

The AngularJS Way

Remember how there are only two bullet points. Well, here they are:

First, your page HTML:

<html ng-app>
  <body>
    <div ng-controller="MyAnimalController">
      <div ng-repeat="animal in animals">
        <div>{{animal.animalName}}</div>
        <div>{{animal.favoriteFood}}</div>
      </div>
    </div>
  </body>
</html>

Did you see that? There’s no <script> hack. The template is right inside the page! Right there. In-line. Right where you wanted it all along, but never had the guts to ask. But I digress.

Second, the JavaScript:

function MyAnimalController($scope, $http) {
  $http.get("/api/animals/").success(function(response) {
    $scope.animals = response;
  });
}

And that’s it. It really is glorious. The AngularJS team really distilled the client-side template problem to its essence and produced an elegant solution. But don’t take my word for it. Check out the win list below.

Win List

Look at all the prizes you won by using AngularJS:

  1. CSS classes are just for CSS now.
    You used to abuse the HTML class attribute so you could find elements in the DOM with jQuery. Now, your class attributes are only for CSS. You don’t have to wonder anymore whether a particular class is used by JavaScript or CSS. The answer is always CSS: The way nature intended
  2. No <script> hacks.
    You don’t have to trick the browser into ignoring your client-side templates anymore. Don’t you feel cleaner?
  3. Client side templates are cohesive with your page
    You used to have a pile of client-side template files scattered throughout your project, or all crammed into your HTML <head>. Now they are right in the page, exactly where you wanted to read them in the first place.
  4. You don’t have to name every template
    You used to name each <script> element with an “id” attribute to make it findable by jQuery. You can nuke those strings in your JavaScript and HTML, and not worry about them getting out-of-sync.
  5. You have control over the scope of your JavaScript
    Previously you had to worry about your jQuery selectors casting too wide a net and selecting elements beyond what you intended. For example, suppose there happened to be an element in the page somewhere with class “animal”, and you didn’t know about it. Then you wrote a jQuery selector like $(“.animal”). Boom, you just mofidied an element you didn’t intend to. With AngularJS, your JavaScript cannot reach outside the ng-controller demarkation.
  6. You don’t have to remember to clean up HTML on refresh
    Let’s say I want to refresh the animal list in this example. Under jQuery, I have to remember to do this: $("#my-list-of-animals").html("") before I start .append()ing new animals. In AngularJS, I just replace $scope.animals with the newly downloaded list, and it automatically clears out the old HTML.
  7. Your JavaScript is cleaner
    Your JavaScript has no CSS selectors anymore. It used to be littered with strings to locate elemenents in the DOM. Now it’s just got business logic. Pure, sweet business logic.
  8. You can unit test your JavaScript without a DOM
    I should have mentioned this first. Notice how my JavaScript has no knowledge of a DOM? It doesn’t even know there’s HTML involved at all. This makes it much easier to unit test, because you don’t need to load a big chunk of fixture HTML to test your JavaScript. AngularJS provides some great docs on testing too.

Almost Too Humble

I started reading about AngularJS and re-working parts of my projects to use it in earnest only a few weeks ago. A day into the effort, the light bulb went on for me:

I’ve been doing this all wrong

At that point, I started to wonder why the AngularJS team didn’t write article after article with the same title: “You’re Doing It Wrong”. And that’s what inspired me to write this.

So there you have it. An opinionated blog post about an opinionated framework.

Temporarily Suppress Console Output in Python

October 25th, 2012

Have you ever wanted to temporarily suppress console output in Python? But you really want it to be temporary, even if an exception happens. Maybe you are calling into some idiot’s library who spams your console. Yeah, that’s happened to me before (maybe I was the idiot–I’m not tellin’).

Here’s a handy way to suppress stdout temporarily in your program:

First, slap this code into your project:

Use it like this:

Compiler vs. Interpreter

October 18th, 2012

What’s the difference between writing a compiler and writing an interpreter?

Easy:

Writing an interpreter is like reading an instruction manual and performing the steps.

Writing a compiler is like reading an English instruction manual, translating it into German, and handing it to a German person to execute the steps.

Throttling Your Network Connection on Mac OS X

April 11th, 2012

Sometimes you just need to sloooooow doooooooown to test how your software behaves when your internet connection is crappy.

Linux has tc to do this, but what about Mac OS X?

That’s where ipfw comes in. It does a lot of stuff. I mean a lot, but we’re just going to use it to slow down our internet connection today.

Here’s an example that throttles your web browsing experience to 50 KBytes/second:

sudo ipfw pipe 1 config bw 50KByte/s >/dev/null
sudo ipfw add 1 pipe 1 src-port 80
sudo ipfw add 1 pipe 1 dst-port 80

And to turn it off (this is an important step!):

sudo ipfw delete 1

To make this super easy to use, I wrote a handy little shell script called network-throttle, which you can put in your PATH and run like this:

network-throttle on --port 80 --rate 50KByte/s

And to turn it off:

network-throttle off

You can download the shell script below. Put it in your PATH and name it network-throttle.

Or, if you like things shiny, pointy, and clicky, you can use the Apple Network Link Conditioner by installing X-Code.

Here’s the magical shell script:

#!/bin/bash
#
# Throttles your Mac OS X internet connection on one port.
# Handy for testing

set -e

RATE=15KByte/s
PORT=80
PIPE_NUMBER=1
ACTION=

function usage()
{
    echo $1
    echo
    echo "Usage: `basename "$0"` <action> [options]"
    echo "  Action:"
    echo "     on"
    echo "     off"
    echo
    echo "  Options:"
    echo "  --rate <rate>"
    echo "      Example: --rate 100KByte/s"
    echo "  --port <port> (default is 80 if you don't specify --port)"
    echo "      Example: --port 80"
    exit 1
}

function turn_throttling_off()
{
    echo "Turning off network throttling"
    sudo ipfw delete $PIPE_NUMBER || echo "Is it already turned off?"
}

function turn_throttling_on()
{
    echo "Throttling traffic to port $PORT: $RATE"
    sudo ipfw pipe $PIPE_NUMBER config bw $RATE >/dev/null
    sudo ipfw add $PIPE_NUMBER pipe $PIPE_NUMBER src-port $PORT >/dev/null
    sudo ipfw add $PIPE_NUMBER pipe $PIPE_NUMBER dst-port $PORT >/dev/null
}

# Grab command line args:
while [ -n "$1" ]; do
  case $1 in
    --rate)
      shift
      RATE=$1
      ;;
    --port)
      shift
      PORT=$1
      ;;
    *)
      ACTION=$1
  esac
  shift
done

[ -n "$ACTION" ] || usage "Error: no action specified"

case $ACTION in
  on)
    turn_throttling_off >/dev/null 2>&1 # in case it's already on, clear out the old one
    turn_throttling_on
    ;;
  off)
    turn_throttling_off
    ;;
  *)
    usage "Error: Bad action specified"
    ;;
esac

Dangerous Python Default Arguments

April 1st, 2012

Dangerous? Really? Well, not if you understand how it works.

Note: I’m not the first to write about this subject.

When writing a function in Python, it’s handy to use default argument values like this:

And you think this will provide an easy way to let lazy callers pass no arguments to your function, and it will simply be called as if they had passed ['some item'].

But you would be wrong.

What actually happens is this (interactive shell output):

That’s right. Python creates a new object, named some_list that persists as an attribute of the function. If callers don’t pass their own some_list object, this one, the same one, is used each time your function is called.

Weird, huh?

If users pass their own some_list object, then sanity is restored:

So why is this? Python stores each default argument value in a special attribute on the function called func_defaults. You can inspect any function’s default arguments like this:

Because functions in Python are just objects, you can store arbitrary attributes on them. And indeed, you can actually modify the default function arguments at run time, like this:

But remember: Just because you can doesn’t mean you should. I would not recommend making a habit of stuff like this, especially if you like not having your co-workers hate you.

It’s always good to know how your tools work. Inside and out.

I discovered this behavior when investigating the pylint W0102 message, and discovered that this message actually inspired an entire wiki of Pylint message descriptions.

The Code Quality Continuum

March 5th, 2012

What does it take to write high quality code?

Here’s a little table that I use to judge my own code quality:

Code Quality Continuum Chart

Future axes to add:

  1. Ratio of the initial development cost to the long term maintenance cost
  2. Code testability: Code can be manually tested, code can be tested with automation, code can be tested via continuous integration

iPhone + Microscope = Awesome

January 3rd, 2012

I was trying to repair my TV, and I wasn’t happy with the crummy iPhone camera resolution of this chip:

So I took the part to work, put it under the microscope, lined up the iPhone camera with the eye piece, and voila!

I put my left index finger in the frame for size reference.

Note: in the second photo, the chip has been removed. :)

Book Review: Treading on Python

December 28th, 2011

Treading on Python by Matt Harrison provides a basic introduction to the Python programming language for programming novices.

Background of the reviewer

I have been writing code professionally for 10 years. I’ve spent most of my time in C++, but I’ve written a handful of small Python scripts (less than 100 lines) and a couple medium-sized Python applications (hundreds of lines with multi-threading).

In Treading on Python, I was looking to shore up my Python foundation before jumping into my first big Python project.

I was not disappointed.

Who is this book for?

If you are interested in learning how to write computer programs as a beginner, this book is probably a pretty good place to start. The book starts by persuading you to choose Python as your first programming language for two main reasons:

  1. Python is used widely in industry
  2. Python is easy to learn

This book is written primarily for brand new programmers. It provides practical advice for getting started at the very early stages of programming:

  • How to edit Python code
  • How to run Python programs
  • How to use the Python interactive shell
  • What a variable is (complete with cattle analogy)
  • How to use strings, integers, and lists

However, even if you have, like me, written some small to medium sized Python programs, you will still probably benefit from the following useful information:

  • Python’s handy dir and help functions
  • The enumerate() function
  • The dictinoary setdefault() method
  • Python’s concept of None and object id
  • List slicing
  • import and from...import semantics
  • And a surprisingly good list of pitfalls to avoid

Early in the book, Matt spends a lot of time explaining basic programming concepts (like variables). He does this by providing real world analogies (like cattle) that will probably seem superfluous to the experienced programmer, but that may be beneficial to the programming novice. I was tempted to skip the first few chapters but I’m glad I read them competely. The book is peppered with little gems that reveal what writing Python code is all about, and even the most basic topics still provide these insights.

Who is this book not for?

If you are looking for a book that delves deep into Python, this is not the book for you. Notably absent concepts from this book include:

I don’t offer this list as a criticism of the book. The book’s stated purpose is clearly not to provide a comprehensive Python treatise for the experienced programmer. But if you are considering this book as a way to delve into any of these concepts, this is not the book for you.

Opinion of the book

Matt clearly knows his Python. He has peppered the book with helpful tips that compelled me to whip out my Python interpreter to experiment. Many of the tips were very handy, even for a semi-experienced Python programmer such as myself.

Matt is pleasingly frank in his recommendations to avoid certain approaches, and after reading the book, I feel like I have a better eye for assessing how “Pythonic” something is. In fact, now that I have finished the book, I can look back on Python code I wrote before reading the book, and critique the heck out of it. Prior to reading this book, my Python code looked a lot like my C++ code, which is just a shame. This book can help inoculate you against such behavior.

The book reads smoothly and quickly. Matt is very careful to keep his explanations succinct and clear, such that you don’t feel like you’re reading a college text book or a reference manual. Even still, the book does contain a high information density.

On my iPad, with the default font size, the book is 243 pages in landscape mode and 147 pages in portrait mode.

I finished the book in fewer than a dozen 15-30 minute sittings.

Conclusion

If you can already crank out Python list comprehensions and lambda expressions, this is probably not the book for you. If you are an experienced programmer and want to learn Python, this is a fast way to start. If you are a total programming novice, this may be a good way to begin, but I’m not a great judge for this audience.