Clean Code
Professional programmers don’t only think about how the software functions well, but also how to write a proper source code so the software they are building will be maintainable and developable in a long term of time. Since the code is going to be read by everyone in the project, it’s so important to write a readable, simple, and understandable code.
That’s where we apply clean code.
What is Clean Code?
“Code is clean if it can be understood easily — by everyone on the team. Clean code can be read and enhanced by a developer other than its original author. With understandability comes readability, changeability, extensibility and maintainability.”
— Robert C. Martin
How do we implement clean code?
Currently, me and my team are working on an iOS project and these are examples on how we implement clean code on our project:
- Clear naming for class, method, and variable
Take a look at this class:
import UIKitclass DaftarPertanyaanViewCell: UITableViewCell { @IBOutlet weak var clientcodeLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var bgView: UIView!
func setPertanyaan(question: Pertanyaan) { clientcodeLabel.text = question.clientCode messageLabel.text = question.message categoryLabel.text = question.category }
The name of the class, method, and variables are clearly representing what they are or what they do. Names are important because they are the identifier of each elements.
For Swift, the format for variable and method is camelCase and PascalCase for class.
2. Error Handling
do { let data = try JSONSerialization.data(withJSONObject: data as Any, options: .prettyPrinted) let decoder = JSONDecoder() let questionResponse = try decoder.decode(Questions.self, from: data) let questionDetails = questionResponse.results completion(questionDetails, status)} catch { print(error.localizedDescription) completion(nil, .failed)}
It’s better to throw exceptions rather than return to error codes. When you throw an exception when you encounter an error, it’s easier to do debugging and it helps a lot.
3. Don’t Repeat Yourself (DRY)
Duplication is a problem for software. It’s better if we make it more efficient. Here’s the example for a duplication in a Swift program:
@IBAction func didClickKeluarButton(_ sender: UIButton) {
let defaults = UserDefaults.standard
defaults.removeObject(forKey: "Email")
defaults.removeObject(forKey: "Token")
defaults.removeObject(forKey: "Lawyer Code")
defaults.removeObject(forKey: "Lawyer Name")
defaults.removeObject(forKey: "User ID")
defaults.synchronize()
}The function above repeats itself when it has to remove object on User Defaults. We can make it more efficient by using enum and having one reset method to remove all the keys. Check this out:
enum Keys: String, CaseIterable {
case Email
case Token
case LawyerCode
case LawyerName
case UserID
}func reset() {
Keys.allCases.forEach { UserDefaults.standard.removeObject(forKey: $0.rawValue) }
}
4. Reducing Code Smells
Get Yafonia Hutabarat’s stories in your inbox
Join Medium for free to get updates from this writer.
Code smells can increase the chance of bugs in the future. There are many kinds of code smells:
- Long Methods and Classes
- Duplicated Methods in the Same or Different Class
- Class Divergent Change
- Shotgun Surgery
- Feature Envy
- Data Clumps
- Primitive Obsession
- Switch Statement
- Parallel Inheritance Hierarchies
- Lazy Class
- Temporary Fields
- Message Chains
- Inappropriate Intimacy
- Middle Man
- Alternative Classes with Different Interfaces
- Incomplete Library Class
- Comments Code
- Speculative Generality
In this article, I want to share with you what issues I have with code smells in my project. Here’s the example:
func fetchQuestion(page: Int) { // loading = delegate?.startLoading() var questions = [Pertanyaan]() networkManager.getQuestions(page: page, pageType: delegate?.getPageType()) { (result, status) in if status == .success { result?.forEach { q in let question = Pertanyaan(clientCode: q.question_code, message: q.description, category: q.answers?.lawyer?.category?.first?.category?.name) questions.append(question) } self.delegate?.updateQuestion(questions) } else { //Show gagal message }}}
We see that there’s one line of unused code //loading = delegate?.startLoading() . We can delete it because we don’t need it anymore. There’s one examle of code smell.
We use Sonarqube to detect code smells, issues, test coverage, and code duplication.
Sonarqube helps us to figure out the issues on our codes. It helps us to reduce code smells.








