Movie rental refactor challenge

I got this refactor challenge for a simple ruby script that has 3 objects and produces a statement. In effect we have a Movie object, a Rental object and a Customer object. The purpose of the script is to print out a statement with the customer’s name, order, amount due and frequent renter points.

The code that I received for refactoring has syntax and other errors, which after a quick email exchange I found out where put there intentionally. So it’s more of a fix the code challenge rather than a refactor job, but I did both. Underneath you’ll see the snippets of the code I got:

class Movie
  CHILDRENS_MOVIE = 2
  REGULAR = 0
  NEW_RELEASE = 1

  attr_reader :title_for_movie
  attr_accessor :price_code

  def initialize(title_for_movie, price_code)
    @title_for_movie, @price_code = title_for_movie, price_code
  end
end
class Rental
  attr_reader :movie, :days_rented

  def initialize(movie, days_rented)
    @movie, @days_rented = movie, days_rented
  end
end

And the problem object

class CustomerClass
  attr_reader :customer_name

  def initialize(customer_name)
    @customer_name = customer_name
    @rentals ||= []
  end

  def add_rental_object_to_list(arg)
    x = 7
    @rentals << arg
  end

  def statement
    total_amount, freqent_renter_points = 0, 0
    result = "Rental Record for #{@customer_name}\n"
    @rentals.each do |_element|
      this_amount = 0

      # determine amounts for each line
  case _element.movie.price_code
  when Movie::REGULAR
    this_amount += 2; this_amount += (_element.days_rented - 2) * 1.5 if _element.days_rented > 2
  when Movie::NEW_RELEASE
    this_amount += _element.days_rented * 3
  when Movie::CHILDRENS_MOVIE
    this_amount += 1.5; this_amount += (_element.days_rented - 3) * 1.5 if _element.days_rented > 3
  end

      # add frequent renter points
      freqent_renter_points += 1
      # add bonus for a two day new release rental
      freqent_renter_points += 1 if _element.movie.price_code == Movie.NEW_RELEASE && _element.days_rented > 1

      # show figures for this rental
      result += "\t" + _element.movie.title_for_movie + "\t" + this_amount.to_s + "\n"
    total_amount += this_amount
    end
    # add footer lines
    result += "Amount owed is #{total_amount.to_s}\n"
    result += "You earned #{freqent_renter_points.to_s} frequent renter points"
    result
  end
end

At first glance we can see that we are dealing with a renting operation in which a customer chooses one or more movies to rent and gets billed accordingly.

We can see from a glance that the customer class is pretty much a mess. We have an unnecessary variable (x = 7) , we have bad variable and method names “add_rental_object_to_list(arg)” , an improper constant call “Movie.NEW_RELEASE” , a couple of typos and worst still:

# We have code comments
# Now for those of you that are new to my blog
# or are simply curious as to why I am so opposed to comments
# the reason is twofold and boils down to this:
# 
# The existence of code comments is proof of hard to understand code
# and hard to understand code logic.
# If you need to add comments to your code
# to make it readable, chances are you need to refactor more.
# 
# And secondly, I have yet to meet a developer that once tasked with
# making changes to commented code will take the time to 
# improve and change the comments so that they now reflect the new 
# code reality. So what happens is that by the time the third developer
# comes up to the code, the comments say one story because they are outdated
# and the code tells a whole other story.

Now, let’s move on to how I made the code, and look under the hood a bit

class Movie
  CHILDRENS_MOVIE = 2
  REGULAR = 0
  NEW_RELEASE = 1

  attr_reader :title_for_movie
  attr_accessor :price_code

  def initialize(title_for_movie: title_for_movie, price_code: price_code)
    @title_for_movie = title_for_movie
    @price_code = price_code
  end
end
class Rental
  attr_accessor :movie, :days_rented

  def initialize(movie: movie, days_rented: days_rented)
    @movie = movie
    @days_rented = days_rented
  end
end
class Customer
  attr_accessor :customer_name

  def initialize(customer_name: customer_name)
    @customer_name = customer_name
  end
end

Now you must be wondering ‘what happened to all the code logic from the customer class?’

Well I extracted out all that business logic and placed it all inside an Interactor. I did this because all business logic should be extracted and separated from ruby/rails logic. I like to keep my public objects as plain and as dumb as humanly possible. I guess you have heard of the paradigm, ‘slim model fat controller’ or others put it as ‘slim controller fat model’. I for one prefer to keep all my main public objects as slim and as dumb as possible.

I know what you’re thinking, ‘model? controller? what does rails logic have to do with a ruby script?’ and you’d be right. But I am putting out an idea. and as I’ve said it before in a previous post the business logic of your app should be extracted and tested separately. This has many advantages including: a more modular design, easier to read code, easier to extend and maintain, easier to refactor etc.

So first I’ll put the tests

require 'spec_helper'
require_relative '../interactors/set_price_and_bonus_points'
require_relative '../bin/rental'
require_relative '../bin/movie'
require_relative '../bin/customer'

RSpec.describe Interactors::SetPriceAndBonusPoints do
  let(:new_movie)       {Movie.new(title_for_movie: "Jaws", price_code: Movie::NEW_RELEASE) }
  let(:kids_movie)      {Movie.new(title_for_movie: "Incredibles 2", price_code: Movie::CHILDRENS_MOVIE)}
  let(:regular_movie)   {Movie.new(title_for_movie: "Avengers", price_code: Movie::REGULAR)}
  let(:new_rental)      {Rental.new(movie: new_movie, days_rented: 2)}
  let(:kids_rental)     {Rental.new(movie: kids_movie, days_rented: 4)}
  let(:regular_rental)  {Rental.new(movie: regular_movie, days_rented: 2)}
  let(:customer)        {Customer.new(customer_name: "Robert")}

  describe 'calculates and prints out a statement' do

    it 'returns 0 amount and 0 bonus points if no movie is rented' do
      expect(Interactors::SetPriceAndBonusPoints.call([], customer)).to eq "Rental record for Robert\nAmount owed is $0\nYou earned 0 frequent renter points"
    end

    it 'can calculate a price and bonus points awarded for a new release movie rented for 2 days' do
      expect(Interactors::SetPriceAndBonusPoints.call([new_rental], customer)).to eq "Rental record for Robert\nAmount owed is $6\nYou earned 2 frequent renter points"
    end

    it 'can calculate a price and bonus points awarded for a kids movie rented for 4 days' do
      expect(Interactors::SetPriceAndBonusPoints.call([kids_rental], customer)).to eq "Rental record for Robert\nAmount owed is $1.5\nYou earned 1 frequent renter points"
    end

    it 'can calculate a price and bonus points awarded for a kids movie rented for 2 days, and it should cost just as much as for 4 days' do
      new_kids_rental = Rental.new(movie: kids_movie, days_rented: 1)
      expect(Interactors::SetPriceAndBonusPoints.call([new_kids_rental], customer)).to eq "Rental record for Robert\nAmount owed is $1.5\nYou earned 1 frequent renter points"
    end

    it 'can calculate a price and bonus points awarded for a regular movie rented for 2 days' do
      expect(Interactors::SetPriceAndBonusPoints.call([regular_rental], customer)).to eq "Rental record for Robert\nAmount owed is $2\nYou earned 1 frequent renter points"
    end

    it 'can calculate multiple rental bonus points and a prices added up' do
      expect(Interactors::SetPriceAndBonusPoints.call([new_rental, kids_rental, regular_rental], customer)).to eq "Rental record for Robert\nAmount owed is $9.5\nYou earned 4 frequent renter points"
    end
  end
end

And here is the actual code

module Interactors
  SetPriceAndBonusPoints = lambda { |rentals, customer|
    amount_owed = 0
    frequent_renter_points = 0
    result = "Rental record for #{customer.customer_name}\n"
    rentals.each do |rental|
      individual_film_amount = 0
      if rental.movie.price_code == Movie::NEW_RELEASE
        individual_film_amount += rental.days_rented * 3
        rental.days_rented > 1 ? frequent_renter_points += 2 : frequent_renter_points += 1
      elsif rental.movie.price_code == Movie::REGULAR
        rental.days_rented > 2 ? individual_film_amount += (rental.days_rented - 2) * 1.5 : individual_film_amount += 2
        frequent_renter_points += 1
      else rental.movie.price_code == Movie::CHILDRENS_MOVIE
      rental.days_rented > 3 ? individual_film_amount += (rental.days_rented - 3) * 1.5 : individual_film_amount += 1.5
      frequent_renter_points += 1
      end
      result += "\t" + rental.movie.title_for_movie + "\t" + "$" + individual_film_amount.to_s + "\n"
      amount_owed += individual_film_amount
    end
    result += "Amount owed is $#{amount_owed}\n"
    result += "You earned #{frequent_renter_points} frequent renter points"
    result
  }
end

I extracted all the logic in this lamba function that you can conveniently call as such:

Interactors::SetPriceAndBonusPoints.call([new_rental, kids_rental], customer)

and it will print out the following:

Rental record for Robert
        Jaws    $9
        Incredibles 2   $1.5
        Avengers        $1.5
Amount owed is $12.0
You earned 4 frequent renter points

You can find the code repo here and also other code snippets and scripts.

Have a splendid week!

How To write an Armstrong number checker

Hello there, and for those of you who have read my previous work, welcome back.

Now, what is an Armstrong number:

“In recreational number theory, a narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong) or a plus perfect number) is a number that is the sum of its own digits each raised to the power of the number of digits.” – wikipedia

So in layman terms, a three digit number abc is narcisistic if a^3 + b^3 + c^3 = abc.

Before we go through the code let’s analyze what we need to do. We need a number to check, we need to find out how many digits it has, we need to raise each individual digit to the power of how many digits there are, add them up and check to see if it’s equal to the original number.

So down below you will see a little script that checks if a number is an armstrong number or not. After we will go through the code line by line to understand what each bit of code does what.

class Armstrong

  def check_user_number
    puts "Enter any number for check: "
    user_input = gets.chomp.to_i
    is_narcissistic?(user_input)
  end

  private

  def is_narcissistic?(user_input)
    all_digits = user_input.to_s.chars.map(&:to_i)
    number_of_digits = all_digits.count
    raised_to_power = all_digits.map {|a| a ** number_of_digits}
    if raised_to_power.inject(0) {|sum, x| sum + x} == user_input
      puts "your number #{user_input} is a narcissistic number"
    else
      puts "it's not a narcissistic number"
    end
  end
end

Armstrong.new.check_user_number

Now we have one class and just 2 methods inside it. The first method is pretty straight forward and doesn’t need to much explaining. It just greets the user, asks for an input, takes that input, turns it into an integer  and passes it to the is_narcissistic? method to be checked.

So in essence the first method – which is public – holds the interface, and the second method – which is private – holds the business logic.

Now onto the second method.

def is_narcissistic?(user_input)
    all_digits = user_input.to_s.chars.map(&:to_i)
    number_of_digits = all_digits.count

The first line of code just take the user input and turns it into an array of integers corresponding to the digits of the number. so for example 153 will be turned into [1, 5, 3] and saves that array into the variable “all_digits” because we will use that later on.

The second line of code counts the number of digits inside the array and saves that in a variable called “number_of_digits” because we will need this number to be able to raise to power the individual digits inside the “all_digits” array.

The third line of code:

raised_to_power = all_digits.map {|a| a ** number_of_digits}

This line of code maps over the array “all_digits” and raises each and every one of them to the power of the “number_of_digits” and saves that inside the “raised_to_power” variable.

The last five lines of code does the check against the original number

if raised_to_power.inject(0) {|sum, x| sum + x} == user_input
  puts "your number #{user_input} is a narcissistic number"
else
  puts "it's not a narcissistic number"
end

It does this with a simple if/else statement in which it checks if the sum of the “raised_to_power” digits is equal to the original “user_input” in which case it prints a statement that tells the user that it truly is a narcissistic number or a statement that it’s not.

And that is all there is too it. Now, do you think you could write up a new program that uses the above code to find out all the narcissistic numbers in a range of, let’s say [1..999] ?

Have a great week!

How To Write a Custom Decoupled CSV Importer

Hey there! Last time I spoke about how to add a bit of microservices style architecture flavor to your monolithic app and the benefits of doing it in such a way. Now I’m going to go through a concrete working example of a modularly built, ‘plug-in and play’, intuitive and reusable CSV importer. We’ll have it import a Post object for our blog

To start things off let’s look at what we’ll need and what we’ll be doing. we’ll be doing it the TDD way so we’ll have a spec file, a importer file, a ImportPostsController and it’s subsequent route and also a rake task for mass imports.

Go to your filetree, right click app and create a new directory called ‘data_importers’. Inside it place the importer.rb file. This is where you’ll put your importer code. Do the same for the spec and create you’re importer_spec.rb file where you’ll host your tests.

Normally you’ll go the lines of red, green, refactor path, but to keep this as short as possible I’ll just put in the whole importer_spec file in it’s entirety followed by the importer file.

require 'rails_helper'
require 'ostruct'

class ModelMock < OpenStruct
  def save
    true
  end
end

RSpec.describe DataImporters::Importer do

  it 'can be instantiated with a file path' do
    importer = DataImporters::Importer.new file: 'data/export.csv'
    expect(importer.file).to eq 'data/export.csv'
  end

  it 'can be instantiated with a hash of source and target fields' do
    importer = DataImporters::Importer.new field_mappings: { target: :source }
    expect(importer.field_mappings).to eq({ target: :source })
  end

  it 'can be instantiated with the ActiveRecord model that will hold the data' do
    importer = DataImporters::Importer.new import_to: OpenStruct
    expect(importer.model).to eq OpenStruct
  end

  it 'the import method returns false if the file doesn\t exist'  do
    importer = DataImporters::Importer.new import_to: OpenStruct,
                                           field_mappings: { target: :source }
    expect(importer.import).to be_falsey
  end

  it 'the import method returns false if the model doesn\t exist'  do
    importer = DataImporters::Importer.new file: 'data/export.csv',
                                           field_mappings: { target: :source }
    expect(importer.import).to be_falsey
  end

  it 'the import method returns false if the field_mappings are wrong'  do
    importer = DataImporters::Importer.new file: 'data/export.csv',
                                           import_to: OpenStruct
    expect(importer.import).to be_falsey
  end

  it 'the import function returns the number of successful imports' do
    allow(CSV).to receive(:foreach)
                      .and_yield({csv_name: 'John', csv_email: 'john@example.com'})
                      .and_yield({csv_name: 'Dan', csv_email: 'Dan@example.com'})
    importer = DataImporters::Importer.new file: 'data/export.csv',
                                           import_to: ModelMock,
                                           field_mappings: { name: :csv_name,
                                                             email: :csv_email}
    allow(importer).to receive(:file_exists?) { true }

    result = importer.import
    expect(result[:success]).to eq 2
  end

  it 'the import function returns the number of failed imports' do
    class ModelMock
      def save
        false
      end
    end
    allow(CSV).to receive(:foreach)
                      .and_yield({csv_name: 'John', csv_email: 'john@example.com'})
                      .and_yield({csv_name: 'Dan', csv_email: 'Dan@example.com'})
    importer = DataImporters::Importer.new file: 'data/export.csv',
                                           import_to: ModelMock,
                                           field_mappings: { name: :csv_name,
                                                             email: :csv_email}
    allow(importer).to receive(:file_exists?) { true }

    result = importer.import
    expect(result[:failure]).to eq 2
  end
end

 

And here is the importer.rb file that makes the test pass:

require 'celluloid/current'

module DataImporters
  class Importer

    attr_reader :file, :model, :field_mappings, :print_progress

    def initialize(file: '', import_to: nil, field_mappings: {}, print_progress: false)
      @file = file
      @model = import_to
      @field_mappings = field_mappings
      @print_progress = print_progress
    end

    def import
      return false unless valid_input?
      result = { success: 0, failure: 0}
      CSV.foreach(file, headers: true) do |record|
        save_to_model(record) ? result[:success] += 1 : result[:failure] += 1
        puts "Imported #{result[:success]}" if print_progress && (result[:success] % 100 == 0)
      end
      result
    end

    private

    def valid_input?
      file_exists? && model_exists? && field_mappings_exist?
    end

    def file_exists?
      File.exist? file
    end

    def model_exists?
      model != nil
    end

    def field_mappings_exist?
      field_mappings != {}
    end

    def save_to_model(record)
      m = model.new parse(record)
      m.save
    end

    def parse(record)
      result = {}
      field_mappings.each do |target, source|
        result[target] = record[source]
      end
      result
    end

  end
end

Now to use this, we create a rake task where we invoke the logic. We can use this rake task via the server console and import a multitude of records via one single task.

require File.expand_path('../config/application', __FILE__)

Rails.application.load_tasks

desc 'Import My Posts'
task :post_import => :environment do
  file = Rails.root.join 'posts.csv'
  field_mappings = {
      title: 'Title',
      user: 'User',
      text: 'Text'
  }
  importer = DataImporters::Importer.new file: file,
                                         import_to: Post,
                                         field_mappings: field_mappings,
                                         print_progress: true
  result = importer.import
  puts "Successfully imported #{result[:success]} records. #{result[:failure]} failures"
end

For individual imports we just create a ImportPostsController where we invoke the importer logic, create a route for it and add the link in the UI so that an individual user can do it. But this post is getting kind of long, so we’ll do that in a future article

Applying Microservices Style Architecture to Monolithic Apps

Def: Microservices is a software development technique—a variant of the service-oriented architecture (SOA) architectural style that structures an application as a collection of loosely coupled services. – wikipedia

“A collection on loosely coupled services”. Bit of a brain twist. Ok, loosely coupled we get from the get-go, it’s good software practice and design, but what do they mean by “services”.

Well, first and foremost, to understand this development technique we have to peel off all the layers and go to the core. It’s a very specific type of software development that, in my opinion, is meant to handle a very specific problem – accessing more libraries from more than one language. In other words, having the capability to evolve the technology stack.

In a traditionally styled monolithic app you can (but shouldn’t) chunk everything inside one place. And that would work just fine so long as you never have to touch or change the code ever again after you’re done with it. Sometimes you can see this in practice in hackathons.

But people are smarter than this. They realized long ago that this method is inefficient and came about with rules that govern software architecture and good coding practices. And as such they learned through practice that it’s good to apply the SOLID principles to the code base, and to make it all more palpable to human readers, have a file tree structure that separates code structure in a modular design pattern. And this works just fine. But what happens when you’ve grown and grown and now you’ve got over 50 developers working on your monolithic app?

Things get hard. Constraints start becoming obvious. You can only use one language and are limited to it’s libraries. It’s harder to separate work done into teams. One team’s work that is seemingly finished might be dependent on another team’s separate work and as such they cannot push and merge their tickets separately. Asynchronous development becomes impossible.

So what can you do in this situation? One popular solution is to split up your app into several servers or “Microservices” that can have their own specific language each, specific access to libraries, own development team that can fully concentrate on just one part of the business, and of course – to be truly a microservice – it’s own database.

Obviously drawbacks exist when doing it this way.

– You can either go about having the separate services communicate between each other synchronously – meaning that each separate service can call the other directly and as such are more tightly coupled (harder to change in the future).

– Or you can go the asynchronous way where you have a PUB/SUB style of message queues where a receiver takes a request, does something with it and returns a result to the caller. Some popular ways of achieving this is by using RabbitMq or Apache Kafka.

The second method is unavoidable if you truly want to go the microservice way. Yet oftentimes I’ve spoken with developers at meetups and conferences and they’ve told me that they use microservices, but without a PUB/SUB style of communication between them, or that they have 6 separate servers up and running, but only one common database between them.

In recent months I’ve come to an idea as to why so many people would go the microservice way, but not in it’s entirety like in above examples.

You see, having two or three or more separate servers forces you to write code inside them in a very specific way. For instance you can’t chunk everything inside one place. Another thing is that it forces you – at least in the beginning – to write decoupled code. And that’s good and all, but it never lasts, it never ends up fulfilling what it sets out to do. They set out to do it this way as a means to force themselves to write code in a good structured and orderly fashion. But that is kind of like donating your personal car so that you walk around more and get more exercise. It works in theory, but not so much in practice. What I’m saying is that only a fraction on businesses that set out to use microservices actually need it for objective reasons.

So what would be the best route to go? I for one strongly advocate a strong separation of logic in your app. Grab a pen and paper, write down the essential elements of your app and take a step back and look at the bigger picture.

Let’s say for instructional purposes you have a business that offers publishing capabilities for your customers who are accountants. That would be your USP or unique selling proposition. Other that that you have to offer log in and log out capabilities – thus a users class – a good database solution, some simple and intuitive UI and also a possible means of that said user to read and write posts. And you decide to offer all this over the Internet and as such you choose to do a webapp.

So you have a User class, and Posts class. The MVC for User and Posts is very straight forward and at least for Users you have third party out of the box solutions, “Devise” for rails apps being a pretty good choice. Up until now your customers love the simplicity of the design, but they want to do even more. They want to be able to upload CSV’s directly onto a new Post.

How should you go about it? You could just clump the logic inside the PostsController?

You can go about it that way, but it’s bad practice and here’s why:

– It overcrowds the controller. It should only hold CRUD actions in the public interface and if need be, more specific methods in the private interface.

– It sets a bad example to your other coworkers. If they have to add other features related to Posts, they’ll just follow your example and extend the PostsController until probably one day soon it will be too cluttered and tightly coupled, impossible to extend, refactor or change.

So what are you gonna do instead? You’ll create a separate file in your app directory called data_importers. In it you’ll place your posts_importer.rb file. You’ll start with TDD and create a posts_importer_spec.rb. By doing red, green, refactor you’ll soon end up having the route, the UI link and necessary pages and good test coverage.

The idea behind this is simple. Act as if what you want to add to your base functionality is “external logic”, and implement it as such. Do it in a modular way that is individually tested and has integrations tests on top. If down the line this functionality needs to be expanded, changed or even tossed out, it will be very simple to find the place to do the change. And you can change with confidence knowing that what you touch upon is in it’s entirety in one place and you won’t break something somewhere else.

Doing this you’re file directory will start to look like a microservice oriented application, but instead of separate servers, you have separate folders. Any developer can – at a quick glance and without checking the code in depth – understand what the app does and how it goes about to do it. Business logic becomes apparent, custom logic is easy to find and read, and core structures of your app are left as dumb and as simple as possible.

And if one day your business grows to the point where a monolithic app just doesn’t cut it anymore, you can charge with confidence in the microservices direction knowing that you can structure your code in a intuitive way that is simple to maintain and straight forrward to extend.

Finding And Promoting Abstractions In Your Code

Throughout my posts and in many many other articles, books, booklets and almost all (good) IT materials, you keep hearing the same over and over again, repeated almost like a mantra – “Find the abstraction and use it” – it’s good and all, but how you should go about it is almost always lacking in the explanations.

Now don’t take this as if I’m trying to dis my fellow authors – I most certainly am not – it’s just that – from my own personal experience from when I was a fledgling programmer tackling the great sea of code- people have a very hard time wrapping their heads around something so “abstract” as abstractions. I know I know, I used the adjective to describe the noun, something akin to recursion but not quite. Just leave it at that.

So what are abstractions?

Def: “abstraction is a technique for arranging complexity of computer systems. It works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level. The programmer works with an idealized interface (usually well defined) and can add additional levels of functionality that would otherwise be too complex to handle.” – wikipedia

In layman terms, an abstraction – in computer programming sense – represents the essence of the object, or more simply put: “That which it cannot do without”. It it the core of the functionality, or even more simply put: “it is that which defines the system with the least words possible”.

If you are a first time reader, then you may not be accustomed to my enforced practice of stating that programming is the craft of modeling real world events and interactions and as such, most of the principles and ideas that govern programming are based on real world paradigms, principles and examples that were taken and reapplied in code.

That being said. What are abstractions?

To better help you understand I will illustrate to you the greatest abstraction I know off, and for that we shall make a small exercise in writing.

Class Humanity
 Def human_being
  person
 end

 def person
  unless assign_male
  assign_female
 end

 private

 def assign_male
  #...
 end

 def assign_female
  #...
 end
end

 

Now the code I have wrote is childish, but the point it’s leading to is not. So from the example I have given, you could extract the fact that the human_being is the abstraction (since it was conveniently placed in the top level and public interface) and the assign_male and assign_female methods are the complexities of the code that are built up on the abstraction.

But if you stop, just for a short moment, and think about it, really take a second and chew down, to the bone, there is an even higher level abstraction.

And if you can understand that high level abstraction, then you can really begin to contour the logic behind any and all abstractions and how they exist in the first place. If I’m still sounding mysterious then think of this.

To exist, what does a human being need in the first place? How did the human_being come to be instantiated?

“Third Planet from the sun”. It’s planet Earth.

You see, Mother Earth, in all it’s bountiful generosity and love, manages all dependencies. In it’s absence there could be no humanity. You see, Earth, as the abstraction, defines all rules, laws and objects upon which we as human beings depend upon. Small, but very important things such as air and oxygen, water and fire, plants and inanimate objects. It is the sole high level abstraction and we are the complexities built upon it. We convey specificity and application to a very vast and base set of rules.

If I lost you just now – and you might be justified in thinking that “hey, this is not coding” – you’d be right. But I am not explaining a coding concept. I am conveying to you an idea. I want you to understand the base idea upon which the “abstraction in programming” is based. If I can succeed in teaching you how to visualize the concept of abstraction, then you will never ever be bogged down navigating through your – or anyone else’s – code.

In ruby, the highest (or more commonly put “top level abstraction”) is BasicObject. You can think of it as Mother Earth. Every other object – whether predefined or defined by you – inherits from this top level abstraction.

You can think of it (and of all abstractions in general) as the environment. The one place in which all other object live in.

So the next time you are defining a class, think onto yourself. What is it that this class cannot do without, what does it all boil down to, and doing so you’ll have won half the battle in extracting abstraction. The other half is all about setting up your code on the right kind of abstractions. But more about that in another post.

Modules and the Method Lookup Path

In the previous post “Organizing Your Code With The Help Of Modules” we created our very first outline of a module (though very basic) and mix it in a class via the include method (in this case we can refer to modules as mix-ins).

If you haven’t noticed by now, the act of mixing in a module strongly resembles inheritance from a superclass. So to say that if class Second inherits from class First, then instances of class Second can call the instance methods of class First. In the same way, if for example class Third mixed in module TheModule, instances of class Third can now call the instance methods of module TheModule.

The similarities in both cases congeal in the fact that the instances of the class at a lower level (the one that inherits, in our examples being class Second for classical inheritance and class Third for mix-ins) get to call both their own methods (as defined inside the object) but also those externally defined in class First (superclass object) or TheModule (mixed-in module).

Now you might ask “what’s the point of having both if they act the same?”.

Well although they act the same, they do not impose the same limitations. You see, you can mix in more than just one module. Remember that in classical inheritance in OOP, you only ever inherit (directly) from one parent or superclass via an established class hierarchy. To be able to inherit from more than just one, you need to inherit (indirectly) from an ancestor (the superclass of the superclass). But there is a limit of how high (or how low, depending on what you focus on) you can go without incurring heavy penalties.

So want should a programmer do in case you want or need numerous extra behavior in a class? Well, you tuck all the extra bits neatly away in modules. This helps with maintenance since you break up multiple jobs in simple components that are clear and unconfusing. It also helps DRY out your code since you can (and probably should) use one module in more that one class, depending on requirements. Now each module brings something new to the table (to the class) and together they get the job done.

Now onto the next issue at hand. You know from personal experience that methods tend to share names. And also from personal experience you know that this is important because you always want to receive the method you want to call. To do this, let’s take a quick glance at how Method Lookup works?

You have an object. This object receives a message. Now this object needs to figure out some things. It needs to figure out: a) “Can I respond to this message?” and b) “If yes, How should I respond to it?”. So if our object receives a request to resolve a message into a method, it will search, in order, in these following places:

  • Look for it in its own class
  • Looks for Modules mixed into the class then checks inside the Modules in reverse order of inclusion
  • Looks for it inside the class’s superclass
  • Looks for Modules mixed into the superclass and then checks inside the Modules in reverse order of inclusion
  • If all fails, it then looks inside class Object , then inside it’s mix-in Kernel and finally inside BasicObject (the final superclass)

Let’s follow that lookup path with an example

module FriendlyModule
 def greet_reader
  puts “What's up doc?”
 end
end


class InheritedClass
 include FriendlyModule
end


class MyClass < InheritedClass
end

obj = MyClass.new

obj.greet_reader => “What's up doc?”

 

So how did the magic happen?

Well it all began when our object conveniently named obj was suddenly and abruptly woken up by receiving a message to call a method. So it jumped up and said:

“I’m an instance of my class, MyClass. Does the class I reside in contain a greet_reader method?”

=> No, it does not.

“Okie dokie, then does MyClass include any modules I can look in?”

=> No, it does not.

“Fine, then does MyClass ‘s superclass (InheritedClass) have the method definition?”

=> No, it does not.

“O.k, o.k the does InheritedClass include any Modules in it?”

=> Yes, it does indeed include the module FriendlyModule.

“And does FriendlyModule define a greet_reader method?

=> Yes, it does indeed define a greet_reader method

“Alrighty then, I’ll execute it!”

Had the obj ‘s search ended up in failure, it would have triggered method_missing which gets called as a last ditch effort in case of an “unmatched message”.

The example I gave is pueril and just at a quick glance you can see what method the object can call. But the same steps are traversed even with big Classes and Modules in huge aps. Knowing how the Lookup works can really save you allot of hassle when working with legacy code, or wore, Monolith aps.

But we’ll check out more about models and their usefulness in another post.

Organizing Your Code With The Help Of Modules

We know about classes and how they are an Object defined to “huddle up” like minded or similarly goal oriented objects (namely methods) and we know about class hierarchies, the perils that it imposes on our code through the thing called classical inheritance and how namespacing matters because the names we choose for our objects pose both rewards and great peril by threatening to pollute the global namespace.

So why am I bringing all this up?

Well, because it is time to take a closer look at our next great programming tool: Modules.

I’ll use this post as a starting point to branch out in a greater series of articles concerning Modules, why we need them, how to use them, benefits and limitations, among other things.

So what is a Module? I could tell you that a module is a part of a program. Or that it acts like a component of an application that shines at runetime. But in layman terms, a Module is just another way of grouping classes, methods and constants, objects that are like minded enough or serve the same purpose (work together to get the same job done). Mind you, it is only the Beholder (the author or user of the module and subsequent code) that determines that the Module is composed of code that serves the same purpose. The machine is oblivious to that fact. For it, it is all the same regardless.

If by now you’ve noticed the similarities between Modules and Classes, know that in Ruby for example the class Class is a subclass of the class Module. This means that every class object has the class as it’s parent (from which it inherits directly) and the Module as an ancestor (from which it inherits indirectly).

Now time for the differences. The most important one being that modules do not have instances. For you to grant it access to an instance you must specify that you desire to add the functionality of one particular module to the functionality of a class or a specific object. Think of it in terms of Module being the abstraction and Class being the specialization.

Okay, armed with that little bit of knowledge you’ll ask: “Why bother using them in the first place”?

The short answer is that modules exist to help you with program design and flexibility since modules (as the real world borrowed name implies) encourage modular design – a breaking apart, sorting and separating of large components into smaller, more manageable ones that you can use to mix and match object behavior.

Now if we already know that all objects “descend” from Object (which in turn descends from BasicObject) then this know that the majority of methods common to all objects (the base methods of the language) live – inside module Kernel.

Before I leave you hanging, let’s take just a quick look on how you define a Module.

module FriendlyModule
 def greet_reader
  puts “Hi there!” 
 end
end

 

So you do it just like you would define a class, albeit by substituting your starting definition of class for the keyword “module”.

But hold up just one second. We established that modules do not have instances. So how can we use our ExampleModule?

To use it, we’ll have to include it in a class object. Doing so we grant access in that class object to the the functionality existing in the Module, like so

class TheAuthor
 include FriendlyModule
end

ta = TheAuthor.new # instantiation
ta.greet_reader # => “Hi there!”

 

We’ll go in deeper, but for now we’ll leave it at that. One last thing though. Modules that are included like such are sometimes referred to as “mix-ins”.

Incremental Software Development Or Why Big Achievements Are Done Through Small Steps

If you’re a hardcore software developer, a journeyman set on the noble path of software design and implementation, or you’ve just started out on this great journey, chances are you’ve hit a snag in the road while getting accustomed to continuous code implementation. And if you work as part of a team, where more people than just yourself add to the codebase, then I know for sure you’ve had this problem.

In case I still sound mysterious, I’m referring to development problems arising due to asynchronous programming & software development.

First let’s identify the problem with a simple common example.

You work at a mid to large level company. You are part of a mid to large team, let’s just say somewhere around 20 developers. New requirements trickle down from the CEO and management down to team leads and then work gets assigned to you and your colleagues or you choose those assignments yourself. Whichever the case, tasks are taken and given and the job starts rolling.

For performance and tracking issues, you use a story board system, let’s say Pivotal-Tracker or Blossom. And you should. Numerous tasks are required, some are fast implementation types like small bugs and hot fixes while others represent major overhauls of previous functionalities, redesign or even new functionalities all together. Even still, some of your colleagues might not be in the same office, instead working remote from other parts of the world, in vastly different time zones. So tracking is essential.

Management assigned points based on difficulty of task and time estimation for delivery. And you get to work.

In case the problem hasn’t started being obvious, it has everything to do with team moral and overall productivity.

So how many points should be attributed to a story? 1 point, 2 points, 5 points. You might think that all depends on the difficulty of the task at hand and as such the time it will require to finish. But you’d be mistaken. So how many points should be attributed to a story?

Answer: Just 1 point. That’s it. Just 1 point on any story. Well, in all actuality, it is irrelevant, it could be 5 points at that and still make no difference. So long as all stories get assigned the same number of points. Why? We’ll touch on that a bit further down.

Secondly. How should tasks be assigned? How should assignments be attributed? Should Management be solely responsible for task assignments? Or should the developers themselves be responsible with task attribution?

There are no cut-out perfect scenarios, and like most things in life, the “perfect” solution can only be picked taking into account the particularities of each individual situation. In most cases, it implies a bit of both. So how does a perfect system look like?

Management and the sales team take time and discuss options with clients. They take a pen and paper or even better still record the meeting. In it they ask as many questions as possible about what the client wants.

The reason this is important is because, as most of you know already – or will learn soon enough via the hard and painful way – most users & clients do not know what they want. Sure, they have an idea, but for lack of a better word, they are oblivious as to what they want. Why? Because they do not know what they need and what are the requirements for that to happen – namely if they are feasible (meaning doable) requirements in the first place.

Management takes the hand written notes or a transcript of the conversation and passes it around to the entire dev team. After careful documentation, the dev team gives valuable input and feedback on what is possible to implement, what is impossible, what is easy to do (meaning cheap) and what is hard (long and expensive).

I am well aware that for you, this scenario might be out of your hand since it requires a significant level of active participation from management and from the rest of the development team.  So let’s check the next step which isn’t.

What comes next, after the goals are set and the tasks published on the story board, is to decide who gets what.

First, tasks should be put up on order of priority. What has priority can only be decided based on each individual team’s and company’s requirements.

After that, each individual dev should pick for himself a task, in order of priority, and based on his or her personal experience (strong points and weak points).

If this makes sense for you, then we will move to the next, and arguably more important step.

How should stories be published?

In my infant stages as a fledgling developer I had a story unanimously attributed to me by management. It was a complete redesign of a very important part of the companies application, the users management page. 3 points were assigned and after I branched of off develop I got to work. Nearly Two months and over 200 commits later I was almost done. All that was left were the merge conflicts to deal with. For lack of a better word, I found the whole experience akin to a nightmare.

Although I was making good progress, and spending regular hours making important progress, I was always left feeling dejected and left behind. I could not stop questioning my skill and capabilities as I was constantly seeing my colleagues pushing and merging new features in a fast paced manner leaving me questioning my performance and value to the team.

Looking back now, and knowing what I know know, I fared remarkably well given the situation. So what was the problem?

To put it simple, the ticket was huge. It was way to big. And before you point out the now obvious solution, a question arises in the minds of many developers and management personnel alike – what did you expect? It was a single task that had to be done completely from beginning to end. True enough. But I’ll still say it.

Tasks should always be split up in individual components? A task should be defined by the implementation of a single job or feature. If that sounds familiar to you, yeah, you’ve guessed it, it is the Single Responsibility Principle in application in a real world scenario.

As I’ve stated before, all these programming principles are modeled after real life practices since programming, as a profession, models real life events.

So this is how you should “attack” stories from now on. Break them up in the most small components as possible. In my example the story should have bees written up as such.

1 Base story containing the generic title and requirements – Redesign of User’s Management page.

Them a multitude of multiple stories containing each and separate functionality, or job.

  • 1 story dealing with users reclassification and iteration on index. ( who are account administrators and who are general purpose users)
  • 1 story dealing with each individual users edit page.
  • 1 story dealing with each individual users show page.
  • 1 story dealing with small UX design upgrades.
  • 1 story dealing with final front-end design touches.

There could be more, but you get the point.

Now the benefits to this system are two fold.

First, in case of multiple developers tackling the same task and working together, they can separate work amongst each other.

Secondly, even if only one user does the whole task, he can now handle it in an incremental fashion. He is forced to focus on each task at a time.

He is also seemingly more productive since he pushes and opens pull requests on a daily or weekly basis instead of one giant merge at the end.

Morale is boosted and performance is increased as a result.

Management has a far better tracking of the situation. Deadlines can now be set and promises can be kept.

It is a win-win situation on all fronts. Developers get to shine and be productive and “unconfused” about their work related requirements and Management gets to score big with clients and users.

To translate this entire post in layman terms, work should be done as follows:

Client requirements should be received with as mush detail as possible.

Stories should be separated in low hanging fruits (the meat and potatoes part of the business) and “high risk – high reward” tasks (the specialization of your application)

Further down, each individual story should be further broken down to it’s bare parts, it’s most basic components and these should be made into stories of their own.

Tickets should be published on the story board in order of priority, with the most urgent ones at the top.

Team members should be trusted to individually pick tickets based first on order of priority for the company (as set together in team meetings) and secondly on personal capabilities.

New improvements, fixes and functionality get to be outputed on a continuous basis.

There are other significant benefits to using this system, to adhering to this work methodology. For example by letting devs pick small stories from themselves they can also choose stories that do not fit their strong points, so that they can learn new things and develop new areas of expertise. This helps reduce programmer specialization. You do not want to end up looking on the story board and saying – “Hmm, The online shopping cart is up for a redesign, who did development on it last time? Oh, Daryl. O.K. Give it to Daryl, he knows his way around the code” – And there are plenty of companies that resort to these tactics.

You want your whole tech team to be familiarized with the entirety of the system, the whole app, the whole code, both front-end and back-end. This helps create a kind of synergy, but more about that in a different post.

Classical Inheritance In Object Oriented Programming

If you’ve been eying the opportunity to become a computer programmer for some time now, or even if you’ve just started venturing out onto this great and noble journey, chances are that you’ve hit yourself with this term quite a few times whether in books, booklets or even documentation sites, Classical inheritance has always been there, ever present.

So what exactly does it mean? What does this term – that sometimes has had even seasoned programmers on the ropes – actually express?

Def- Class-based programming, or more commonly class-orientation, is a style of object oriented programming (OOP) in which inheritance is achieved by defining classes of Objects, as opposed to the objects themselves (compare prototype based programming). – wikipedia

So let’s break it into parts. First off we start with Inheritance.

Now, even If you are not a programmer, you’ve heard or even seen this term applied in real life. In non-programming situations, the institution of Inheritance defines the laws and rules applied to the transfer of goods or traits from one person to the next. We usually see it most often applied on the case of a testament reading and application. The family of the deceased – usually the children – inherit his or her patrimony, both active (meaning goods and income) and passive (meaning debt and taxes).

The other scenario is with body traits and possibly behavior. You often hear stuff like – “He has his mother’s beautiful blue eyes” or “She has her father’s temper and drinking problem”. We contextualize the statement as if the child inherited physical traits and behavior from one or both parents.

Here lies the problem. Because of our previous experience and connotations with the term, we have a presupposition in place, and often it messes with our understanding of Classical Inheritance in OOP.

In OOP, one Object only ever inherits directly from just one other. Understand this simple sentence and you’re journey into programming will be much much easier.

I’ll say it once again, just to be sure the message got across. In OOP, class A inherits from class B , but not from class C. You do not have simultaneous inheritance.

You do however have multi class inheritance, kind off, but via a step system, not direct.

If you remember the guiding SOLID principles of design, you place your core business logic in abstract Objects and trickle down specifics in other Objects. This, for example, is how RUBY is written and designed. You have class Object, which is the root of Ruby’s class hierarchy. Its methods are available to all classes unless explicitly overridden. But Object also has a parent. It inherits from BasicObject. It is the parent class of all classes in Ruby. It’s an explicit blank class.

So when you define class A, this specific class inherits from Object, it’s default parent, and thru the fact that Object inherits from BasicObject, class A also inherits, indirectly, from BasicObject.

So when you read a phrase stating that “X class inherits from it’s parents”, in reality X only inherits from 1 direct parent, and the rest indirectly.

This is a important concept to grasp since knowing it, you can use and successfully apply the concept of Blank Slates.

If you are unfamiliar with the term, a blank slate is basically an empty Object. It comes in handy when you want to settle an Object hierarchy (for purposes which shall be announced later in a post on metaprogramming) but you do not want to inherit any behavior. So you use a dumb object

A simple example would be if you want class A to have a method that conflicts with a preexisting method already defined in the language syntax. So you sidestep the chain of hierarchy and make class A inherit directly from a dunce object, BasicObject

class A < BasicObject
  def conflicting_method_name
    #......
  end
end

Be careful though. It might come in handy, and there are specific scenarios where using a blank slate is very useful, but heavy usage can easily lead to severe consequences.

The second part of the classical inheritance concept lies with the classical part. To better understand what this term signifies you need to understand how it came about.

It is a play-on-words on the “class” name since the concept deals with class inheritance. Think of it like an “insider joke”. It might be funny to those “in the know” but to those just starting of on the great journey into programming, it is counterproductive naming to say the least.

Just take it as a very good real-world example on “the importance of naming” and the consequences bad names have. As a programmer you will spend a boatload of time pondering good names for your objects (variables, methods, classes etc). But more about that in a later post.

The Interface Segregation Principle or Why I Keep My Wife Public And My Mistress Private

The Interface Segregation Principle states that no client should depend on methods that it does not use.

In layman terms, what this principle iterates is that you only have to make public that which is essential to the core of your application. You can think of it like this:

You’ve been hard at work all day long. Come 5 O’clock and you and your favorite colleagues decide that a well deserved break is in order. And to make it all the more rewarding, you decide to add a nice fulfilling meal on top of it.

So you make haste to one of your favorite restaurants, a chic, Lebanese cuisine centered, comfy cozy joint right around the block from your office.

You go inside, the waiter seats you, passes you menus and states that he’ll be back shortly for your order.

You choose a delicious rack of lamb with a side of aromatic basmati rice paired with a nice glass of red wine. Your colleagues order similar dishes and all of you place your order. You wait while having a nice chat discussing work or hobby related topics.

45 minutes later the waiter brings your order and all of you dig in. Come the end of your stay, you pay and all of you hop off merrily on your way.

In this specific scenario an interface segregation has been applied. More exactly, the only business related logic that was made public to you – the client – were the menu options. And everything worked out great.

Now imagine that were not the case. In this more “explicit” scenario the waiter gives you a dictionary thick menu and for you to place your rack of lamb order you had access to more private methods like such: slaughter lamb, drain blood, butcher carcass, pay butcher x amount per pound, separate cuts, purchase rice, purchase condiments, pay y amount for each; then pay rent, agree on utilities contract, fire up stove, cook meat, cook rice, add condiments, plate food and serve dish.

If you haven’t yet lost your appetite at slaughter lamb, then you must have been particularly hungry.

In reality, what you – the client – only care about is: view options, place order, wait for order and pay bill. That’s it, and that should be the only thing you should have access to.

Now although you understand that behind the magic that happens between you placing an order and you receiving that order are several more steps, you have no authority on how they are made, nor should you. It means that they are of no interest to you, and as such should be kept hidden.

In programming this relates to the segregation (or separation) of public and private interfaces. If you haven’t yet read the post on Setting Up Good Interface Design, do so now.

You offer a few core functionalities as the base of your application, the things pertaining to your business logic end of the code – and these should be part of your public interface. All the other methods and code bits are just instruments necessary to get you to your destination – and these should be part of your private interface. As such you understand that the private parts may change in time. Thy are less dependable and should be “kept secret”.

As with all programming principles and paradigms, some (or even most of them) you already use – knowingly or unknowingly. The secret to being a good software developer is learning – through practice and experience – to distinguish the patterns that apply for each principle or guide-line in specific scenarios.

Case in point, you cannot successfully apply the Interface Segregation Principle all on it’s own without touching on other SOLID principles or paradigms. For example, an even worse situation then the one in which you knew how the restaurant operates and as such “knew to much about other objects” is the inevitable case in which you decided “how the lamb should be slaughtered” (humanely of course), how the meet should be cooked or worse yet, you decided to take a trip into the kitchen to supervise and give pointers. If you think this is bad enough, imagine that you and all your colleagues had placed the same order, took a trip to the kitchen and expected different results. One wanted it baked, another grilled, one chose stewed etc. You had conflicts.

Speaking of conflicts, I spoke in the title about keeping the Wife public while the Mistress private. If you are curious, I will further illustrate this scenario in a coding example in a later post, but by know you should understand that unless the Wife also uses Mistress (yeah, in your dreams) the less these two know about each other, the better.

If this sound familiar yet then by now you understand that by separating the interfaces you do more than just that. You :

  • Declare with confidence which bits are stable and dependable (the public interface).
  • Which bits are susceptible to change and as such are not dependable (the private interface).
  • Decouple your code by applying the Law of Demeter (LoD). You know waiter and his underlying purpose of take_order, but you do not know cook nor his prepare_food.
  • Apply the Single Responsibility Principle, since every object is limited in tis choices and can only really do one thing: You place_order, The Waiter takes_order, and the Cook prepares_food. And they are limited in choices because they are limited in their knowledge of other objects. They are decoupled.

And you Don’t Repeat Yourself. By acting DRY you apply the essence of SOLID design principles and create good, scalable and dependable code. But more about the DRY principle in a later post.