Clean code: Writing Function

santosh
4 min readOct 7, 2022

--

Photo by Chris Ried on Unsplash

Function are first line of organization in any program. (Some language different meaning for function and method)

Writing them well is topic of discussion

Best practice for writing function list below as standard

1. Functions should be small
2. Block and indenting
3. Do one thing (Single Responsibility Principle)
4. Descriptive name (names should shout what they do)
5. Command Query Separation
6. DRY
7. Structured Programming

1. Small

A line should be ~150 character long and there not be more than ~20 lines

The first rule of writing functions is functions should be small. The second rule for writing functions is that they should be even smaller. Functions that have 200 or 300 lines are kind of messy functions. They should not be longer than 20 lines and mostly less than 10 lines.

2 Block and Ident

This means that the block within if statement, else statements, while statements and so on should be one line long.

Probably that line should be a function call.

This will keep the enclosing function small and adds documentary values reason the function called within the block can have a nicely descriptive name.

This also means that functions should not be large enough to hold nested structures. Therefore, the indent level of a function should not be greater than one or two. This of course, makes the functions easier to read and understand

3. Do one Thing

The problem is it is hard to find what “one thing” is.

If there are multiple reason for a function to change apart from bug fixing it is NOT DOING ONE THING IT MUST BE DOING MULTIPLE THINGS

See below product.go listing it is doing multiple things

  • checking request correctness
  • Create or update or clear product if setup is enabled with create/update/clear
  • send http response
1. product.go

So which is it? Is this function doing one thing or three things?

We can notice that two steps of the function are one level of abstraction below the stated function. We can describe the function in TO format

TO CreateUpdateClearProduct we check to see the setup and if so we do check product existence and take action. In either case we return response

Ways to check a function is doing one thing

If the function does only those steps that are one level below the stated name of the function then the function is doing one thing.

Another way , if we can extract another function from it

One level of Abstraction per Function

In order to make sure functions are doing “one thing”. We need to ensure that the statement within our function are all at the same level of abstraction.

Mixing level of abstraction is always confusing like s.db.ProductExist(pr) , s.db.CreateThirdParty(pr)

4. Descriptive name (names should say what they do)

handleProductLifeCycleRequest is far better name then handle, because it better describe what it does. Even all private function should follow same principle.

Choosing good name for a function can go a long way toward explaining the intent of the function. for example write(name), isFileExist(fileName)

assertEquals might be better written as assertExpectedEqualsActual

I always had hard time using assertEquals as was not sure ordering between actual and expected.

5. Command Query Separation

Function should either do something or answer something, but not both.

Meaning either function change the state of an object, or it should return some information about that object.

// Above function set the value of a named attribute and return true // if successful and false if no such attribute exist.func set(attribute string, value string) bool{

}

Now from reader point of view

if(set("username", "ram")){
....
}
// what does this means if username was set to ram
// if attribute username was previously set to ram
// OR if attribute username was set successfully to ram
func attributeExists(attribute string) bool
func SetAttributeExist(attribute string, value string)
if(attributeExists("username")){
SetAttribute("username", "ram")
}

6. Don’t Repeat Yourself

Repetition leads to confusion and subtly broken codes because only a few repetitions were updated as expected.

Sometimes that also means you didn’t think properly of your code. When you see duplicate code, this is a danger sign. Integrity is a cost, do not pay twice

Look at product_v2.go above and notice repetition

// repeated 14 times
g.JSON(http.StatusOK, gin.H{"data": "created product", "id": id})

7. Structured Programming

Many programmers follow Edsger Dijkstra’s rules of structured programming .

Dijkstra’s said that every function and every blick within a function, should have one entry and one exit. Following these rules means that there should be one return statement in a function.

This is only a guideline and not rule, So if we keep our functions small, then occasional multiple return statement does no harm and can sometimes be for expressive than the single-entry, single-exit rule.

In larger functions we can see significant benefit of this rule which

Almost final version using all clean code guidelines

Reference

  • Clean code by Rober C Martin

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

santosh
santosh