Skip to main content

Simple code: Functions and methods

What makes a good function or method? I don't think it's a single thing but a combination of things where each is significant. If one the things is flawed it affects to all others and the whole function is flawed. So what are those "things"?

Have a meaningful name


Function should have a name that describes it's purpose or functionality. When a function has a meaningful name it's easy to read and understand what's it's purpose.

Let's take a example.

If function's purpose is to find a customer by it's id a good name could be findCustomerById(id: String) or it could just as well be just findCustomer(id: String) because the function signature implies that the
customer is found by it's id the word find also implies that the customer might be found or it might not be found.
If the function's name would be changed to getCustomer(id: String) it's meaning changes because now it implies that there's no fallback, the customer is either found or the function fails miserably and maybe throws a exception.
Both are valid names for a function but they have a different meaning and therefore their implementations should also be different.

Should have as few parameters as possible


I like to follow the rule of three myself what that means is that a function should have three or less parameters. When the function needs more than three parameters it should be rewritten and the parameters placed inside a data holder e.g. class, data class, JavaScript object etc. This is a easy way to reduce the number of parameters and to organize the data within the application.

Lets take a example of a function that has identical behaviour but differing signatures.


fun createCustomer(
  firstname: String,
  lastname: String,
  streetAddress: String,
  city: String,
  zipCode: String
)


vs.

data class Address(
  val street: String,
  val city: String,
  val zipCode: String,
  val streetNumber: String
)

data class Customer(
  val firstname: String,
  val lastname: String,
  val address: Address
)

fun addCustomer(customer: Customer)


Does what's expected


Function should do what's expected of it, nothing more, nothing less. If a function is named as findAddress(latitude, longitude) it should find the address in the given coordinates or if no address can be translated for the coordinates return a None, null, Empty, what ever is the appropriate type for the given language. The function should not do anything else e.g. find  adjacent addresses or building records of the coordinates or address. The function can have side effects like logging or analytics but those
are invisible to the input and to the output.

Is testable


Functions should be designed so that they're testable. In the previous code sample I defined the function addCustomer but I didn't define any return type for it so in that format it's testability is questionable. Sure it could be tested with mocks or spies depending on what the internal implementation is like but by just simply giving it a return type we can easily test it.

fun addCustomer(customer: Customer): Customer


With the given function signature we can return the added customer entity to the callee and with that addition we can test that the function does what it's supposed to do that customer entity e.g. assign it a unique id.

Four conventions for functions


Have a meaningful name, have as few parameters as possible, do what's expected of it and be testable.
Doesn't seem that hard to follow or too restricting conventions that when followed makes the code simple, easy to read, easy to reason, testable and maintainable.

Next part


In the next part I'll be writing about contracts and how they're related to code.

Popular posts from this blog

Simple code: Naming things

There are two hard things in programming and naming is one them. If you don't believe me ask Martin Fowler https://www.martinfowler.com/bliki/TwoHardThings.html . In this post I'll be covering some general conventions for naming things to improve readability and understandabilty of the code. There are lots of things that need a name in programming. Starting from higher abstractions to lower we need to name a project, API or library, we probably need to name the source code repository, when we get to the code we need to name our modules or packages, we give names to classes, objects, interfaces and in those we name our functions or methods and within those we name our variables. Overall a lot of things to name. TLDR; Basic rule There's a single basic convention to follow to achiveve better, more descriptive naming of things. Give it a meaningful name i.e. don't use shorthands like gen or single letter variables like a, x, z instead tell what it represents, what it does...

DIY home automation, new generation

I've had my DIY home automation system for controlling outlets and reading sensor data running for about two years now. The system has been working fine and I haven't had any need to touch the code since I added the sensor reading to it, until a few months back. Need for new functionality Few months ago I got a new IoT toy for a lend from a friend until I'd get my own toys, a ruuvitag sensor beacon. Ever since I found the ruuvitag for the first time from kickstarter I had the idea of getting a bunch of ruuvitags and adding their weather station sensor readings as part of my home automation system. The original home automation backend included only tellstick compatible devices and was written in Python, and in my mind it was kind of a hack. The ruuvitag beacons communicate via BLE i.e. Bluetooth Low Energy and that meant that I needed to add functionality to read the beacon data via bluetooth. I found a ruuvitag Python library and initially thought that I'd just...

Simple code: Unit tests

Unit tests are the developers number one safety net. Let that sink in. This is the number one reason for writing unit tests. Unit tests are written by developers for developers to ensure that the code works as expected and handles happy and sad paths correctly. With enough unit test coverage the tests enable a safe environment for refactoring and rewriting code. Unit test scope Unit test should test a single thing, a method or function call and it should test only one use case within. In other words a unit test should test a function with a single input. This is a important guideline to understand. When a unit test tests a function with single input it makes the test isolated, repeatable and predictable. Example of good tests: @Test fun findsAddress() {   val address = findAddress("Stevens street 35", "Southport", "Australia")   assertThat(address).isNotNull() } @Test fun doesNotFindAddress() {   val address = findAddress("Stevens street 697", ...