Hotswap + Nesh. A more awesome Node.JS development experience.

Ever since working on some minor Clojure projects and getting some experience with the leiningen and LightTable, I’ve been expecting a little bit more from the programming environments I work in. I want to interact with my code as I write it to see how it behaves, know when there are problems as soon as there are problems, and I don’t ever want to have to hit “run” or “compile” or anything like that. I realize this I won’t be getting that with C++ or Java, but that’s ok – most of what I need to do I can do pretty well in a scripting language.

Anyway, as I’ve begun doing significantly more work using Node in the past few months, I decided to really dig into the available toolset. I’ve discovered a few things that have really made life much more pleasant.


Hot code reloads are pretty necessary for catching errors quickly and being able to interact with your code as you write it. The hotswap module helps with this nicely. It’s not perfect – changes in modules required by the modules you hotload aren’t recognized instantly, so unless you’re only working on a few modules you’ll probably have to restart your REPL session at some point, but it’s a big improvement over the standard REPL experience. All you have to do to get rolling is this:


and in your module…

module.change_code = 1;


Nesh is a drop-in replacement for the standard Node REPL. It features code inspection, multiple language support (you can write CoffeeScript), convenience functions and a plugin system.

You can also start it as part of a node process, just like the standard REPL.

One thing that really annoys me about the Node REPL (that Nesh shares) which I haven’t figured out a good solution to yet is when (for example) a syntax error is thrown, the Node process bails and the REPL closes. I’m sure a solution is possible, I just haven’t tracked one down. A work-around, and otherwise generally useful practice, however, is to do some preprocessing to prepare my REPL environment. That way, I don’t need to load too much of what I was working on when I restart the REPL. This is possible with both the standard REPL (by modifying the REPL context) and with Nesh (by modifying the global scope). Here’s an example:

Say I want to load a specific REPL experience (for working in one part of my application vs another). I have a script which is included anytime I want to have a REPL:

var hotswap = require('hotswap'),
      nesh = require('nesh');

opts = {
    welcome: 'Welcome!',
    prompt: '> '

// Load user configuration

module.exports = {
    start: function(callback){
        // Start the REPL
        nesh.start(opts, function (err) {
            if(callback) callback();
            if (err) {

That bit loads hotswap and calls a callback when the REPL starts. The callback is what I use to inject what I want into the scope:

var repl     = require("./repl")
      fs         = require('fs');

    config  = require('../config');
    lib1 = require(config.libdir+'/lib1');
    lib2 = require(config.libdir+'/lib2');

Voila! A very pleasant Node development experience – an interactive REPL with code hot swapping and configuration dirty work taken care of.

Posted in JavaScript, NodeJS, Programming | Comments closed

An open letter to Baxter State Park

To whom it may concern,

On July 22nd, 2014, I entered Baxter State Park at around 9PM with the intent of camping at the Katahdin Stream Campsite.

Upon arriving at the clearing with the bathroom facilities, ranger station and employee housing near the daicey pond campsite, I took note of the sign informing me that I would not be able to check into the camping site after hours. Specifically, the sign said I would not be admitted. It was after midnight and I had walked nearly fifty miles that day. As a thru-hiker, I had become very accustomed to often reaching my destinations very late. This was the first indication I had seen that I would not be able to sleep at the Katahdin Stream Campsite. There was no indication that I could continue to the campsite and pay in the morning. The sign simply stated that I would not be admitted. I knew that “stealth camping,” or unauthorized camping, was not permitted, so I chose to sleep, very uncomfortably, on a gravel pile directly in front of the employee station, so when I woke up in the morning I could promptly pay the $10 fee that would have been required if I had arrived before the Katahdin Stream Campsite closed.

When I woke up and was packing my tent, I indeed met an employee driving towards the Daicey pond site in her truck. I believe her name was Rita. Rita refused my $10 and reported me to the law enforcement ranger. She asked me for identification and I provided it, willingly.

The Baxter State Park Rules and Regulations book states that camping is limited to certain sites to preserve flora and fauna. I slept on a gravel pile next to a gravel road in front of a building. Presumably, this gravel road and building destroyed a lot of fauna in their construction. Had I any intention of dishonestly avoiding the $10 fee, I would have simply stealth camped in the woods, and would have never been discovered. I would have never given your employee who was not physically capable of pursuing me my identification. Yet, I chose to limit my ecological impact and sleep on the gravel pile, and to attempt to pay the $10 fee despite having slept on a gravel pile.

After my encounter with the first park employee, I talked to the ranger at the base station. He acted like he was sympathetic to my story and told me the employee I talked to earlier “liked her job too much,” and was making a big deal out of nothing. He said she had been on the radio making a big deal about it. He said he didn’t care, but it would probably be a good idea for me to check in with the law enforcement ranger.

I hiked up to the end of the trail at Katahdin and upon my return, went to talk to the ranger at the base station about how to contact the law enforcement ranger. He informed me that the law enforcement ranger was leading a convoy of construction cranes, and that to link up with him, I would need to run a half mile to the road and hop in his truck. I did.

The officer, Isaac Needell, summarily proceeded to tell me that I broke the law and that he would be writing me a ticket for it. I brought up the fact that the park’s charter, and the intent of the law, was to preserve the ecology of the park, and what I had done had satisfied the spirit of those requirements. I told him that I believed that this had nothing to do with preserving biodiversity, and everything to do with revenue.

I do not deny that I broke the law by sleeping most miserably on your gravel pile. Your policy communicates to people that it is better to dishonestly avoid the law, than to respect the spirit of a law and approach any breaches honestly. I voluntarily slept in front of your employee station on a pile of gravel that was left over from park development projects that most assuredly destroyed the flora and fauna your charter claims it protects. I voluntarily confronted your agents, provided my identification, and entered officer Needell’s car. The fact that I was penalized for my honesty and conscientious behavior, and that my money was refused in favor of the opportunity to extort me, speaks volumes about the true intent of Baxter State Park – commercialization of natural resources and revenue through extortion.

Best regards,
Calvin Froedge

Posted in Appalachian Trail | Comments closed

Dreams and Feedback Loops

I had a dream last night about Chris Granger.  He worked on Microsoft’s Visual Studio team, and then went on to build LightTable, a next generation IDE written in Clojure.  I’ve known about LightTable for a couple of years, but have only begun using it recently.  The takeaway from the dream was, “Get to know your tools, learn as much as you can.”  I went to Chris’ blog this morning and started reading posts.  I came across this post, which talks about connecting to what you create.

Chris referenced a talk by Bret Victor, a kind of renaissance man, who was discussing feedback loops during the creative process.  He showed some screenshots from a design tool he built which allows you to visualize your work as you complete it.  For example, you write an algorithm, and you can see, as you write the algorithm, how it manipulates data.  This is where Chris Granger got his inspiration for LightTable, and after seeing the talk, went and coded a prototype in Clojure.

Bret talks about working by guiding principles, choosing tools that give you immediate feedback, and nurturing your ideas.  It’s funny how inspiration hits.  Chris saw this video and then started coding.  Fast forward two years and he raised a few hundred thousand on KickStarter and built an awesome product.  I didn’t get just how powerful it was until watching this video, and now have a reason to take the time to master the tools while continuing on the project I’m working on.

Dreams are funny.

Posted in Ideas, Programming, Software Design | Comments closed

Why Abe Lincoln Would be Homeless Today

“Let no man live who is wiser or better or more famous or even handsomer than the mass. Cut them all down to a level: all slaves, all ciphers, all nobodies. All equals.”

- CS Lewis, The Screwtape Letters

We have, in American culture, most curious ideas about equal opportunity.  Where once we valued inventive genius, we now tend towards something which is much more static, predictable, and stale.  Fifty years ago, around 5% of Americans held college degrees, and fewer than 40% had graduated high school.  Today, more than 30% graduate college and more than 90% from high school.  It’s easy to make the assumption that such an improvement in the educational attainment of the common man means that the average American is becoming more intelligent.

However, this just isn’t what’s happening.  We’ve been using standardized tests to evaluate college preparedness for nearly a hundred years, and those scores (SAT, namely) haven’t improved.  In fact, they’ve dropped 40 points since 1967.  Interestingly, scores haven’t dropped because the tests got harder, as the average man became more educated.  The opposite is in fact true.  Scores have declined, in spite of “re-scalings” and simplifications in the test format. Meanwhile, higher education is becoming exponentially more expensive, outpacing general inflation by 500%, and graduates are getting less from it.  The problem is that we have, as a culture, become more accustomed to jumping through arbitrary hoops than actually becoming competent at something.  Instead of being interested in really learning things, we set our sights on becoming certified to do it.  Abraham Lincoln attended less than a year of school throughout his lifetime, yet taught himself to read and write.  He took the bar exam, he passed, and at the height of his career he was handling more cases than any other attorney in Illinois.  He didn’t come from a rich family, he didn’t attend a prestigious school – he practically didn’t attend school at all.  He studied on his own, he took the test and he passed.  People hired him because he charged reasonable rates, spoke eloquently, and knew the law well enough to win cases.  Today, it’s not possible to “Read the Law” as Lincoln did.  Our legal code is vast, but understanding it certainly doesn’t require formal education – it simply requires actually reading the laws, something so very few of us, including those hired to interpret the laws, do.

The list of professions requiring institutional licensure is vast.  Lawyers and Doctors spend decades in school, beginning with childhood.  Accountants, engineers, massage therapists, psychologists, speech therapists, even hair dressers and barbers, all must complete long tenures in education before they can begin practicing in their chosen profession.  This doesn’t lead, as conventional wisdom would suggest, to better professionals.  The institutional educational model is diametrically opposed to the style of learning that some of the most profound scholars, professionals and leaders in human history have followed.  Under the institutional model, whether or not someone can do it is irrelevant.  Whether or not someone aces the bar exam is irrelevant.  The real requirement is that they spend years of their life and thousands of dollars at a state approved institution. If the intended output of our educational apparatus really is people who are capable of performing certain societal functions, as demonstrated by their performance on a final written exam, why do we not simply allow people to just take the  test and spend the best years of their life doing something other than required drudgery?  There’s a term in our prison system called “make work,” which describes work that is created simply to keep someone busy.  I can’t help but believe that the majority of the things we engage in are simply that – make work.

We live in a world abound with free educational opportunities.  Universities around the world publish lectures, notes and research on their public facing websites.  Between Khan Academy, Udemy, Udacity, Coursera and Wikipedia, you can easily find every educational resource you would need for both a world-class K-12 education, and a competitive university education.  The only thing you need is a bit of self-discipline.  In a free market economy, one expects that when better, cheaper alternatives to goods and services enter a market, all of the costs for those goods and services will be reduced.  The older, less effective, more expensive goods and services will at first have their prices lowered to remain competitive, and at some point, they will lose their economic viability entirely and disappear from the market forever.  This isn’t happening in education, because education in the United States is not a free market.  Economic vitality is tied directly to professional licensure, which is controlled by the educational system.  Economic livelihood in the United States has become a walled garden.  Someone could learn everything there is to know about medicine, but to practice medicine without going to jail, you have to stay in school till an institution says you can leave.  We all pay for this – not just the aspiring doctor.  Because the AMA tightly controls the process for becoming a doctor, and the amount of doctors who can enter the market, we all pay more for medical services.  We debate about how to pay for national healthcare schemes, yet we don’t consider that the costs are so high in the first place because the design of our institutions makes them so.

I was drawn to software development because it’s difficult to regulate, and thus easier to practice without needing to do make work.  I’ve spent thousands and thousands of hours learning, and as a result, I can make software.  Because I can make software, people hire me to make software.  It’s significant that, being one of the only professional fields which does not require licensure to practice professionally, software development has made such a significant impact to every other field.  Electronic medical records, magnetic resonance imaging, synthetic biology, electronic diagnosis, etc., were all made possible by software engineering.  It doesn’t matter what industry you examine – architecture, aviation, psychology – every single one of them have made huge advances in recent years only because of the advent of computers and those who program them.  It’s ironic that these advances were largely enabled by unlicensed people.  Yes, universities were involved and played a considerable role.  MIT, Stanford, Berkeley and Michigan State all played huge roles in the development of the internet and of many advancements in programming tools, languages, and operating systems.  However, the contributions of the unlicensed amateurs were incredible.  Gates was educated by having access to computers at an early age.  He dropped out of Harvard and his operating system enabled cheap desktop computing for a generation.  Jobs dropped out of Reed and brought us Toy Story and the iPhone.  Larry Ellison dropped out of high school, and went on to build one of the first relational database systems, power half of the world’s ERP systems and purchase an island in Hawaii.  John Carmack revolutionized the video game industry with his physics engines after dropping out of public school, then went on to found Armadillo Aerospace, serving as the lead engineer.  He landed a spacecraft on the moon and won a $500k prize.  Nasa spent $25B in 1969 dollars to put a man on the moon, while the Soviets spent $4.5B on their Luna program.    Going back to the very birth of electricity, Benjamin Franklin, the guy who appears on the $100 bill, had a famous disdain for institutions.  He is remembered for such minor advancements as electricity, refrigeration and modern currency.

The point is that our society is totally reliant on progress made outside of our institutions, yet we chain ourselves to these institutions.  We require K-12 completion to be admitted to public universities on scholarship (GED students are not eligible for state merit scholarships in most states, regardless of standardized test scores).  We require degrees and licensure for so many professions and further study programs.  We’ve decided that people must do one thing at a certain age, and another thing at some other age.

Today, we stand at the precipice of systematic collapse.  Global food systems and ecology are on the brinke.  Bees are dying, rain forests are being cleared at an unprecedented rate.  Our currency is worth less and our lives cost more.  Half the world lives on less than a dollar a day.  Deserts are expanding as soil levels are depleted.  And yet…an unassuming, sweet girl who just wants to get married and pop out a few kids has to stay in school for over a decade just so she can cut hair.  A young Isaac Newton has to sit in class with that girl until he reaches the level where he can take an advanced class with only slightly less dumb classmates.  As Lewis stated, “The bright pupil thus remains democratically fettered to his own age group throughout his school career, and a boy who would be capable of tackling Aeschylus or Dante sits listening to his coeval’s attempts to spell out A CAT SAT ON A MAT.”

Sure, there are exceptions.  There are ten year old students who go to college, graduate and spend the rest of their lives doing something meaningful, the miserable make work out of the way.  This exception requires a village of support, however.  It requires not only that the pupil be extraordinary, which is surprisingly common, but that the parents are willing to take action to challenge the student outside of what is conventional, that administrators of educational and professional institutions are flexible, and both willing and able to bend the rules for unusual circumstances.  A system which can accommodate someone with exceptional potential is, sadly, far less ordinary than the prodigy herself.  In this regard, the responsibility lies more on society to allow for greatness, than for individual greatness to occur.  What does all that mean?  For starters, that if a fifth grader can test out of high school, that the local school district damn well better encourage her to.  That  the parents better cast away all fears about social acceptance.  That an individual with no formal educational background, yet who has developed a substantial body of intellectual work, should be evaluated on her proven merits rather than her hoop jumping abilities.  The “real” world – the world that produces the things that allow the rest of us to survive – already works this way.  The trick is to make our institutional world – academia and government – mirror this rather than impede it.

Posted in Abstract, Philosophy, Politics, Programming | Comments closed

Sex is a Ghetto

We’ve got a big problem in this country with intellectual honesty.  After all, 46% of Americans still believe that God created man in the past 10,000 years.  Any educated person accepts that the earth is not flat, that there is no tortoise carrying the world on its shell, and that knowing a lot about plants makes someone a botanist, not a witch.  I’m not picking on religion – I’m simply showcasing a belief that seems childish to anyone willing to think critically, yet many Americans hold.

Equally stupid are our views regarding sex.  Everyone will agree that sex is pervasive in our culture.  Every magazine at every super market checkout line advises women on “how to spice up their sex life” or, “how to make him go crazy.”  Conservative news networks feature scantily clad, big busted reporters with low IQs.  Attractive people get better job offers.  STD rates are on the rise, especially in conservative states.  Divorce rates are still increasing.

The evidence says that sex is happening all the time.  One would assume by looking at the most recent Cosmopolitan cover that sex is all women ever think about.  30% of all internet traffic is porn, more than Netflix, Twitter and Amazon combined.  Yet, talking about sex openly and maturely is taboo.  Over 50% of Americans watch porn once a month, yet only 29% consider it morally acceptable, and only 23% of women. Dating sites like OKCupid and Plenty Of Fish ban profiles with sexual content, even when there is no nudity.  Craigslist is anonymous.  Dating apps are anonymous.  Sexual education programs in many states are severely lacking, focusing on an “abstinence”  rather than educating people about sex.

Considering our remarkable cultural obsession with sex, it’s nothing short of incredible that practically no one talks about their sexual preferences and activities openly.  It’s incredible that there are no non-objectified instructional sex programs on cable television.  Unless it’s not, the goal of dating is generally sex, yet it’s considered immoral, rude and disgusting to come out and say it.  For whatever reason, people are fine proclaiming absolutely idiotic beliefs about a myriad of political topics to the world, yet nearly no one has the balls to come out and tell a potential mate that they’d like to have sex with them straight out.  Everything is a game – a complex weaving of clothes, perfume and conversational topics all directed at an end which is universally understood yet never put bluntly.  We create so many facades portending greater meaning that are absolutely void of substance, simply so we can save ourselves the embarrassment of being caught speaking truthfully.

It shouldn’t have to be like this.  We as a culture should be able to talk openly about sex.  We should be able to look at sex as a natural act, and discuss it in a rational way.  The only function of the clitoris is female genital stimulation.  Other intelligent animals engage in recreational sex.  In an ideal world, two people who are attracted to each other should be able to come right out and say, “I’m attracted to you, and I’m horny.  Would you like to have sex?  Do you have any STDs?  Are you regularly tested?” Furthermore, they should be able to do it in front of their friends without fearing public disgrace.  It’s time we stop with the euphemisms and misdirection and start viewing sex for what it is – something that we all do, that we all want, that we should be able to talk as naturally about as we would a pair of shoes.

Instead, “sex communities” are created that use code language like “swinging,” “tantric experience,” and “open love,” and meet in virtual secrecy.  People flock to online services that promise intimate encounters yet more often simply charge a monthly fee to chat with bots and scam artists.  Other sites cater to sex seekers as if sex is a perversion, designed using dark colors and using more code language that isolates people and makes them believe there is something perverted about them.  Good people with open minded views about sex and intimacy are forced to either play the game or join the sex cults, because there is virtually no public forum that allows direct sexual language.

All of this has to be the biggest waste of time in human history.  If we weren’t spending so much energy obfuscating pursuit of our sexual desires, we could spend more time doing useful things like…I dunno…replanting forests, finding cleaner energy sources, redesigning utility, energy and housing systems to be more efficient, banning pesticide use, limiting campaign contributions, etc. etc.  In the time that we  spend playing games to get into each others’ pants doing this ridiculous cave man’s mating dance, we could have simply fucked, had a meaningful conversation about something completely unrelated to sex, and spent time doing something worthwhile.

It’s about time that we stopped treating sex like a Ghetto that can only be stumbled into in secret, drunken revelry or puritanical union, and start acknowledging it as a part of adult life that can be discussed shamelessly.

Posted in Abstract, Philosophy, Sexuality | Comments closed

Good habits

Consider this quote by Aristotle:

“Excellence is an art won by training and habituation: we do not act rightly because we have virtue or excellence, but we rather have these because we have acted rightly”

Wow. If this is a true statement (and I believe it is), then a man ought to build his life around doing the very things that produce virtues (goodness, compassion, magnanimity, honesty, etc.) and competencies (skills and abilities). To me, that means recognizing the actions that will grow your virtues and competencies, and making a real commitment to perform them on a consistent basis. Take for example the following well-known proverb:

“The early bird gets the worm.”

The phrase is usually said to mean “he who rises early finds opportunities which others miss.” The meaning of “early bird” lies in “he who rises early.” An “early bird” is not so much a thing that is or is not, such as gold or copper or air, but rather a word used to describe one who performs certain actions. Though a man can never through his actions become gold or silver, he can assuredly rise earlier each morning and thus become an early bird.

Thus, what life may really be about is deciding what activities you might participate in or abstain from which will form the virtues you wish to exhibit, or build the skills you wish to have.

Harry Truman once said, “In reading the lives of great men, I’ve found that with all of them self-discipline came first.” A man is not virtuous or competent because he was born as such, but rather because he has worked at it. The type of systematic work that actually makes the difference is what takes discipline. A man might be a great admirer of music. To become a musician, however, he must work. He must study theory, analyze the music of others, and become skilled with some instrument. Simply enjoying music is not enough. Simply wishing will not suffice.  A man must perform repeated actions to achieve a desired result.

All of this comes back to your habits. If you wake up early every day and focus for a few hours on getting something really important done, you become a person who gets up early and gets things done. If you can make time every day to learn more about your craft (a few hours), then very soon, you will find yourself surpassing your peers who perhaps only learn when necessity demands. Bad habits go the same way.  If you drink often, you risk becoming a drunk.  If you shun social interaction, you might become a pariah.

To simplify Aristotle’s original quote:

“We are what we repeatedly do.”

Posted in Abstract, Goals, Philosophy, Self Improvement | 1 Comment

The fire

A warm fire, a cool night; your lips on the tea cup. A savory liquid fills the soul like early morning light.

These years have been dark; despair an old friend. A fortitude beats yet inside – a muse that inspires, a desire to fight.

Fuel given, the fire builds. This tiny house a beacon, its radiance weakening winter’s grasp, a new creature emerges, a heart overcome with delight.

Keep at it, urges the muse. Your work known, your path defined; Cloaked in gold and purpose refined, go now, take hold of what you sought to find.

Posted in Poetry, Self Improvement | 3 Comments

Traits, Exceptions, and Better Automated Tests

I really, really dig 5.4′s traits. Let’s review:

  • Through the ‘use’ keyword, traits let you include shared functionality in a class without relying on inheritance or encapsulation of another class.
  • With the exception of declaring static variables (you can’t), and referencing parent (will call the class you’re using the trait in), traits behave just like they’re part of a class.

Now, let me say a few things about how I prefer to code:

  • Unless I know 100%, beyond a shadow of a doubt, that an argument list will *never* change, I prefer passing objects or arrays as arguments instead of variables.  What I’ve seen happen in many projects / frameworks is you end up with this impossible method list.
  • As much as possible, I like to write defensive code that favors exceptions I can catch over fatal errors that will crash my programs.
  • I do NOT like repeating myself.
  • I’m lazy.  When I’m running automated tests, I don’t just want to know that an assert failed, I want to know exactly why it failed.

Thus, was borne my solution to checking required params and throwing exceptions I can catch in my tests when they’re omitted.  Consider the following code snippets:

The RequiredParams trait:

namespace System\Friend;

trait RequiredParams
	protected function checkArgs($params, $required){
		$missing = array();
		if(is_array($params) || is_object($params)){
			if(!is_object($params)) $params = (object) $params;

			foreach($required as $k){
				if(!isset($params->$k)) $missing[] = $k;

			if(count($missing) > 0) {
				$missingKeys = implode(", ", $missing);
				throw new \Exception("Required params are missing: $missingKeys");
			else {
				return true;

		throw new \Exception("Argument list was empty.");

RequiredParams is used in AccountingProxy (duly noted that the hardcoded numeric literals should probably be constants). Here is one of the methods:

	public function createInvoice($params)
		$this->checkArgs($params, array('type', 'id', 'created', 'due', 'items'));

		$invoice = array(
			'Invoice' => array(
				'Type' => ($params->type == 'payable') ? 'ACCPAY' : 'ACCREC',
				'Contact' => array(
					'ContactNumber' => $params->id
				'Status' => 'AUTHORISED',
				'LineItems' => array(
				'Date' => $params->created,
				'DueDate' => $params->due

		foreach($params->items as $item){
			$this->checkArgs($item, array('description', 'qty', 'amt'));

			$item = (object) $item;

				$code = $item->code;
			else {
				$code = ($params->type == 'payable') ? 65700 : 410;

			$invoice['LineItems']['LineItem'] = array(
				'LineItem' => array(
					'Description' => $item->description,
					'Quantity' => $item->qty,
					'UnitAmount' => $item->amt,
					'AccountCode' => $code

		$created = $this->xero->invoices($invoice);

		return $created;

And here is a a test definition for the method:

			new \Model\Implementation\AccountingProxy,
				'name' => 'Create a receivable invoice',
				'method' => 'createInvoice',
				'args' => array(
					(object) array(
						'type' => 'receivable',
						'id' => $customerId,
						'created' => '',
						'due' => \System\Implementation\DateTime::now(),
						'items' => array(
							'description' => 'This is an invoice item',
							'qty' => 1,
							'amt' => 20.00
				'assert' => array(
				'responseToVar' => &$payInvId

So, as you can see, if createInvoice is missing any required items, even params within params, we can use checkArgs to throw an exception and give us real details about the problem.


Posted in PHP, Programming | Leave a comment

Traits + Interfaces in PHP 5.4 – The Perfect Team

PHP has been getting consistently better over the past few years. One new feature that I’m really pleased with is traits, which is similar to multiple inheritance in Java, friend classes in C++ or mixins in Ruby and Python.

Basically, traits allow your classes to share functionality without constructing any objects or inheriting from any base classes. I’ve been able to put traits to some pretty cool uses already.

One of the neatest things I’ve done is teaming them with interfaces to implement shared functionality that adheres to an interface without needing monolithic base classes. Here’s a simple example:

interface Foo
	public function bop();

trait Baz
	public function bop()
		print 'it works!';

class Bar implements Foo
	use Baz;

$x = new Bar();

As you can see, Bar does not have a bop() method in its class definition. It’s using the definition provided by the trait. The scoping in the Baz treat still works just like you’d expect for the most part (the only trouble I’ve had so far is using parent::__construct() in a shared constructor).

Let’s look at a more complicated example (Note – this is just an excerpt from a more complicated program, it won’t work if you just copy and paste it. If you want to give traits a shot, start with the simple example and work your way up):

namespace Model\Abstraction;

interface InterfaceRead
	public function __construct();

	public function fetchBy($qualifiers = array());

	public function fetchAll();

namespace Model\Friend;

trait Read
	*	Fetch records using a where clause
	public function fetchBy($qualifiers = array())

		$result = $this->stmtPrepExecFetchAll("*");	

		return $result;

	*	Fetch all records
	public function fetchAll()
		return $this->fetchBy();

namespace Model\Implementation;

class Intl extends \Model\Implementation\Base\Base implements \Model\Abstraction\InterfaceRead
	use \Model\Friend\Read;

	public function __construct(){

Since all of my models which are read only will use the same API, it makes great sense to use traits to implement common functionality. Fortunately, if I need to, I can still override the functionality provided by the trait by simply declaring the method within my class.

Ok, so let’s take this a step further. What If I want to adhere to an interface which demands more shared functionality? Easy, just toss another trait into the mix:

namespace Model\Implementation;

class Intl extends \Model\Implementation\Base\Base implements \Model\Abstraction\InterfaceCreateRead
	use \Model\Friend\Create;
	use \Model\Friend\Read;

	public function __construct(){

Anyway, thought this was cool and wanted to share = )

Posted in PHP, Programming | Comments closed


For the past few months, I’ve been exploring software design patterns, both at their roots and in their modern implementations. I’ve been exploring new languages and deepening my understanding of the languages that I already use. Man can I ever tell ya, it’s been exhilarating.

I started reading a new book last night, given to me by a CS professor who has been extremely kind to me. It was written in 1979, published by IBM: “Structured programming, theory and practice“. In the preface to the book, the authors discuss the beginnings of the software development field (originally an afterthought to hardware, and an error-prone, cut-and-try process) and its evolution into a true discipline where a programmer could solve a problem correctly, the first time, with no mistakes. I found one statement incredibly profound, contrasting ad-hoc spray-and-pray methods with true precision: “A programmer can gain 10 years of experience, or a programmer can get the same years experiences 10 times over.” Wow. How true.

If there is any fundamental evil in the profession of software, it must be that horrible trial and error loop that is the result of a lack of understanding – about the problem at hand (if it has even been defined), the tools at your disposal, existing solutions, or all three. When we allow ourselves to subsist in such a state, we waste the little time we have on this planet. We become triflers and busy bodies, always scurrying about in a rush yet never accomplishing anything of significance.

Have you ever met someone who has been in the field for years, yet still seems to have abilities only slightly better than that of a novice? I have. In contrast, have you ever met a “whiz” who seems to make incredible progress in short amounts of time? I’ve met a few of those as well.

In Daniel Coyle’s “The Talent Code: Greatness isn’t Born, it’s Grown,” the process of building skill is discussed and examined at length. The book opens with a story about a girl who does a month’s worth of practice in five minutes, without even knowing it. This seems like a fantastic claim from the outset, but as the book progresses Coyle makes his case. Coyle claims that while duration of practice is indeed important, the method of practice is a far more effective mechanism for building talent. Coyle examines Russian Women’s Tennis Champions, South Korean Golf Champions, Brazilian Soccer Players, World Class Musicians and Singers, Surfers, Chess players, elite magnet schools and more. His argument is that in all cases – elite performers don’t simply spend lots of time in their respective courts – they spend their time doing completely different things. Elite performers focus on developing a fluency with the fundamentals. They “chunk” their learning such that each piece is mastered independently of the whole.

I feel software development is a field where this is especially true. From my own experiences, I know that my greatest personal gains have come from:

- Deep study of fundamentals. Language fundamentals. Programming paradigms. Data structures. Repetition of those fundamentals.
- Application of those fundamentals in more holistic contexts.
- Closely examining (not just reading, but PORING OVER) code written by more capable programmers

Conversely, I can say that my own gains plateau when I find myself debugging code I don’t understand, using tools I don’t understand, and staying in my comfort zone (ie writing code and designing systems I already know how to write and design). The longer I subsist in this state, the harder it is to get back to doing it right. Complacency and ignorance breed the same.

CS Lewis states in the preface to “The Great Divorce” that “when a man faces a fork in the road and chooses incorrectly, he will never reach his desired destination by continuing. He must backtrack to where the error was made and begin again on the correct path.”

A programmer will never grow in a state of willful ignorance and repetitive, mindless busy work. A commitment to knowledge and understanding, being guarded against error, a passion for our craft; These are the building blocks of growth. This is how we evolve…quickly.

Posted in Abstract, Computer Science, Programming, Self Improvement | 5 Comments