Unix is the most powerful development tool

The Unix operating system is the most powerful development tool.  It doesn’t matter if you’re working with a LAMP/LEMP stack, Java, NodeJS, or SQL or any other coding language, Unix allows you to develop code and computer systems more efficiently.

Developed in the 60s in Berkeley California, curiously at the same time LSD was being experimented with in Berkeley, it still proves today to be one of the great general purpose operating systems.  It has evolved very much since then and most us use a version of it today now called Linux.

The main Unix philosophy is that everything is a file, and can be treated as such.  Source code, executables, I/O, and processes are files.   This allows you to manage and manipulate everything on the computer system in a unified way.

Simple Unix commands like grep, sed, awk, cat, cut, head, and many others can be strong together to do very sophisticated things, like parse a spreadsheet and pull out meaningful data from selected parts, or managing large computer programming projects.

These days I work mostly with Python, PHP, SQL, HTML/Javascript/CSS and API calls, but what really pulls it all together and makes work a pleasure is Unix.  It is were it all starts.

 

 

OOP Behavior

When designing in Object Oriented Programming (OOP) the question I always ask myself when trying to figure out where some piece of code should go is, “Who does this behavior belong to?”.

If our class names are nouns, such as Orders, Books, ProductColors, ERPOrderSender, etc., then it is usually easy to figure out what behavior (or class method) belongs to which class.

Recently I had to add a condition to our order fulfillment workflow to look for suspected fraud orders, and stop them from being processed.

Originally, I had written a simple method to do this inside our ERPOrderSender Class, which is the class responsible for sending EDI order data to our ERP system.

After a while, these new suspected fraud orders start showing up in our “Stuck Orders” Report, and I needed a way to tell that report the reason these orders were stuck.  Clearly the ERPOrderSender Class was no longer the right place to house the “Are you a suspected fraud order” code.

In this case I created a new class called OrderReview, and a new method called getReviewStatus().  The new framework now works equally well when called in the context of Order Fulfillment, and in Reporting.

OOP is great.  It allows us to think in terms of system behavior.  This makes our system easier to talk about in natural language.   Which is just more fun – and makes our lives easier.

 

Saleor Products Data Model

I’m looking to replace our Magento Ecommerce Server with something “Nice” – Something that is not complicated, not over abstracted, something that is well … fun to work with.

Saleor is an elegant solution. It is an Ecommerce app written in Python and Django.  I was able to download it and get it up and running in about 2 hours.    That says a lot.

Now, I need to write a product upload script.  I could not find a diagram of the Product Schema, so I drew one.  I did this by looking at products/models/base.py and images.py and the postgresql database tables.  It is open for comments and corrections.  Here it is:

 

 

Data is King, is KING!

Good Data makes life easy; If we model all our the business logic in the database then the application layer is trivial.

Case in point:  I’m implementing a User Access Module.   First I define a list of Access terms:  Things like dashboard (allow view dashboard),  orders (allow view orders report), download (allow CSV downloads), etc.

Then I come up with a list of Roles: CS Agent, and Executive, will do for now.

Then I create a role_access many-to-many join table with just id, role_id, and access_id.

Then I add a role_id to the users table.

Then I painfully craft all the static data in access, roles, and access_roles tables in csv files that gets loaded when the tables are created.

When that’s done it looks like this.

User_Access_Data_Model

From there the work in the application layer is easy.    The caller simply looks like this

if self.user.has_access('download'):
    output += self._getDownloadCSVButton()

Implementation of this functionality is also trival.  We add the following two lightweight methods to the user model class:

class User(object):
    ...
    @lazyproperty
    def access(self):
        '''Return users access list'''
        sql = '''
           select a.code as access
           from   users u
                  join role_access ra on ra.role_id = u.role_id
                  join access a on ra.access_id = a.id
           where  u.id = %s'''
       results = self.db.query(sql, params=(self.id,))
       return [r['access'] for r in results]

   def has_access(self, access_name):
       '''Return True or False if this user has the given access'''

       if access_name in self.access:
           return True
       return False

And that’s all there is to, it.  Express your business logic in the database and the rest follows easy.

 

Make is Simple

Complexity is only Simplicity x 1000 — A mathematician friend once told me that. The idea struck a chord with me and has stuck with me ever since.

Everything in this world is complex.   When we design computer systems our goals should be to encapsulate that complexity into simple business level concepts.  They in turn can be broken down into smaller and smaller simple systems – and then no part of the system will be complex on its own.

Here is an example.  Say you need to download and update pricing information on a regular bases.   The new process should simple be called ‘Update Prices’.

I – The process could have the following simple breakdown:

  • Update Prices
    • Download Pricing
    • Load New Pricing Data
    • Update Pricing Data

II  – The first one could further be broken down into

  • Download Pricing:
    •  Get External Resource URI from config
    • Get External Source Dir from config
    • Get Local Destination Dir, from config
    • SFTP Download files

III – The first one here could further be broken down into

  • Get External Resource URI from config
    • Create a Config Module that reads YAML config file
    • Create environment variable to set config file name
    • Provide getter methods for each config value
    • Create YAML config files, (one for dev, staging, and prod)

IV – The first one here again, can be further be boken down into

  • Create a Config Module that reads YAML config file
    • Load YAML parser
    • Set config filename = config.basedir + / + ENV(CONFIG)
    • yaml.parse(read filename)

And nothing in it is complicated. So break it down.  Make it simple!   Everyone will be happy.

 

 

Successful Computer Programmer

So we’re all computer programmers, but what makes you successful?   What makes you an excellent contributor to your team or company?

I discovered the importance of these traits little by little over the years.  They are progressively more important as you move down.

1. You’ve got to be smart,  that’s the first step –   Love math, enjoy implementing crazy algorithms, etc.  We’re all smart, or we wouldn’t be programming computers.

2. Be organized.  It is not enough that you can write code, you need to be organize.   This includes standard practices, documentation, and good habits.  This improves productivity many fold over the long haul.

3. Planning.   The more you can plan the more really hard stuff you can get done in ever shorter time periods.  Get the scoop directly from users, design, get sign off on everything, plan your time – and then bingo – just two days of coding, and you’re done.

4. People skills.   Finally to really become successful you need to develop strong collaborative relationships with everyone involved.   Programming computers is often the easy part.  Dealing with everyone else on the project requires real talent, and may take up more time than coding.

So, in a nutshell:  Be Smart …, Be Organized …, Plan …, and … last but not least, Be a People Person.   Have fun!

 

 

 

Safety Belts Off

When should we use secure practices and when not to?  Like all good advice secure practices need to be weighed against practicality.

In a perfect world your system will have full test coverage, automated testing, database migration scripts, automated deployments, adhere to common coding practices, have identical dev and test environments, as well as excellent documentation.

In that perfect world the best way to protect production systems is not to allow logins – and to do everything through automation.

But what if that is not the case?  What if you’re supporting a legacy system that is hacky, poorly designed – and the business is relying on it at the same time?

In this case your best line of defense is think creatively and have full access to all production systems – so you can react quickly when things go wrong.  If automation can not be relied upon – then its hands on test, tweak if you have to, retest, and commit.   Until you can replace the system with something more stable.

Sometimes you need to take your safety belt off, if only for a short time.

DB, Config and Logging

The Database, Config and Logging are at the core of all application development.  Everything starts there.

A Database System stores all of the applications data.  The storage itself can be anything from a loose collection of files like jpegs, a nosql db like mongodb,  or a full fledge relational database like mysql or postgresql.   This subsystem sits right below any Model Objects.

A Configuration System allows you to configure your application without changing code.  It primarily determines where things are, such as: subdirectories, external web services, database credentials, log files etc.    You will have a different configuration file for each type of environment: dev, stage, and prod

A Logging System should be built in from the word go.   All backend tasks should be logged.  One philosophy is that all events write a single line entry of Success or Failure.   Each event can optionally also write multiple Warning or Debug logging messages.  When done this way your logs are themselves databases of all system events.   You can can easily answer questions like how many transactions processed today, and how many of them failed.

These three subsystems are needed for all application development. Here is a link to a library I have written that provides these functions.  Which I reuse it all the time.

Python Application Development – Core Library Classes – https://github.com/dlink/vlib

 

 

Always diff before you commit

If you don’t diff before you commit you don’t know what you’re committing.

When programming anything even remotely interesting, we’re making changes all the time.   Change, change, change.  Phase 1, phase 2,  experiment 1, experiment 2, etc.  And we’re using Version Control Systems, like git.  (If not, stop reading and learn git)

If you believe as I do, you should only commit working code, then we must safeguard our git repos from danger from ourselves.  That’s why you should always run git diff and scrutinize the changes before git commit, to make sure debug, merge conflicts, and other unwanted changes are not making into the big time.

It’s like look both ways before you cross.   Diff before you commit – make it a part of your stitch in time.

Less Is More

You know you’re doing a great job when, adding new functionality to a code base, and you wind up removing more code then you’ve added.  Less is More.

I once heard boast a programmer that he’d written million lines of C code.  That seemed undesirable to me.  Better you should boast that you’ve written an entire system in under 1,000 lines of code.

Doing more with less, requires good design and a lot of reusable code.   Doing more with less means you have less to maintain, and less that can go wrong.

So pride yourself on how small your code base is, not how large it is.