Code Katas: The Stack

I explored in my previous post the idea of a coding kata. I expressed that I did not think just any exercise was worthy of being called a kata, because not all exercises are worth of practicing more than a few times. But there are concepts in computer science that are worth repeating again and again, to become a better programmer.

What brought this first to my attention was Uncle Bob’s screencast on the Stack kata where he demonstrated Test Driven Development implementing the Stack data structure.

As a kata, it’s beautiful. It’s a fundamental concept that could be implemented in many different ways. Also, interestingly, it would be implemented differently in different languages. So there is a lot to explore here.

Before putting forward the tests Martin used, I’ll recap what a Stack is.

A stack works like a stack of plates.

  • The first items into the stack are the last items to be taken off.
  • If you have a limit to how many plates will fit on your shelf, you can’t fill it too high.
  • You can’t remove from a stack if it’s empty.

That’s basically it.

Here are the tests that Uncle Bob lays out in his screencast.

  1. Can create Stack object.
  2. Newly created stacks should be empty.
  3. After one push, stack size should be one.
  4. After one push and one pop, should be empty.
  5. When pushed passed limit, stack overflows.
  6. When popped passed limit, stack underflows.
  7. When two values are pushed then one is popped, size is one.
  8. When one is pushed one is popped.
  9. When one and two are pushed two and one are popped.
  10. When creating stack with negative size, should through IllegalCapacity.
  11. When creating stack with zero capacity, any push should overflow.
  12. When one is pushed, one is on top.
  13. When stack is empty, top throws empty.
  14. With zero capacity stack, top throws empty.
  15. Given stack with one two pushed, find one and two.
  16. Given a stack with no two, find two returns null.

In my implementation and the tests I used, I ignored everything relating to capacity (5,10,11,14) because I implemented my stack in JavaScript. I could implement overflows, but JavaScript does not require a capacity when instantiating an array.

Want to give it a shot yourself? Post your implementation in the comments.

Exploring Test Driven Code Katas

I’m fairly new to the term Code Kata; I haven’t read any books on the subject. Over the past few years I’ve seen them mentioned around the internet, but with the overuse of the martial arts terminology in coding — everyone’s a ninja — I chose to ignore it for the most part. When I did look into it, the ‘katas’ I saw seemed like a gimmick to sell mere coding exercises.

Kata is Japanese for ‘form.’ In martial arts, a kata is a collection of moves that are brought together for the purpose of raising and maintaining a student (or any practitioner) to a base level of competence. Sometimes a kata embodies an entire style of martial arts, so it’s far more than that simply a collection of moves, but I won’t get into that here.

Robert C. Martin (Uncle Bob) author of the seminal paper bringing together the SOLID principles, has a video series on his site — Clean Coders — aimed at educating developers towards writing better code.

In the “extras” for episode 4 Martin does the “Stack Kata” to demonstrate how Test Driven Development (TDD) can be implemented for most anything.

Watching the show feels like you’re watching Good Eats, but for coders. There are multiple personalities — all played by Martin — who argue with each other over the best way to accomplish something, there are backdrops from around the universe, his family take part. It’s endearing, and sometimes distracts from the content. Overall I would say that the content has helped me grow as a developer by leaps and bounds.

Having practiced martial arts, for years, the idea of the “Stack Kata” speaks to me. There are fundamental concepts, patterns, and principles that developers should go back to, that will improve the way they think about everything they do. With each iteration they understand the coding principles on a deeper level, which then resonates throughout the rest of their code.

The experience of performing a “basic” kata and then experiencing it on a completely different level of competence, is powerful. For that matter, when watching a master perform that same “basic” kata — you can see their mastery clearly.

According to Wikipedia the term ‘code kata’ was probably first coined by Dave Thomas, co-author of the book The Pragmatic Programmer. While I highly applaud the concept, I disagree with what he puts forward as what code katas should be.

In his intro to the concept, Thomas explains “A kata is an exercise in karate where you repeat a form many, many times, making little improvements in each.” But katas, really, are more fundamental than a mere exercise. A Kata is a ‘form’ or ‘pattern’ in Japanese — not an exercise. He states in that same intro that “Sometimes ‘kata’ isn’t quite the right word.” I think that might be because many of the ‘katas’ he suggests on that page are simply exercises, not foundational concepts.

I’m not opposed to exercises, but they don’t need to be practiced again and again.  It’s very possible that Thomas suggests katas that are far more fundamental elsewhere. I personally think data structures and design patterns are prime candidates to be excellent code katas. Maybe I’m just a purist.

Test Driven Code Katas

What are Test Driven Code Katas? Well, they’re code katas done TDD style. Given the tests, you perform the kata.

What makes Test Driven Code Katas powerful are that they lay out the path to take when practicing without giving away what how exactly the code should look.

Probably the most important part of developing tests first is writing the right tests. If you are given the tests, it detracts from the practice. However, at least for starting out, there is no better guide — even better than specs — then following a proper set of tests.

I’ve been exploring fundamental computer science terminology, concepts I missed as a self-taught developer. As I go through them, I’ll be posting my katas for all to enjoy and explore.

Join me

If you’d like to share your implementations along with me, I’d love to see them. Post a link to your github repo with your implementation below the kata. If you decided to write your own tests, I’d love to see other ideas on how to approach a problem.

Image credit

Ep6 – Owning Books

On April 8, 1933, the Main Office for Press and Propaganda of the German Student Union proclaimed a nationwide “Action against the Un-German Spirit”, which was to climax in a literary purge or “cleansing” by fire.

On May 10, 1933, Nazi Germany staged an event unseen since the middle ages young German students from universities, which formerly had been regarded as among the finest in the world, gathered to burn over 25k books.

On April 6th, two days before the initial declaration, William Lyon Phelps of Yale University, who taught the first American University course on the Modern Novel shared the following thoughts on a public radio broadcast.

Why this speech?

Today, more than any other time, we are never alone. Between social media, music and video on demand services, email and cellphones, we are never alone.

Even so, what Phelps describes, about friends still holds true.

While we can still connect with most anyone, whenever we want, there still lacks a depth that we have in-person that we cannot have with digital-friends. That depth still holds with book-friends.

Movies are too short,  DMs can’t convey depth. Book-friends are there with you for hours, and open a window into their lives on a level and complexity that no one would dare share on Facebook.

We always put our best foot forward on our social platforms, with books we see the real issues people struggle with.

Why doesn’t flush_rewrite_rules() work on my plugin?

One common issue that people run into when using custom post types in their plugin is that the pretty permalink structure doesn’t seem to take hold on plugin activation.

When adding new paths into the permalink structure, like with a new custom post type, you typically need to run flush_rewrite_rules() in order for them to take hold. One common piece of advice people give is to visit the Permalinks page in the Settings menu in wp-admin. The reason for this is that page runs flush_rewrite_rules() on load.

The problem with this advice is that you do not want to have to tell your plugin users that they have to visit that page after they activate your plugin. They should be able to click “activate” and it should just work.

One would think that if you add flush_rewrite_rules() to the activation function for your plugin that that should do the trick, right?


Well, yes and no.

If you call register_activation_hook when you are supposed to, not in a hook, then it will run well before your custom post type is registered — in init.  So it never actually gets to init, and your rewrite rules are never flushed.

So you do need to call flush_rewrite_rules() in your activation function, but you need to register your custom post type there as well.

Something like this:

function my_plugin_activate() {
register_activation_hook( __FILE__, 'my_plugin_activate' );

I’ve run into this myself and lost time trying to debug what’s going on. If you are ever trying to figure out why something isn’t happening when you think it should, look at the hooks.

Subsequently, if you don’t think you can do something in WordPress, you’re probably wrong. There are hooks for everything.

I hope that it will help someone else avoid this pitfall.

Image credit

We are here to make a choice between the quick and the dead

ON June 14, 1946 The Baruch plan was proposed  during it’s first meeting of the United Nations Atomic Energy Commission.

Less than a year after the US dropped fat man and little boy it was time to put in motion a plan to make sure that such destruction could be prevented from ever happening again.

Text to full speech.

Why this speech?

There are few things that effected the geopolitical landscape of today as greatly as World War II.

However, even knowing people who have lived through the war, and reading countless books, and lectures and courses about the war it is still something that is hard to fathom.

This speech is a powerful reminder of what had been at stake, what sacrifices had to be made, and what actions had to be taken to ensure victory.

But in the fabric of this speech, too, is an echo of the fears, and hopes following the War.

Object Oriented WordPress Plugin Development

I’m refactoring my WordPress plugins to implement better Object Oriented Programming concepts in them. During my exploration I came across

I have the utmost respect for the initiative and contributors to the project. I see this post as an exercise in understanding other people’s code, and thinking about what I would do. So I’m going to do my best to rip the project part.

I may be way off on some things, and spot on with others. I hope that if the contributors find this they don’t see it as a negative review; rather, an initiation of a discussion and request to jump in with their thoughts.

Screen Shot 2016-01-05 at 9.26.28 PM.png

Let’s start with the first file WordPress loads…


Lines 28:31
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {

Security features like this are all too often overlooked and ignored. I want to say that this should be at the top of every file in every plugin. However, it may cause issues for testing suites.

As for the rest of this file, a lot of the project is about encapsulating various aspects of a plugin into modules. This entire file, however, is all functions.

Why run:

register_activation_hook( __FILE__, 'activate_plugin_name' );

when you can run:

register_activation_hook( __FILE__, array( $this, 'activate' ) );

Also, I also don’t understand what you are gaining by starting up your plugin like so:

function run_plugin_name() {
  $plugin = new Plugin_Name();

I’m not sure what you’re gaining by doing that in a function instead of encapsulating the whole plugin in a class, including activation/deactivation hooks and then instantiating the class.

$Plugin_Name_Wrapper = new Plugin_Name_Wrapper();

There is a strong case to make your classes not run on instantiation. But then, do this:

$Plugin_Name_Wrapper = new Plugin_Name_Wrapper();

One of the benefits of encapsulating your plugin is that since WordPress is backwards compatible, it’s really the best way to namespace. Additionally, why would you wrap the instantiation code in a function then run it, unless you were to need it elsewhere. So it seems extraneous to me.

/includes, /admin, /public

This is nice. A clear separation between the different pieces of what you might put into your plugin. I’m not sure, though, if every component necessarily would break out so cleanly.

As I understand best practices for creating components, a component is a collection of classes or functions that all would be changed for the same reason.

In this case, there might be a component in which might need a bit of /admin, and a bit of /public. If you don’t do this you will most probably end up violating several of the SOLID principles. The single responsibility principle immediately goes out the window, what goes in admin? Widgets, and admin page, and saving the admin page… Also if you have these clear boundaries you cannot invert dependencies. I could go on.

You could still use this structure if you separate out each class for each piece individually, but I’m still not sure if there’s a benefit to pushing yourself into thinking along these boundaries.


If you are internationalizing your plugin, and you do it properly, all your strings would be in /languages, in which case that is a good directory to have.


Moving on… Let’s follow the includes, we have class-plugin-name-activator and class-plugin-name-deactivator; they both work and are structured as I’d expect. Run all the set-up/tear-down methods you need to get your plugin running.


I really do not understand what the point of the Loader class is for. I think it’s an attempt to not violate DRY (Don’t Repeat Yourself).

Take a look at this:

$this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' );


add_action( 'plugins_loaded', array( 'Plugin_Name_i18n', 'load_plugin_textdomain' ) );

Do you see a difference? Same about of repetition between the two. I think the thought behind it is that maybe this is how the authors wished hooks worked in WordPress?

Here’s the thing. Hooks are one of the most OOP aspects of WordPress. It easily allows you to to have all your code open for extension, but closed for modification; which, in turn enables dependency inversion.

Now this doesn’t negate that, but I also don’t see any benefits to adding this pseudo-factory. It only makes another layer that is unnecessary. It creates something else you need to test, and make sure is working. What happens if you need to change it? You’re going to have to change all the classes that depend upon it, and for what?

I think I picked on this enough.

I’m going through this, because I decided to refactor some of my own plugins to be better Object Oriented and so I’m thinking about this now. I’ll be releasing a post about what I ended up doing once I release the new version.

I’d just like to close by saying that there are a whole lot of nice concepts implemented here, it made me look at how I structure my projects more critically. I just feel that there’s a lot of things, as well, that are only for the sake of code and don’t actually provide Object Oriented benefits.

To my developer friends out there, what are your thoughts?

Blood Toil Tears And Sweat

On May 10th 1940 Germany invaded Belgium, France, Luxembourg and the Netherlands; Winston Churchill became Prime Minister of the United Kingdom upon the resignation of Neville Chamberlain. The United Kingdom invaded Iceland, and Belgium declared a state of emergency.

As the new prime minister, Churchill was called on to form a wartime coalition government. On May 13, 1940 Winston Churchill gave his First Speech as Prime Minister to the House of Commons.

Why this speech?

World War II changed the face of the world. There were two possible paths ahead. One side represented division, discrimination and destruction in the name of making one nation “great” among the rest of the world. The other path, was fighting for it’s existence and against all the evils that their opponents stood for.

Churchill is one of the great orators of the 20th century and this speech captures so succinctly that moment in history… with parallels to today that are not lost on me.

We Choose To Go To The Moon

On September 12 1962 John F. Kennedy gave a speech at Rice University where he declared his plan to send man to the moon within the decade.

I chose this as the first speech I would practice because it serves as a constant source of inspiration to me. This speech gives me chills each time I hear or read it, and it is the prime example, for me, of the power of speeches.

Why this speech?

Not only did President Kennedy cover so many of the important accomplishments of humanity, but he was able to put them into perspective.

50 years is hard enough to comprehend, but it is within a lifespan. He could have said “Less than 100 years ago we developed penicillin.” Instead, he said “less than a week ago.” A week in the context of 50 years is far more powerful than 100 years in context of 50,000 years. Most people can remember what they had for breakfast a week ago; while, I don’t know anyone who remembers first hand anything that happened 100 years ago.

Putting a man on the moon might have seemed impossible then, but when looking back over humanity’s accomplishments and seeing those accomplishments in the perspective of the exponential progression it took, it almost feels achievable.

That leads into the second piece I read from the speech, the why.

Reading this speech makes me want to be better, it plays chords on my soul reviving the sense of adventure I felt as a child when first discovering new things, new stories in books, hearing about new places and wanting to go there.

This speech speaks directly to the greater spirit of man, the transcendent urge to be, to conquer, and it channels that great desire towards one of the greatest achievements man could ever think of doing at that time. A challenge we haven’t achieved since.

And this speech has the power that it could do it. It could inspire man to reach that goal. and It did.

“For if Achillês is left alone to fight…” – Zeus Cloudgatherer

The literature of humanity that has stayed with us taps into the deepest part of how we perceive our existence. The stories that our ancestors have crafted and passed down to us resonated with them. The stories that made it down to us, made it through the filter of time because those stories said something important to each link the the chain from then until now.

Pondering this I recently read the Iliad for the first time, and then I read it again. One way that it resonated, surprised me.

Growing up I was never one of the athletic kids, but several of my close friends were, and thus I learned to play. There’s a unique excitement that engrosses you when you are participating in a game. I can still remember viscerally how deeply I wanted to win — especially during tournaments, and how it felt that all the powers of nature were conspiring for each event that happened during that game.

“You should pray to the everlasting gods yourself. You are no mere man.” Apollo to Aineias

– Iliad, book XX

Feeling this — while playing an intense game — it is 100% natural to pray to god, to request a favorable outcome to your game. Looking back 20 years later, or even a single month, most of those circumstances seem a silly catalyst for requesting divine intervention. But when you’re in the moment, heaven and earth should move for you to get that touchdown, or home run.

This affects spectating participants as it does the players. As a Red Sox fan (since before 2004) it’s clear to me that divine intervention is involved in these great games…

Achillês now cast his spear, and struck on the outermost ring, where the metal was thinnest and the hide thinnest behind. The Pelian lancewood ran through with a ringing sound. Aineias had crouched down holding up the shield; so the shaft passed over his back and stuck in the ground, still fast in the shield with the two layers torn apart. But he had escaped: he stood up dizzy and shaken when he saw that shaft sticking at his elbow. Achillês then drew sword and leaped at him with a shout. Aineias lifted a great big stone in his hand such as two men could not carry, as men go now, but he managed it easily alone. And now Aineias would have crashed down that stone on his helmet, or on that shield which had saved him before, and Peleidês would have chased and killed him with that sword; but Poseidon Earthshaker thought his time was come…

So Poseidon left them, and passed through the battle to the place where Aineias and Achillês were face to face. He drew a mist over the eyes of Achillês; he pulled out the spear from the shield of Aineias and laid it before the other’s feet, whisked up Aineias off the ground and hurled him through the air. Over the ranks of fighting men Aineias flew from the god’s hand, over the lines of horses, and alighted on the outskirts of battle where the Cauconians were getting ready for action.

– Iliad, book XX

This is exactly how I felt while engrossed in my games, praying for me or my team to win.

When you’re watching a Super Bowl and a long toss is sent, you can feel the entire stadium willing that ball to do one thing or another. There is little doubt in my mind that people are hoping for Great Earthshaker Poseidon, or whichever surrogate they pray to, to whisk the ball through the air into the hands of the right mythical hero to make that touchdown.

I got chills reading this next piece; having studied religious liturgy for a good part of my life, I hear clear echoes of my prayers from the Days of Awe.

But when the fourth time they drew near the two fountains, see now, the Father laid out his golden scales and placed in them two fates of death, one for Achillês and one for Hector. He grasped the balance and lifted it: Hector’s doom sank down, sank down to Hadês, and Apollo left him.

At that moment Athena was by the side of Achillês, and she said in plain words:

“Now you and I will win, my splendid Achillês! Now I hope we shall bring great glory to our camp before the Achaian nation, by destroying Hector, for all his insatiable courage. Now there is no chance that he can escape, not if Apollo Shootafar should fume and fret and roll over and over on the ground before Zeus Almighty! Rest and take breath, and I will go and persuade the man to stand up to you.”

– Iliad, book XXII

The imagery of scales is universal. This expression of scales balancing the fate of the two heroes of the Iliad echoes through every confrontation I witnessed, and every request I have ever made in any prayer.

When reading through the Iliad there were points where I could not fathom why this piece was so important, especially when lineage went on for pages. After finishing reading the work I understand more why we must study and cherish the great treasures passed down to us from ages past.

Image credit: Pietro da Cortona

The Privacy / Convenience Polarity is a Myth

There is a myth, that if you want to have privacy, it will be at the expense of convenience; and if you want convenience, it will be at the expense of privacy.

They say that is the way things have to be, but it really doesn’t have to be this way.

Open up your iPhone and go to settings, then open up Privacy > Location Services and see how many apps are using your location “always”. See how many of those apps were just defaulted to “always” and how many require to always have your location. Then ask yourself which of those apps actually NEED to ALWAY have your location?

Here is how this is justified. Let’s use a location recommendation service, like Foursquare or Yelp, as an example.

The pitch is, this location recommendation app gives you value by finding all the great places your friends like.

However, In order for you to benefit from that data you need to enable the location services on your phone. The app then tracks where you, as well as your friends, go. It records all the places you “check in” to. Based on where your friends “check in” and based on the ratings other people who frequent that venue give, you can get the best recommendations everywhere you go.

This app can then sells to advertisers the data it collects. This is the app’s business model. The app sees that you frequent a specific gym. It can then go to the gym across the street and sell them the opportunity to advertise to you, as you go to their competitor. That’s how they pay the bills.

People will tell you that this is the way it NEEDS to be if you want the convenience of getting the best recommendations. 

The problem with this approach is that the more independent services that manage your sensitive data, the more you are open to vulnerabilities. Do you know what systems each individual place that handles your data uses to protect that data?

Why should you care?

In many situations, like what my favorite pizza order is, I am less susceptible to being hurt by a breach of privacy. But that’s not the case with ALL personal data.

What happens when a company that collects your location data goes out of business or is acquired? Any agreement it might have had with you vis-a-vis privacy is can be ignored. When Internet companies go out of business, their data is often the only valuable asset they have left.

Or from the comments of the CDT before the FCC.

Consumers’ dissatisfaction is likely to be heightened when the advertisements arrive from third parties with whom the consumer has not established any relationship. Without awareness of how their location information is being used and who has access to it, consumers will feel as though there is omnipresent surveillance of their activities by companies they do not know. The invasiveness of such advertising increases when the volume and frequency of messages is also outside of their control.

The real issue is that Apple, Android, and Microsoft, the gatekeepers to the location services on our devices, haven’t built their systems properly.

There is a concept in computer science called Data Encapsulation.

Data encapsulation, also known as data hiding, is the mechanism whereby the implementation details of a class are kept hidden from the user. The user can only perform a restricted set of operations on the hidden members of the class by executing special functions commonly called methods. – Wikipedia

(Note: “User” here refers to the classes or methods manipulating the data, i.e. the user of the data.)

This actually is a best practice of software architecture. When your code knows too much about the other components that means that those sections of code are probably dependent upon that knowledge, which means that your code is inflexible, fragile, rigid, and more likely to break.

Let me show you another way location, and other sensitive data could be designed.

Stripe is a payment processor. It’s my favorite to use, because they clearly care about both security and ease of implementation. I.e. they care about the people using their service.

One of the interesting aspects of how they implement their system is that if you use them, your server never has any idea what the purchaser’s credit card number is.

This is a really good thing for developers. If your system handles credit cards you have to make sure your system is PCI compliant otherwise you’re opening yourself up to all sorts of legal fun. Making your system PCI compliant is not easy. Which means that implementing e-commerce can be a challenge… Unless you work with a company like Stripe that already solved that problem for you.

How does Stripe make sure that your server never touches a credit card number?

When you submit a form, the fields in the form have to be named. If the fields are not named the browser simply will not pass the data in those fields to the server. It can’t, because it doesn’t know how to label that data.

Stripe takes advantage of this “feature” and hijacks the submit button. When a purchaser on your site puts in their credit card information Stripe collects all the data in the form securely sends it to their servers and sends back a token and places that token in a proper form field on your site.

Once the data is submitted, the browser doesn’t send the credit card data, because it isn’t named, but it does sent over the token that Stripe created for this interaction.

As a developer you can look up information about that transaction, even about the purchaser. But you can’t have the full credit card number. The purchaser is protected, because there is an impartial third party who is responsible for keeping the credit card information secure. And the site is protected as it does not have to hold sensitive data. But can have all the benefits as if it did save the credit card number. The site has usage statistics, purchase statistics, all the bells and whistles.

This is the beauty of data encapsulation.

Location data should work this way too.

For starters. There should not be an option for services to have location data always on, by default. I’m saying this as a developer fascinated by location-centric apps. Location data should be as protected as credit card information. There is no excuse for that.

The creators of the operating systems should be the gatekeepers of our location data. If they were serious about security this should be the next front line. They already collect and record the data if it is enabled, they should be the only ones.

Apple Pay, Google Wallet, these are all big targets because they have huge revenue potential. They also make things safer. A pay-per-use location API would be too (there are many affordable ways to make pay-per-use services, see Mailchimp.)

There should be a PCI SCC equivalence for location data. There should be a council looking out for your privacy and making sure that others hold to those standards.

This probably won’t happen, people don’t seem to care enough.

But don’t listen when people tell you it has to work this way.

Image Credit: Dizzy Fripper