Racism, Autism, Clean Code and Safe Office Spaces

In my old life, I had to deal with questions such as, “how do I motivate Mary so that she comes in on time and does her work diligently?”

In my new life, I have questions such as, “how do I ensure that the correct metadata is automatically published for a newly available ultra high definition (UHD) tv programme promptly so that the i-player website is always correct?”

Seven simple steps to solve my current issues:

  • Know a bit of python
  • Use Test Driven Development (TDD) to write a unit test.
  • Use Unittest module patch instead of dependency injection for mock.
  • Update code until code passes.
  • Use AWS cloudformation to deploy infrastructure as code to implement
  • Examine cloudformation JSON and manipulate python classes and loops to write appropriate JSON
  • Smoke test the result

Learn Python

https://learnxinyminutes.com/docs/python/

                # Single line comments start with a number symbol.

""" Multiline strings can be written
    using three "s, and are often used
    as documentation.
"""

####################################################
## 1. Primitive Datatypes and Operators
####################################################

# You have numbers
3  # => 3

# Math is what you would expect
1 + 1   # => 2
8 - 1   # => 7
10 * 2  # => 20
35 / 5  # => 7.0

# Integer division rounds down for both positive and negative numbers.
5 // 3       # => 1
-5 // 3      # => -2
5.0 // 3.0   # => 1.0 # works on floats too
-5.0 // 3.0  # => -2.0
            


Let me tell you a secret, writing computer programs; coding is easy. I’ve spent most of my life in business as a finance professional and finance systems consultant, which was hard. It was almost impossible. All day every day, I had to deal with other people. I had to read their minds to find out what makes them happy and then give that to them. I had to make small talk, network and build working relationships. I had to decide on who to hire and who should be fired. I had to be empathetic, thoughtful, polite, friendly and motivated.

However, I could not mind reading. I was often stereotyped as the black working class trouble maker — the foreigner, separate and different, temporary and future enemy. I was tolerated as I could see what they couldn’t see. I saw blindingly obvious solutions that saved companies millions of pounds. I saved EasyJet millions of pounds simply by reading and understanding the published VAT rules, something anyone could have done. I then applied them as stated by using simple maths and percentages. This enabled them to calculate their correct VAT liability instead of overpaying.


Test Driven Development

Decide what you want the code to do. Then write a test in code that passes when the code does what it suppose to do. Update the code until the test passes. No magic or mind-reading is needed. This is Test Driven Development (TDD)

As Kent Beck says, “TDD is meant to eliminate fear in application development. The byproducts of fear include tentative, grumpy, and uncommunicative programmers who cannot absorb constructive criticism. When programming teams buy into TDD, they immediately see positive results. They eliminate the fear involved in their jobs.”

TDD Hello world example

Write failing code — decide on code design

                def hello_world():
    pass
            

Write a test — test design

                import unittest
from mycode import *

class MyFirstTests(unittest.TestCase):

def test_hello(self):
        self.assertEqual(hello_world(), 'hello world')
            

See test fail — ensure design tested.

                F

====================================================================

FAIL: test_hello (__main__.MyFirstTests)

--------------------------------------------------------------------

Traceback (most recent call last):

File "mytests.py", line 7, in test_hello

self.assertEqual(hello_world(), 'hello world')

AssertionError: None != 'hello world'

--------------------------------------------------------------------

Ran 1 test in 0.000s

FAILED (failures=1)
            

Write passing code — implement design

                def hello_world():
    return 'hello world'
            

See test pass — check that design implementation works.

                --------------------------------------------------------------------

Ran 1 test in 0.000s

OK
            


Mock Objects in unittest with patch function

unittest.mock() has a mechanism for mocking objects using patch(), which looks up the object to be mocked in a given module and replaces that object with a mock.

A mock or mock object substitutes and imitates a real object in a test to control the behaviour of the tested code.

Notice that it is crucial where you ‘patch’. You need to ‘patch’ where you look up the object.

Using patch a decorator — the code to be tested

                import requests
from datetime import datetime

def is_weekday():
    today = datetime.today()
    # Python's datetime library treats Monday as 0 and Sunday as 6
    return (0 <= today.weekday() < 5)

def get_holidays():
    r = requests.get('http://localhost/api/holidays')
    if r.status_code == 200:
        return r.json()
    return None
            

Using patch in test to replace requests object

                import unittest
from my_calendar import get_holidays
from requests.exceptions import Timeout
from unittest.mock import patch

class TestCalendar(unittest.TestCase):
    @patch('my_calendar.requests')
    def test_get_holidays_timeout(self, mock_requests):
            mock_requests.get.side_effect = Timeout
            with self.assertRaises(Timeout):
                get_holidays()
                mock_requests.get.assert_called_once()

if __name__ == '__main__':
    unittest.main()
            


Using Python AWS SNS library in Code

Amazon Web Services (AWS) is a cloud service many companies use to host online services.

As well as hosting applications on servers, AWS also provides other services such as S3, Simple Storage Service and SNS, Simple Notification Service. SNS is a messaging service that implements the pub-sub pattern.

UHD metadata code uses this messaging service to trigger an update of i-player when new UHD media is available.

Example of python using boto3 library for SNS — publish a message to topic

                import logging
import boto3
from botocore.exceptions import ClientError

AWS_REGION = 'us-east-1'

# logger config
logger = logging.getLogger()
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s: %(levelname)s: %(message)s')

sns_client = boto3.client('sns', region_name=AWS_REGION)


def publish_message(topic_arn, message, subject):
    """
    Publishes a message to a topic.
    """
    try:

        response = sns_client.publish(
            TopicArn=topic_arn,
            Message=message,
            Subject=subject,
        )['MessageId']

    except ClientError:
        logger.exception(f'Could not publish message to the topic.')
        raise
    else:
        return response


if __name__ == '__main__':

    topic_arn = 'your-topic-ARN'
    message = 'This is a test message on topic.'
    subject = 'This is a message subject on topic.'

    logger.info(f'Publishing message to topic - {topic_arn}...')
    message_id = publish_message(topic_arn, message, subject)
    logger.info(
        f'Message published to topic - {topic_arn} with message Id - {message_id}.'
    )
            


AWS Cloudformation — Infrastructure as Code

Infrastructure is the services and resources you need to deploy and run your code.

You could set these up by using the AWS console, filling in the forms etc.

However, you can use code to set up your AWS infrastructure.

This code is a template written in either JSON or YAML.

This is referred to as cloudformation. Having it as code makes it repeatable and allows it to be version controlled.

Example of AWS cloudformation for EC2 — Server, elastic cloud computer

                {
  "AWSTemplateFormatVersion": "2010-09-09",
  "Resources": {
    "EC2Instance": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "InstanceType": "t2.micro",
        "SecurityGroups": [
          {
            "Ref": "InstanceSecurityGroup"
          }
        ],
        "ImageId": "ami-0080e4c5bc078760e"
      }
    },
    "InstanceSecurityGroup": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupDescription": "Enable HTTP over port 80",
        "SecurityGroupIngress": [
          {
            "IpProtocol": "tcp",
            "FromPort": "80",
            "ToPort": "80",
            "CidrIp": "0.0.0.0/0"
          }
        ]
      }
    }
  }
}
            


Using a Python Library — Troposphere to Create Cloudformation JSON

The cloudformation JSON can be written by hand, but it is easier and clearer to use code to output the JSON.

The troposphere python library is used to create AWS cloudformation.

All that is needed is an understanding of python, for example, instantiating classes and setting class and instance variables.

Create an EC2 instance.

                >>> from troposphere import Ref, Template
>>> import troposphere.ec2 as ec2
>>> t = Template()
>>> instance = ec2.Instance("myinstance")
>>> instance.ImageId = "ami-951945d0"
>>> instance.InstanceType = "t1.micro"
>>> t.add_resource(instance)
<troposphere.ec2.Instance object at 0x101bf3390>
>>> print(t.to_json())
{
    "Resources": {
        "myinstance": {
            "Properties": {
                "ImageId": "ami-951945d0",
                "InstanceType": "t1.micro"
            },
            "Type": "AWS::EC2::Instance"
        }
    }
}
>>> print(t.to_yaml())
Resources:
    myinstance:
        Properties:
            ImageId: ami-951945d0
            InstanceType: t1.micro
        Type: AWS::EC2::Instance
            

Alternatively, parameters can be used instead of properties.

                >>> instance = ec2.Instance("myinstance", ImageId="ami-951945d0", InstanceType="t1.micro")
>>> t.add_resource(instance)
<troposphere.ec2.Instance object at 0x101bf3550>
            


My management style; way of dealing with people was different. So for Mary, it was first about recruiting the best person. So I favoured actual metrics above team fit and personality. An easy primary metric is turning up for the interview on time when given ambiguous incomplete information. An excellent excuse for being late did not cut it for me.

Secondly, I always judged my team on what they did rather than what they said they wanted to do — so arriving for work at an agreed time, even if late, rather than occasionally missing the contractual start time.

I was never big on motivation. I just had a down-to-earth chat with my staff about what they wanted from work. I made some suggestions but held them to what they wanted in the main. So if they wanted a promotion, I expected them to over-deliver. In contrast, if they wanted a quiet life, I was happy for them to do the minimum work but contribute to the team’s success in other ways, such as remembering birthdays.

Yet, it wasn’t easy. I always masked my neurodiversity. This took its toll on me mentally and emotionally. Also, racism was always present as a background hum or negativity. There was always racist talk and stereotyping when I was not present. I know this because concerned colleagues ‘helpfully’ told me about it. It was tough.

In contrast, the UHD metadata issue for the i-player tv programmes task was straightforward.


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!

Avatar

Errol Elliott

Senior Software Engineer, BBC

@ezzye
Ezzy Elliott(ezzy.elliott@gmail.com) BBC and https://t.co/eJ1pNWeDI7. Passionate about justice, coding, autism & Hackney. The views expressed are my own.
Stats
13

Influence

305

Total Hits

1

Posts