Upgrade to Pro — share decks privately, control downloads, hide ads and more …

DevFest Romania 2020 | Clean Code with Kotlin

44a168e6578c2cc83aaf54a38458ade9?s=47 Magda Miu
October 17, 2020

DevFest Romania 2020 | Clean Code with Kotlin

Talk at DevFest Romania 2020

Bio:
Magda Miu is an enthusiastic and innovative Squad Lead Developer at YOXO.ro (Orange) and GDE for Android with more than 10 years experience in software development.

Abstract:
With Kotlin we are able to write concise, expressive and safe code. Sounds like clean code, doesn’t it?
During this presentation we will recap what clean code is, we will highlight the importance of defining meaningful names and how to write clean functions and classes.
Finally we will be able to learn more about the advantages of immutability and how to handle the errors in Kotlin.
By the end of the session, you will have a better understanding of what clean code means and you will learn a series of tips and tricks ready to be applied in your code.
“Coding is not a sprint, is a marathon” so join my session and let’s exercise together our clean code skills.

44a168e6578c2cc83aaf54a38458ade9?s=128

Magda Miu

October 17, 2020
Tweet

Transcript

  1. Magda Miu @magdamiu Squad Lead Developer at YOXO.ro (Orange) Android

    Google Developer Expert Clean Code with Kotlin
  2. A. An app that works perfectly but is very difficult

    to add new features or to change. What would you prefer to have: B. An app that does not contain all the features required by stakeholders but it is easy to extend and change.
  3. What is Clean Code? “Express your intentions clearly to the

    reader of the code. Unreadable code isn’t clever.” Venkat Subramaniam
  4. None
  5. None
  6. Code quality “measure” Few WTFs Developer Many WTFs Developer WTF/min

    WTF = What a Terrible Feature
  7. MEANINGFUL NAMES

  8. A name should reveal intent and should answer at these

    questions: • Why it exists? • What it does? • How it is used? Use intention-revealing names
  9. Examples Types Names Classes and Objects Customer, Account, WikiPage Methods

    postPayment, deleteAccount, displayPage Solution domain names AccountVisitor Problem domain names churnPerMonth
  10. “UNCLEAN” CODE CLEAN CODE

  11. if (t % 5 == 0) { val w =

    t / 5 println("$w week(s)") } else { println("$t days") } TODO: display the number of days/weeks until an offer will expire
  12. if (daysUntilOfferEnds % numberOfDaysInAWeek == 0) { val numberOfWeeks =

    daysUntilOfferEnds / numberOfDaysInAWeek println("$numberOfWeeks week(s)") } else { println("$daysUntilOfferEnds days") } TODO: display the number of days/weeks until an offer will expire
  13. class Address { var addressCountry: String? = null var addressCity:

    String? = null var addressStreety: String? = null var addressStreetNo: Int = 0 } TODO: define a class for geo addresses
  14. class Address { var country: String? = null var city:

    String? = null var street: String? = null var streetNumber: Int = 0 } TODO: define a class for geo addresses
  15. users.filter{ it.job == Job.Developer } .map{ it.birthDate.dayOfMonth } .filter{ it

    <= 10 } .min() Warning: Use explicit argument names and avoid using too often “it”
  16. users.filter{ user -> user.job == Job.Developer } .map{ developer ->

    developer.birthDate.dayOfMonth } .filter { birthDay -> birthDay <= 10 } .min() Warning: Use explicit argument names and avoid using too often “it”
  17. FUNCTIONS

  18. Functions are the verbs of the language, and classes are

    the nouns.
  19. Basic Rules: ➔ The functions should be small ➔ The

    functions should be smaller than that Make it smaller
  20. Extra Rules: ➔ No many arguments ➔ No side effects

    ➔ Indent level max 2 Make it smaller
  21. fun parseProduct(response: Response?): Product? { if (response == null) {

    throw ClientException("Response is null") } val code: Int = response.code() if (code == 200 || code == 201) { return mapToDTO(response.body()) } if (code >= 400 && code <= 499) { throw ClientException("Invalid request") } if (code >= 500 && code <= 599) { throw ClientException("Server error") } throw ClientException("Error $code") }
  22. fun parseProduct(response: Response?) = when (response?.code()){ null -> throw ClientException("Response

    is null") 200, 201 -> mapToDTO(response.body()) in 400..499 -> throw ClientException("Invalid request") in 500..599 -> throw ClientException("Server error") else -> throw ClientException("Error ${response.code()}") }
  23. for (user in users) { if(user.subscriptions != null) { if

    (user.subscriptions.size > 0) { var isYoungerThan30 = user.isYoungerThan30() if (isYoungerThan30) { countUsers++ } } } } WARNING: keep the abstraction level consistent and avoid nested code
  24. var countUsersYoungerThan30WithSubscriptions = 0 for (user in users) { if

    (user.isYoungerThan30WithSubscriptions) { countUsersYoungerThan30WithSubscriptions++; } } WARNING: keep the abstraction level consistent and avoid nested code
  25. fun sumUpUserPoints(): Int { var sumAllPoints = 0 for (user

    in users) { sumAllPoints += user.points sendEmail(user) } return sumAllPoints } No side effects Side effect
  26. Command Query Separation Command Query Output System System System Changed

    state Output (result) Changed state Output (result)
  27. override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(KEY_USER_NAME, username) } Command

  28. fun getProfileInfo(account: SignInAccount): UserProfile { var userProfile = UserProfile() if

    (account != null) { userProfile.name = account.displayName userProfile.email = account.email userProfile.id = account.id } return userProfile } Query
  29. CLASSES Dog Cat Baby Dog Pet

  30. Class organization • A class should be smaller than small.

    • It should have only one responsibility and a single reason to change. • A class collaborates with a few others to achieve the desired system behaviors.
  31. The newspaper metaphor

  32. // var and val control the variable itself // not

    the object instance that is assigned val year = 2019 year = 2020 var age = 18 age = 19 Immutable References
  33. val listOfYears = listOf(2017, 2018, 2019, 2020) listOfYears.add(2021) Read-only collections

  34. data class Movie( val name: String, val studio: String, val

    rating: Float, val releaseYear: Int = 2020 ) Immutable Data Classes Constructor (assign args to props) Only getters toString() hashCode(), equals() copy() final Default arguments
  35. Cohesion • Cohesion is a measure of the degree to

    which the elements of the class/ module are functionally related. • When classes lose cohesion, split them.
  36. Cohesion

  37. Coupling • Coupling is the measure of the degree of

    interdependence between the modules. • This isolation makes it easier to understand each element of the system.
  38. Coupling

  39. Best case scenario Cohesion Coupling

  40. Principles 1. DRY 2. KISS 3. YAGNI 4. SOLID

  41. • Don’t Repeat Yourself • Applicable whenever we copy /

    paste a piece of code D.R.Y.
  42. • Keep It Simple and Stupid • Whenever we want

    to implement a method to do all things K.I.S.S.
  43. • You Ain’t Gonna Need It • Don’t write code

    which is not yet necessary Y.A.G.N.I.
  44. • Single responsibility (SRP) • Open-closed (OCP) • Liskov substitution

    (LSP) • Interface segregation (ISP) • Dependency inversion (DIP) S.O.L.I.D.
  45. OBJECTS AND DATA STRUCTURES

  46. OBJECTS DATA STRUCTURES ➔ hide their data behind abstractions ➔

    expose functions to operate on their data ➔ expose their data ➔ have no meaningful functions Data/object anti-symmetry
  47. class Company { var name: String = "" var address:

    String = "" } DATA STRUCTURE
  48. class Company { var name: String = "" get() {

    if (!field.isEmpty()) { return field.toUpperCase() } return field } var address: String = "" } OBJECT
  49. Train wrecks • Chains of calls are generally considered to

    be sloppy style and should be avoided. • Object interactions spliced into each other can be confusing.
  50. fun getColorOfFolder(folder: Folder): String? { return folder.feature.tag.color.name }

  51. fun getColorOfFolder(folder: Folder): String? { return tagColorName(tagOfFeatureFolder(folder)) } fun getTagColorName(tag:

    Tag): String? { return tag.color.name } fun getTagOfFeatureFolder(folder: Folder): Tag { return folder.feature.tag }
  52. The law of Demeter A module should not know about

    the internals of the objects it interacts with. Demeter Goddess of the Harvest
  53. The law of Demeter Only talk to your friends who

    share your concerns Demeter Goddess of the Harvest
  54. A method f of a class C should only call

    the methods of these: 1. C 2. An object created by f 3. An object passed as an argument to f 4. An object held in an instance variable of C LoD - Formal definition
  55. Law of Demeter A B B is a friend of

    A C C is a friend of B Note: A friend of a friend is a stranger Messages from A to B are OK Messages from A to C are discouraged
  56. fun displayInfoAboutOwner(car: Car) { var city = car.owner.address.city println("${car.owner.name} lives

    in $city") } Car Owner Owner is a friend of Car Address Address is a friend of Owner
  57. App “architecture” Model Room Remote Data source Retrofit SQLite REST

    API Activity / Fragment
  58. Recommended app architecture Activity / Fragment Model Room Remote Data

    source Retrofit SQLite REST API ViewModel LiveData Repository
  59. Room.databaseBuilder(context.getApplicationContext(), UserDatabase::class.java, DATABASE_NAME) .addMigrations(MIGRATION_1_2, MIGRATION_2_3) .fallbackToDestructiveMigrationFrom(4) .build() Fluent APIs

  60. “Tell, Don't Ask” Principle (4) • Object-orientation is about bundling

    data with the functions that operate on that data. • Rather than asking an object for data and acting on that data, we should instead tell an object what to do.
  61. class Balance(var value: Double) class Client { fun alertService(balances: List<Balance>)

    { for (balance in balances) { if (balance.value == 0.0) { // alert } else { // everything is ok } } } }
  62. class Balance(var value: Double, val alertThreshold: Int) { val isExceedsThreshold:

    Boolean get() = value >= alertThreshold }
  63. class Client { fun alertService(balances: List<Balance>) { for (balance in

    balances) { if (balance.isExceedsThreshold) { // alert } else { // everything is ok } } } }
  64. Objects vs Data Tell, don’t ask. Don’t talk to strangers.

    Dealing with Objects? Dealing with Data?
  65. ERROR HANDLING

  66. • Prefer exceptions to returning error codes. • Error handling

    is important, but if it obscures logic, it’s wrong. • In Kotlin we have only unchecked exceptions. • Define dedicated exception classes. • Don’t return or pass null. Error handling
  67. Types/ Nullable Types (recap) @Nullable Type @NotNull Type Java Type

    Type? Type Kotlin ?
  68. val view = activity!!.findViewById<View>(R.id.menu_add) kotlin.KotlinNullPointerException Not null assertion operator !!

    OR Bang! Bang! Boom! operator
  69. fun computeSqrt(number: Double): Double { if(number >= 0) { return

    Math.sqrt(number) } else { throw RuntimeException("No negative please") } } Nothing is something...
  70. fun getMovie(id: Int): Movie { val movie = movieRepository.findMovie(id) return

    movie ?: throw RuntimeException("Movie not found") } Throw exceptions
  71. sealed class MovieSearchResult data class MovieFound(val movie: Movie) : MovieSearchResult()

    object MovieNotFound : MovieSearchResult() object DatabaseOffline : MovieSearchResult() fun getMovie(id: Int): MovieSearchResult { val movie = movieRepository.findMovie(id) return if (movie == null) { MovieNotFound } else { MovieFound(movie) } } Return result class
  72. inputStream.use { outputStream.use { // do something with the streams

    outputStream.write(inputStream.read()) } } “try-with-resources” in Kotlin - initial solution
  73. arrayOf(inputStream, outputStream).use { // do something with the streams outputStream.write(inputStream.read())

    } “try-with-resources” in Kotlin - improved solution
  74. private inline fun <T : Closeable?> Array<T>.use(block: ()->Unit) { //

    implementation } use implementation
  75. COMMENTS We are best friends forever...

  76. Don’t add comments on the bad code, just rewrite it

    until it’s self-explanatory Comments rule
  77. // Check to see if the employee is eligible for

    full benefits if (employee.rate.equalsIgnoreCase("hours") && employee.objectivesDone > 3) if (employee.isEligibleForFullBenefits())
  78. /** Copyright (c) <year> <copyright holders> Permission is hereby granted,

    free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */ Legal comments
  79. fun compareTo(o: Any): Int { if (o is Employee) {

    val employee: Employee = o as Employee val username: String = employee.username val argumentUsername: String = (o as Employee).username return username.compareTo(argumentUsername) } return 1 // we are greater because we are the right type } Explanation of intent
  80. fun makeStandardDateFormat(): SimpleDateFormat? { //SimpleDateFormat is not thread safe, //so

    we need to create each instance independently. val df = SimpleDateFormat("EEE, dd MMM yyyy HH:mm: ss z") df.timeZone = TimeZone.getTimeZone("GMT") return df } Warning of consequences
  81. fun sendEmail(employee: Employee) { //TODO send email } TODO comments

  82. fun updateUserPoints(user: User, points: Int) { try { user.points +=

    points } catch (e: java.lang.Exception) { // User not found } } Mumbling
  83. fun updateUserPoints(user: User, points: Int) { try { user.points +=

    points } // try catch (e: java.lang.Exception) { // User not found println("User not found") } // catch } Redundant & closing brace comments
  84. class Log { /** The data. */ var data: String

    = "" /** The number of data. */ var numberOfData = 0 /** * Secondary constructor. */ constructor(data: String) { } } Noise and scary noise comments
  85. Every time you write a comment, a cat is scared

    somewhere...
  86. CODE REVIEW

  87. CODE REVIEW

  88. 1. Help to improve the quality and consistency of the

    code 2. Exchange of knowledge and best practices 3. Learn the code base 4. New perspective(s) on your code 5. Learn new tips and tricks about writing code Code Review Advantages
  89. Reviewer Author <Code>

  90. Author

  91. • Make sure you understand your task • Refactor the

    code if it’s unreadable • Write tests and follow the team conventions • Format your code before commit it Writing the code
  92. The boy scout rule Leave the campground cleaner than you

    found it.
  93. • Add relevant commit comments • Send pull requests often

    • Have minimum 2 reviewers (one is senior) Before the code review
  94. • Be humble • You are on the same side

    with your reviewer(s) • Know when to unlearn the old habits After the code review
  95. Reviewer

  96. • I think… • I would… • I believe… •

    I suggest... Use I… comments
  97. • Have you consider using… ? • What do you

    think about… ? • Have you tried to… ? Ask questions
  98. • This code… • This function… • This line of

    code... It’s about the code, not about the coder
  99. Feedback equation* Observation of a behavior Impact of the behavior

    Question or Request I observed this function has 60 lines. This makes it difficult for me to understand the logic. I suggest extracting a part of the code into other functions and give them relevant names. * Defined by Lara Hogan
  100. 1. Define with your team a set of conventions 2.

    Justify technology use 3. Enforce good practices (XP) 4. Question until you understand 5. Criticize ideas, not people 6. Testing, testing, testing 7. Integrate early, integrate often 8. Emphasize collective ownership of code 9. Prioritize and actively evaluate trade-offs 10. Listen to users My summary
  101. Coding is not a sprint It’s a marathon

  102. CREDITS: This presentation template was created by Slidesgo, including icons

    by Flaticon, and infographics & images by Freepik THANKS Do you have any questions? @magdamiu
  103. 1. Article “CommandQuerySeparation” by Martin Fowler 2. “Law of Demeter:

    Principle of Least Knowledge” by Professor Karl, Northeastern University 3. Article “Breaking the Law of Demeter is Like Looking for a Needle in the Haystack” by Miško Hevery 4. Article “TellDontAsk” by Martin Fowler 5. Article “One Assertion Per Test” by Dave Astels 6. The Tragedy Of Checked Exceptions by Howard Lewis Ship 7. Exceptions are Bad by Jed Wesley-Smith 8. Checked exceptions I love you, but you have to go by Miško Hevery If you want to learn more...