Sunday, November 27, 2016
How to name a function - Coding in Style - episode 11
Welcome to Coding in style, a series of short videos about how to improve our code.
This is Dragos and you are watching the Episode number 11 where we talk about how to name functions and function parameters.
A few days ago I met a friend. “What are you doing these days?”, he asked. I replied: “Book”. “What do you mean?” he asked. “Swift 3”. “Are you are reading a book about Swift 3?” he said. “Yes, I do,” I replied. “Why didn’t say so?” he said.
Of course, this is not a real conversation as it would have been a strange one. But sometimes this is how we name our functions.
As we’ve seen in the previous episodes, the variables are the nouns of our code.
Similarly, the functions are the verbs. They show an action.
To check if a function name is good, you can have a chat with it:
“Hey function, whatcha doing?”
And the function should be able to reply:
“I [function name]”
You should be able to include the function name after “I” and make a valid sentence.
Let’s look at some examples:
"I dropDatabase" - yes
"I sortArray" - yes
"I user" - nop
"I database" - nop
"I createDatabase" - yes
"I databaseCreate" - sort of, but only if your name Yoda is
You can pick a capitalization rule and stick to it. For Swift, it is lower camelcase.
So dropDatabase is fine, but not dropDATABASE or drop_database.
This can be a bit weird in the case of a name that includes an abbreviation. For example HTML or HTTP.
For example, do you use formatHTML or formatHtml?
createURL or createUrl.
In my opinion, whatever you choose looks ugly, so just pick one and be consistent.
Be specific. The name should make it clear what is the purpose of the function.
For example, create is not a good one. createDatabase is better
Long names are okay.
Make the names as long as needed, but no longer than that.
For example, if you have a function createLocalDatabase and there is only one database, replace it with createDatabase.
Regarding the function parameters, apply the same rules as for variables. In couple words, the name of a parameter should be a good replacement in the sentence “my name is [parameter name]”.
Regarding the number of parameters, they should be as few as possible.
Here is what Uncle Bob (aka Robert C. Martin) says in his "Clean Code" book:
"The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn’t be used anyway."
How about methods? Obviously, we use the same rules.
But, BTW, do you know what is the difference between a function and a method? A method is a function that belongs to a class. So a function is a free bird. A method is a free bird that has been captured and put in a cage, called class.
What else? What are your ideas about naming a function?
That is about it for today. We talked about how to name a function. In a previous episode, more exactly episode 7, we discussed how to name entities in general and in episode 8 we talked about how to name a variable or a constant. Feel free to watch them for more details.
That’s about it for now. See you soon!
Friday, November 11, 2016
Reducing the cyclomatic complexity - Coding in style - Episode 9
Welcome to Coding in style, a series of short videos about how to improve our coding.
This is Dragos and you are watching the Episode number 9 where we talk about how to reduce the complexity of a program.
What if you asked somebody the following question: how can I get to the downtown? And the answer was: You take the bus 102 or 103. If you take the 102, you go for two blocks and get off. Then, if it’s morning, you take 104 bus, if it’s evening and during a weekday you take 105. If it’s weekend you take 106. If you take 104, you get off after 3 blocks, if you take 105 after 5 blocks. Nobody can remember such a thing. But, lots of times, we write code like this.
As you know, the developing process does not end when you finish a task. It does not end when you launch the product or when you fix a bug. It finishes only when the code and the product are trashed and erased from existence. Until then, every little piece of code you write has a big chance to be visited again and changed.
Because of that, it is good idea to write awesome code every step of the way. Do to others as you would have them do to you can be translated, in this case, write your code as you would like others to write the code for you. In a good style, that is.
Maybe one of the most important qualities some code has is to be easy to understand. If nobody can understand our code, it does not mean we are very smart and the code is awesome. No, no, no. On the contrary. It means our brain is so complicated, that we are not able to write simple code.
There is one measure for the complexity of the code. It is called cyclomatic complexity.
The cyclomatic complexity defines the number of possible paths a piece of code can follow. It can be defined for a whole app or for a function.
For example:
//Example 1
func printHello() {
print("Hello")
}
There is only one option of execution, so the complexity is 1.
The following function has complexity 2, as there are two possible paths:
//Example 2
func checkIfTeenager(age:Int) {
if age < 13 {
print("not teenager")
} else {
print("teenager")
}
}
While there is some debate about what complexity should be maximum, it is clear that the smaller the better.
Here are some suggestions to reduce it.
//Example 3
func checkIfPositive(n:Int) -> Bool {
if n > 0 {
return true
} else {
return false
}
}
The function has the complexity 2 as there are two different paths. The more if-s one adds the bigger the complexity is.
We can eliminate the if statement, and thus reducing the complexity, by returning directly the Boolean:
func checkIfPositive1(n:Int) -> Bool {
return (n > 0)
}
//Example 4
func convertToString(n:Int) -> String {
switch n {
case 0:
return "zero"
case 1:
return "one"
case 2:
return "two"
case 3:
return "three"
case 4:
return "four"
case 5:
return "five"
case 6:
return "six"
case 7:
return "seven"
case 8:
return "eight"
case 9:
return "nine"
default:
return "unknown"
}
}
This ugly function has complexity 11. It also has ugliness 1000, but that is not a measure that is invented yet.
What to do?
We can replace the ugly function with:
func convertToString1(n:Int) -> String {
if (n>=0) && (n<=9) {
let numberAsString = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"]
return numberAsString[n]
} else {
return "unknown"
}
}
In this case, the complexity is down to 2.
Let’s check another example, for formatting an address:
//Example 5
func formatAddress(street: String, city:String, country:String) -> String {
if street == "" {
if city == "" {
if country == "" {
return ""
} else {
return country
}
} else {
if country == "" {
return city
} else {
return city + "," + country
}
}
} else {
if city == "" {
if country == "" {
return street
} else {
return street + "," + country
}
} else {
if country == "" {
return street + "," + city
} else {
return street + "," + city + ", " + country
}
}
}
}
Not only it is a solution that does not look nice, it is also error prone. Also, it is long. And it has the complexity of 8, which is pretty big.
We can reduce the complexity by writing a helper function that just adds a command to an item:
func appendItem(item:String) -> String {
if item == "" {
return ""
} else {
return item + ","
}
}
Then we can format the address by appending all the elements to each other:
func formatAddress1(street: String, city:String, country:String) -> String {
var result = appendItem(item: street)
+ appendItem(item: city)
+ appendItem(item: country)
if result.hasSuffix(",") {
result.remove(at: result.index(before: result.endIndex))
}
return result
}
That is about it for today. We talked about reducing the complexity of the code. While it might seem awesome that one is able to write complex code, the reality is the another way round. The smarter one developer is, the simpler and easier to understood code he writes.
What do you think about the topic? What are the ways you like to simplify your code? Feel free to leave a message to the video or send me an email.
Do you have any idea for a topic, send me a message as well!
Friday, October 7, 2016
Tuesday, September 13, 2016
Monday, September 12, 2016
Get smart by being stupid
Do you know why programming is the best job ever? From the thousands and thousands of possible jobs out there, programming is the most awesome one. Why? Simple. Because it is the only job when you feel smart when you are stupid.
Have you ever written a simple code that was so simple that any kid could have written it and yet that was not working? No amount of swearing punches to the table or to the keyboard made it work.
And after hours and hours of investigating you found a comma or a bracket missing. What did you do at that moment? Honestly?!?
First, you felt like the king of the world! The smartest programmer on the planet to have done the stupidity in the first place but then being so smart that you were able to fix it. Didn't you also tell everybody about it? 'Look how stupid I was but the how smart I am for having found a solution to it.'
Does it sound familiar?
What does this have to do with Coding in style? Well, awesome code lives on a foundation of many stupid mistakes and especially of the pain you went through fixing them!
That’s it for today!
Wednesday, August 31, 2016
How to give a great talk
1. Share just one idea
2. Give people a reason to care about it
3. Build your idea using pieces the audience understands
4. Make your idea worth sharing
2. Give people a reason to care about it
3. Build your idea using pieces the audience understands
4. Make your idea worth sharing
Tuesday, August 23, 2016
Capitalization (Coding in style in 60 seconds)
Welcome to “Coding in Style in 60 seconds”, a collection of short videos about how we can improve our code in simple steps. This is Dragos, the speaker for this video.
Do you have any idea what is the first reason for which the code is discarded? Of course, other than the fact that it is not working. Eh? Because it is ugly!!!
Who likes to keep ugly things around? We like to live in a beautiful house, drive a beautiful car and marry a beautiful woman or a handsome guy. But I digress.
One of the fundamental pieces of the code is a variable. So we need to make it beautiful.
To start with, decide on the capitalization. For example, in Swift, the most common one is lower camel case. That is: start the name of the variable with a lower letter and capitalize each of the next words in the name if any.
Let’s take a look at few examples.
var clientName = "john"
var cityOfBirth = "Toronto"
var numberOfSecondsInAMinute = 60
In this example, all the variables are nicely formatted, with first word starting with a lower letter and the next ones with a capital.
Here is another example, not that good this time.
var first_name = "ugly name"
var FirstName = "this is a class name"
var firstNAME = "another ugly name"
The first variable has an underscore, the second one has both words capitalized and the last is a mess.
Let’s talk a bit about constants. A constant is a variable that does not vary so we can use the same rules. With just one addition. To differentiate a constant from a variable, we can start its name with a k.
Here is a good example.
let kClientName = "john"
let kCityOfBirth = "Toronto"
let kNumberOfSecondsInAMinute = 60
And here is a messy one.
let CLIENT_NAME = "john"
let CITY_OF_BIRTH = "Toronto"
let NUMBER_OF_SECONDS_IN_A_MINUTE = 60
Monday, August 15, 2016
Coding in Style in 60 seconds
We are starting a new initiative to promote beautiful coding: "Coding in style in 60 seconds", a collection of short videos.
Each video will present a small topic that can have a great impact on the code quality.
You can receive the video by email by subscribing to the blog: http://blog.adelante.ca/ or see them on Facebook at https://www.facebook.com/adelanteconsultinginc/
Each video will present a small topic that can have a great impact on the code quality.
You can receive the video by email by subscribing to the blog: http://blog.adelante.ca/ or see them on Facebook at https://www.facebook.com/adelanteconsultinginc/
Friday, June 24, 2016
You want the code clearer? Add useless conditionals
Imagine this situation:
You have a shopping cart and after a product is ordered, its status can be Approved, Declined or Not Available.
If the product is not available, you want to do some processing and then display a message depending if it is declined or not available.
The code looks like this:
You have a shopping cart and after a product is ordered, its status can be Approved, Declined or Not Available.
If the product is not available, you want to do some processing and then display a message depending if it is declined or not available.
The code looks like this:
if ([product isNotAvalable] || [product isDeclined]) {
//some common functionality
if ([product isNotAvalable]) {
//do something
} else {
//do something else
}
}
Nothing wrong with this code. For the second if, it is obvious that "do something else" is happening when the product is declined.
What if a developer looks only to this piece of code:
if ([product isNotAvalable]) {
//do something
} else {
//do something else
}
There is a big chance that he will understand that "do something else" is happening when the product is not "not available" that is when the product is available, that is Approved.
To prevent this, we can add a useless conditional like the following:
if ([product isNotAvalable] || [product isDeclined]) {
//some common functionality
if ([product isNotAvalable]) {
//do something
} else if ([product isDeclined]) {
//do something else
}
Wednesday, May 18, 2016
Working in a team
I am working in a building with twelve floors, each of them inhabited by few hundred employees.
Each morning, when I arrive in time, there are two ordered lines of people waiting for one of the elevators. Politely, we wait in line and get in the closest elevator.
Usually, this does not take longer than 1-2 minutes.
Few days ago, I got in front of the line and waited, and waited, and waited. Then I waited a bit more.
What's wrong with the elevators this morning, I thought.
Then the guy if front of me moved a bit and said: 'Oops, nobody pressed the button to call the elevator!'
And he did press the button and one elevator came right away.
Each morning, when I arrive in time, there are two ordered lines of people waiting for one of the elevators. Politely, we wait in line and get in the closest elevator.
Usually, this does not take longer than 1-2 minutes.
Few days ago, I got in front of the line and waited, and waited, and waited. Then I waited a bit more.
What's wrong with the elevators this morning, I thought.
Then the guy if front of me moved a bit and said: 'Oops, nobody pressed the button to call the elevator!'
And he did press the button and one elevator came right away.
Subscribe to:
Posts (Atom)