Named Parameters in Dart, Swift and Python

In software development we optimize for readability since code is read more than its written. Named parameters are one way to improve code readability. Lets say we have a function that calculates the distance between two points. I takes two point Point class instances representing the start and end positions. When calling the functions, using positional arguments its not very clear what is being referred to.

In Python:

In Dart:

In Swift:

On the other hand, using named parameters makes function calls more expressive, its clear to the reader what the arguments represent. This becomes helpful particularly as the number of arguments grow. Lets add one more argument. In the examples below when calling the functions its not very clear what the third argument is when its being read.

Using named parameters is really helpful in such a situation. In the three languages its possible to specify that the parameters should be passed as named parameters. In Python, we can add a *, before the parameters, in dart we can add curly braces around the parameters and in swift we can remove the underscore before the parameter names.

Running flutter app on Genymotion

To run flutter apps for android development you have the option of running the app on android studio AVDs or genymotion. I prefer genymotion since I find more lightweight and I can run vagrant boxes usually for the backend of the application. This is not possible with AVDs. Flutter fails to recognize the devices created using genymotion. After searching around the internet I could not find a solution so I'm going to post what worked for me.

Ensure you have installed the Android SDKs for the target platforms. You can do this from the SDK manager in Android Studio. Launch Genymotion. On the menu bar go to: Genymotion > Settings. This will launch a dialog box. Select ADB in the dialog. Enter the path to your Android SDK folder. For example on my local setup this is /home/lk/Android/Sdk. Restart Genymotion and launch your devices. I had some problems with devices I had created before I made these changes. In this case I deleted and recreated them. When you run flutter devices your launched device should appear now. Run flutter run to launch the app. Happy fluttering.

Flutter loading screen with future builder

When developing UIs you need to give the user some feedback on a long running process. A loading widget is normally the go to solution. In React you would have a boolean property in the components state. If for example you are fetching some data from the internet, you would set the boolean to true. In the component's render method you would display a loading widget based on the value of that boolean property. When you have your data you show the right component. Something like:

This can be achieved easily in Flutter with Future Builder. FutureBuilder allows you to specify a future and a builder function. The builder function will be passed snapshots based on the state of the future. You can then check the snapshot and display your loading widget. The same can be achieved by using viewmodels and state management tools like Provide. This is so much easier though. Example:

Tribal hijacking

Yesterday while casually going through my twitter feed, this post captured my attention. If you have time please go over the thread. It speaks about how Nazi in Germany under Hitler hijacked Christianity. They first identified with it then gradually started distorting it and finally when they had gathered enough of a following cast it aside. Hitler set himself up as a messiah who could not be questioned. This rang with me because I see it at play in my country Kenya.

Tribe is a good thing. It gives people identity, a sense of belonging. Its something to be proud of. Diversity is a good thing, it makes the country richer in terms of culture. Unfortunately, this has been hijacked by our politicians just like Christianity was in Nazi Germany. Politicians use it to rally support for their own selfish interests. They use the phrase "our people are being targeted" or a variation of it. When a politician is caught in a corruption scandal, they retreat into their tribal cocoon. Recently, there was a scandal about two dams not being built but money paid for them. As expected, politicians whose names came up said that their people are being targeted. This is just one example that comes to mind but these happens all time.

Tribe has been poisoned to the extent that there is an underlying anger and resentment towards one another in my country. This boils over when elections come around. People attack one another on social media and defend "their own". People vote for their own even when the politician has a poor track record on development and has been involved in corruption scandals.

We need to move away from tribal based politics. We need to move towards ideology based politics. I think about the political parties in the USA. When I hear democrats I immediately thinks about the ideas they support and are against not which tribal group they represent. The same thing about Labour party UK. The two major political parties in Kenya, Jubilee and Nasa are largely tribal outfits. The future still looks bleak sadly. The upcoming election seems like will be the largely the same. I pray for change in our thinking as a people. I think the current political elite need to step aside to allow for change just like Ethiopia has done.

Our current system favors the political elite, so don't expect them to change. It wont happen. I pray there wont be need to spill blood to get change. The people need to rise up and cast aside the shackles of ignorance and embrace the possible future before them.

Setting up Dart for local development

I've been learning Flutter for mobile development lately. I like the journey so far and I'm going to be posting stuff I learn along the way. First i'll show how to setup Dart for local development. I use asdf for managing different versions of language runtimes on my local machine. I found out about it when trying to setup different Python versions. My dev machine comes with Python 3.7 but at work we use Python 3.6 and I like having the exact version in use. What to do? asdf to the rescue. asdf has a plugin system that allows allows the installation of different langauge runtimes for example you can install Python 3.5, 3.6 and 3.8 on the same machine and switch between them. A lot of langauges are supported you can find these here.

To setup asdf run:

git clone ~/.asdf --branch v0.7.2`

Replace 0.7.2 with the latest version which you can find here. Next add asdf to your shell like so:

echo -e '\n. $HOME/.asdf/' >> ~/.zshrc
echo -e '\n. $HOME/.asdf/completions/asdf.bash' >> ~/.zshrc

Remember to replace .zshrc with your shell specific config file e.g .bashrc. Reload your config file source .zshrc. You are good to go.

Now lets setup dart. We begin by installing the dart plugin:

asdf plugin-add dart

Now we can install dart sdk and tools by running:

asdf install dart 2.3.1

Replace 3.2.1 with the latest version or the version you want. You can find these here. You need to choose a global version. This is the version that will be run when you type dart in any shell. You can do this by:

asdf global dart 2.3.1

You can also set a version to be used only in the current shell:

asdf local dart 2.3.1

Happy darting.

Get your PRs merged faster

Every developer wants their code in production as soon as possible. I am assuming you are in a team or at least have someone else to review your code before its merged into staging or production environments. In the past two years I have seen an improvement in the time it takes to get my code merged.

I've had my PRs waiting for review for days on end. Its annoying to say the least. I'll share a few points that helped me get my PRs reviewed and merged a lot faster.

Its a team thing.

As developers we tend to be fiercely independent. This unfortunately does not help deliver products to clients any faster. As a team you need to learn to set aside your individual goals and work on team goals. I used to say things like "I managed to complete all the tasks I set out to do this week" during retro. Now I try to see did we complete all tasks assigned to our team. Changing this mindset is hard and slow but its worth the results. Agree as a team to be setting aside time to review each other's PRs. Maybe at the start of the day and end of the day. This will leave you with enough time to focus on your tasks.

Have a good relationship with your team mates.

Try and have a good relationship with your team mates. Be interested in them as people. This helps resolve any conflicts when they do arise and we all work better with people we like. Remember at some point you will need help from your team mates and having a good relationship with them allows you to ask for help without things getting weird.

Write clean code.

Write good code. No one likes to read spaghetti code and super huge functions in which you have to spend a lot of time piecing together. If you regularly write bad code, your team mates will avoid your PRs and only check them when its completely unavoidable. This is a skill that can be learnt. There are good books and articles out there for this. A quick google search will guide you.

broken child now man full of hope

When I was about fifteen or sixteen years old in high school I was a really happy boy. People used to call me "smiley". I was also doing very well academically, top of my class. We had a mid term break, I was excited as always to be going home. Left school boarded a matatu with some other guys we lived in the same area and went home. When I got near home i realized things weren't ok. My mom's clothes were scattered outside, I can't remember well but I think my elder brother was gathering or gathered them later. I learnt that my dad had chased my mom away the night before. This had happened before but this time there was a finallity to it. I didn't know how to process it so I ignored it. Spent my break and went back to school. I didn't realize how badly it affected me but I changed. Its like a dark cloud came over me, no more smiles. Academically, I crashed. I can't explain it its like a deep sadness that you can't get away from. You can laugh with your friends till you cry but deep inside there is this inescapable sadness. My home was my entire world, it was all I knew and now it was gone. I lost all the security I had in the world. This placed in me a deep insecurity that took years to overcome. To this day I still struggle.

Now I have a daughter of my own and I am deeply worried for her. What if her mom and I don't last and she has to go through the same. Selfishness and pride caused the break up of my parent's home and now I see elements of the same in my wife and I. This deeply troubles me. See selfishess and pride can be very subtle, they show in our attitudes, tone of voice. Being a christian, I believe the that after the fall in the garden of Eden, we became hopelessly selfish and proud. Both partners need to be in agreement to battle these two foes deliberately. As man, I have had to take one for the team many times. In a fight, I know I'm right and even have the facts to prove it but I love peace more in my home so I yield. I know many men have had to do this for the sake of their families.

I have found hope in the word of God. Sin is deceptive, it hardens and blinds us to our own faults. As a christian, I find hope in God's word, in:

Heb 13:21 says:

...equip you with everything good for doing his will, and may he work in us what is pleasing to him, through Jesus Christ to whom be glory for ever and ever.

Justice shall prevail

I feel sad when I think about the corruption in my country. Kenya has so much potential but the looting of public resources has led to so much underdevelopment and suffering. I have been reading the book of Habakkuk for the past few days and i really related to the old testament prophet. In his time, his people were suffering under a foreign power. In my time, my people suffer under corrupt leaders.

In Habakkuk 1:2, he cries to God:

How long, Lord, must I cry for help? But you do not listen!I call out to you, Violence! But you do not deliver! 

I feel the same way, our country has suffered under corrupt leaders, one after the other, scandal after scandal. My heart cries out to God, how long must we suffer under these wicked people who don't care who gets hurt by their actions. They steal from medical funds and money meant for primary school children, they kill directly and indirectly. During the general elections they incite the people to violence.

In Habakkuk 1:4, he says:

Therefore the law is paralyzed,
    and justice never prevails.
The wicked hem in the righteous,
    so that justice is perverted.

In my country, politicians loot public resources, they are charged in court, post bail and leave. The trial begins but no one is ever convicted. They continue to make public appearances and even run for public office again. There is a lack of political will to bring change. Our institutions tasked with fighting corruption seem powerless to do anything. I remember the other day reading an article in one of the local newspapers that the EACC has only recovered 500,000 KES of looted money, yet billions have been stolen. Cases remain in court for years. I remember my mom and her siblings have a case in court for over eighteen years and its still not done. People can steal and not worry about the consequences, they are able to bribe judges to get favorable sentences. They can bribe court officers so the documents disappear. Justice truly is perverted here. Politics has become so lucrative, people are willing to do anything to anyone so as to get elected or appointed to public office. I had some business dealings with someone and during a casual conversation, I brought up that I was once caught with a traffic offence and was fined in court. He told me if we knew each other then he would have been able to help me, I would have given him ya macho and walked scott free. He works at the court offices.

I like the current DPP, Noordin Haji and the DCI, George Kinoti, they are are ordering arrests and prosecution of high profile individuals. I hope the courts wont let them down. I always remember Haji in my prayers. I need to remember to pray for Kinoti too.

In Habakkuk 2:3, God says:

For the revelation awaits an appointed time;
    it speaks of the end
    and will not prove false.
Though it linger, wait for it;
    it[a] will certainly come
    and will not delay.

Reading from 2:2 to the end of the chapter, God is passing judgement on the wicked and in 2:3 God says it will come to pass. We have the advantage of hindsight, we know the Assyrians were overthrown by the Babylonians so God's word came to pass. In 2:9 God specifically speaks to those who build their house by unjust gain. This is our corrupt politicians, corrupt judges, corrupt police officers and anyone else who is corrupt. I believe one day God will bring justice to our country, things will change for our people. Ultimately, all sin will be punished on judgement day so no one will escape.

Habakkuk 3:16:

Yet I will wait patiently for the day of calamity
    to come on the nation invading us.

Improving readability of Python code

Readability of code as defined in wikipedia:

In computer programming, readability refers to the ease with which a human reader can comprehend the purpose,
control flow, and operation of source code

Python is one of the most readable programming languages out there but we can still improve this more by following software development best practises and tools provided by Python core language and the Python community. By software development best practises I am referring to writing clean code. Watch things like:

  • Use good descriptive variable and function names
  • Follow SOLID priciples
  • Keep functions short
  • Follow coding conventions for your programming language e.g PEP8

For Python, type hinting is also a good option since version 3.5. This will be my main focus for this article.

In this article I am only going to refer to tools specific to Python, later I will add another article on SOLID with examples in Python. Python uses duck typing to determine the type of a variable. This usually leads to criticism where people say it reduces readability and I agree with them. I have been using Python for the past five years and its annoying having to read a function body in order know the type of parameters passed in. If its a dictionary passed in or tuple its worse because you have to look through the code to know the type of keys and values of the dict. I've had to add print statements to determine the type being passed in.

def check_status(project, date):

In the code above project and date could be anything. Proper naming of the variables helps but still, project could be an int, the project database id or a user defined class instance. date could be an int or object. This is the problem typing module was added to solve. I don't think types within the function body are a huge deal since you can usually determine this from the context, even in Kotlin you don't have to specify the type when declaring a variable it can usually be infered from the context.

With Python's type hints you can specify the parameter being passed to a function.

from datetime import date

from .projects import Project

def check_status(project: Project, date: date):

I'm a huge fan of namedtuples, they have a smaller memory footprint compared to classes and are more descriptive that tuples. Typing takes their descriptiveness to a new level. You can specify the type for the field names.

from typing import NamedTuple

class Truck(NamedTuple):
    num_wheels: int
    num_axles: int