Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

Clean Code from the Cognition Point of View

Yoan
February 01, 2024

Clean Code from the Cognition Point of View

Talks made during a Tech Talk at Swissquote

Yoan

February 01, 2024
Tweet

More Decks by Yoan

Other Decks in Education

Transcript

  1. Yoan Thirion #sharingiscaring My Intent - Understand how our brains

    work - Share with you techniques and practices that will enable us to become better at both reading and writing code
  2. Yoan Thirion #sharingiscaring Cognition “Cognition encompasses all aspects of intellectual

    functions and processes such as: perception, attention, thought, imagination, intelligence, the formation of knowledge, memory and working memory, judgment and evaluation, reasoning and computation, problem-solving and decision- making, comprehension and production of language.” - Wikipedia
  3. Yoan Thirion #sharingiscaring A word on the book Learn how

    to optimize your brain’s natural cognitive processes to • Read code more easily • Write code faster • Pick up new languages in much less time https://www.manning.com/books/the-programmers-brain Released on September 7, 2021 Dr Felienne Hermans ü Associate professor at the Leiden Institute of Advanced Computer Science ü @felienne
  4. Yoan Thirion #sharingiscaring Let's test your brain Look at the

    following program for 3 minutes Try to reproduce it as best as you can public class InsertionSort { public static void main(String[] args) { int[] array = {45, 12, 85, 32, 89, 39, 69, 44, 42, 1, 6, 8}; int temp; for (int i = 1; i < array.length; i++) { for (int j = i; j > 0; j--) { if (array[j] < array[j - 1]) { temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; } } } for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } } }
  5. Yoan Thirion #sharingiscaring Various cognitive processes 1) Information coming into

    your brain. 2) Information that proceeds into your STM 3) Information traveling from the STM into the working memory 4) Where it’s combined with information from the LTM Long Term Memory (LTM) • Can store your memories for a very long time • Hard drive of your brain Short Term Memory (STM) • Used to briefly hold incoming information • RAM or a cache that can be used to temporarily store values • Just a few items fit in STM (<12) Information Filter STM LTM WM Working Memory (WM) • The actual “thinking”, happens in working memory • Processor of the brain 1 2 3 4
  6. Yoan Thirion #sharingiscaring What happens when you read code? Use

    LTM to retrieve knowledge (Keywords for example) Use STM to store some of the info we encounter Use working memory : trying to mentally execute the code / understand what is happening TRACING Information Filter STM LTM WM 1 2 4 3
  7. Yoan Thirion #sharingiscaring What happens when you read code? LTM

    STM Filter STM LTM WM 1 2 4 3 public class InsertionSort { public static void main(String[] args) { int[] array = {45, 12, 85, 32, 89, 39, 69, 44, 42, 1, 6, 8}; int temp; for (int i = 1; i < array.length; i++) { for (int j = i; j > 0; j--) { if (array[j] < array[j - 1]) { temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; } } } for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } } } int[] array int temp 2 boucles public static void main(String[] args) for (int i = 1; i < array.length; i++)… public class InsertionSort { public static void main(String[] args) { int[] array = {45, 12, 85, 32, 89, 39, 69, 44, 42, 1, 6, 8}; int temp; for (int i = 1; i < array.length; i++) { for (int j = i; j > 0; j--) { if (array[j] < array[j - 1]) { temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; } } } for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } } } Reproduced code The information extracted from our LTM depends on what we have stored in it. A person with less experience in Java is likely to extract much less information from their LTM.
  8. Yoan Thirion #sharingiscaring Why reading so important ? Research indicates

    that almost 60% of programmers’ time is spent understanding code, rather than writing code Reading code Writing code Improving how quickly we can read code (without losing accuracy) Can help us improve our programming skills substantially Reading code is done for a variety of reasons: • add a feature • find a bug • build an understanding of a larger system https://ieeexplore.ieee.org/abstract/document/7997917
  9. Yoan Thirion #sharingiscaring Why is reading unfamiliar code hard? Time

    limitation Cannot hold information for more than 30 seconds Short Term Memory Size limitation Just a few slots available for information 7 +/- 2 Some research indicates that its capacity could be smaller : just 2 to 6 things A memory issue
  10. Yoan Thirion #sharingiscaring Overcoming size limits in your memory De

    Groot first chess experiment Experts grouped info in logical ways : CHUNKS http://snitkof.com/cg156/chesschunkingtheory.php Fit into only 1 slot in STM
  11. Yoan Thirion #sharingiscaring De Groot’s experiments on programmers In 1981

    Katherine McKeithen, repeat de Groot’s experiments on programmers : Main takeaway : beginners will be able to process a lot less code than experts Nombre de lignes de code https://www.researchgate.net/publication/222462455_Knowledge_Organization_and_Skill_Differences_in_Computer_Programmers
  12. Yoan Thirion #sharingiscaring Chunking 1 Look at this sentence for

    five seconds and try to remember it as best as you can: Reproduce it on paper
  13. Yoan Thirion #sharingiscaring Chunking 2 xqlxxbwukc dhjp Easier than the

    first one! Because consists of letters that you recognize 2 sentences were the same length: 2 words, 14 characters, 10 different characters Look at this sentence for five seconds and try to remember it as best as you can: Reproduce it on paper
  14. Yoan Thirion #sharingiscaring Chunking 3 swissquote 2024 Here you can

    chunk the characters into words. You can then remember just two chunks: “swissquote”, “2024”. Like the chess experts Look at this sentence for five seconds and try to remember it as best as you can: Reproduce it on paper
  15. Yoan Thirion #sharingiscaring Design Patterns The holy origins The holy

    structures CREATIONAL BEHAVIORAL STRUCTURAL The holy behaviors
  16. Yoan Thirion #sharingiscaring Write comments Chunk larger pieces of code

    The more information you have stored on a specific subject the easier it is to chunk information efficiently.
  17. Yoan Thirion #sharingiscaring Working memory Short-term memory applied to a

    problem When reading code, the working memory is only capable of processing 2 to 6 "things" at a time... In the context of working memory, this capacity is known as the cognitive load!!!
  18. Yoan Thirion #sharingiscaring Technique 1 Refactor code to reduce cognitive

    load Temporary refactoring (most of the time) to understand the code Example – replace unfamiliar linguistic constructions If you do not know the famous “functors”, “monads”, … What is easy to read depends on your prior knowledge No shame in helping yourself understand code by translating it to a more familiar form Automated refactorings
  19. Yoan Thirion #sharingiscaring Technique 2 Dependency graph https://annotate.codereading.club/ Annotate variables

    Draw lines between occurrences of the same variable Helps you to understand where data is used in the program
  20. Yoan Thirion #sharingiscaring Technique 3 State table A state table

    focuses on the values of variables rather than the structure of the code. It has columns for each variable and lines for each step in the code. How to ? Make a list of all the variables Create a table : 1 column / variable 1 line for each mutation Execute each part of the code
  21. Yoan Thirion #sharingiscaring Areas related to natural languages Technique 4

    Text comprehension strategies applied to code Reading code is like reading text
  22. Yoan Thirion #sharingiscaring Text comprehension strategies Activating Actively thinking of

    related things to activate prior knowledge Determining importance Deciding what parts of a text are most relevant Visualizing Drawing diagrams of the read text to deepen understanding Inferring Filling in facts that are not explicitly given in the text Summarizing Creating a short summary of a text Questioning Asking questions about the text at hand Monitoring Keeping track of your understanding of a text
  23. Yoan Thirion #sharingiscaring Chunking Pipeline Extract method Chunking master Functional

    pipeline for the Pipeline Object Calisthenics : 1 level of indentation https://github.com/advent-of-craft/advent-of-craft/blob/main/solution/day07/docs/step-by-step.md
  24. Yoan Thirion #sharingiscaring Get better at naming things Good names

    help to activate your LTM to find relevant information that you already know about the domain of the code Bad names can lead you to make assumptions about the code leading to misconceptions
  25. Yoan Thirion #sharingiscaring Why identifier names matter? Huge part of

    our code = NAMES (72%) Names play a role in code reviews 1 in four code reviews contained remarks related to naming… (Miltiadis Allamanis) Names are the more accessible form of documentation
  26. Yoan Thirion #sharingiscaring A good name can be defined syntactically

    Simon Butler, associate Senior Lecturer at the Open University in the UK, created a list of issues with variable names :
  27. Yoan Thirion #sharingiscaring Long parameter list https://refactoring.com/catalog/ Overload our STM

    Primitive Obsession Comments Cyclomatic Complexity… Overload our WM
  28. Yoan Thirion #sharingiscaring Linguistic Anti Patterns https://veneraarnaoudova.com/linguistic-anti-pattern-detector-lapd/LAs/ Methods that say

    more than they do Identifiers whose name says that the opposite than the entity contains Methods that do more than they say Methods that do the opposite than they say var elements = retrieveElements(); private Product retrieveElements() { return products.last(); } public Either<Error, PartieDeChasse> PrendreLapéro(Func<DateTime> timeProvider) { _chasseurs.ForEach(c => c.SortirDeLaPartie(this)); Status = Apéro; EmitEvent("Petit apéro", timeProvider); return this; } private bool Exists(string chasseur) { var found = false; foreach (var c in _chasseurs) { if (c.Nom == chasseur) { return found; } } return false; } var isValid = 42; Impossible to chunk correctly...
  29. Yoan Thirion #sharingiscaring Her findings She studied their occurrence in

    7 open-source projects : 11% of setters: also return a value in addition to setting a field 2,5% of methods: method name and the corresponding comment gave opposite descriptions of the working of the method 64% of identifiers starting with ‘is’ turned out not to be Boolean
  30. Yoan Thirion #sharingiscaring How to protect ourselves? Keeping them in

    mind helps us avoid them (Code Smells, LAP, ...) Checklists for Code Reviews Learning together: code katas, craft / technical coaching Automate their detection Static code analysis / Behavorial code analysis [Fact] public void NoGetMethodShouldReturnVoid() => Methods() .HaveNameMatching("Get[A-Z].*", useRegularExpressions: true).Should() .NotHaveReturnType(typeof(void)) .Check(); [Fact] public void IserAndHaserShouldReturnBooleans() => Methods() .HaveNameMatching("Is[A-Z].*", useRegularExpressions: true).Or() .HaveNameMatching("Has[A-Z].*", useRegularExpressions: true).Should() .HaveReturnType(typeof(bool)) .Check(); [Fact] public void SettersShouldNotReturnSomething() => Methods() .HaveNameMatching("Set[A-Z].*", useRegularExpressions: true).Should() .HaveReturnType(typeof(void)) .Check(); [Fact] public void FieldsShouldNotUseIncorrectSyntax() => FieldMembers().That() .HaveNameMatching("__", useRegularExpressions:true) .Should() .NotExist() .Check(); https://github.com/ythirion/archunit-examples/
  31. Yoan Thirion #sharingiscaring Abstract Code Smells / LAP Write chunkable

    code (Patterns, naming, high level comments, …) Improve in code reading techniques Automate LAPs detection A scientific endorsement of the feeling we had with Clean Code
  32. Yoan Thirion #sharingiscaring More to cover… Flashcards LTM (Automation) Handle

    interruptions Better at on-boarding … https://yoan-thirion.gitbook.io/knowledge-base/software-craftsmanship/the-programmers-brain
  33. Yoan Thirion #sharingiscaring Thank you https://github.com/ythirion Training “craft” les 9

    et 10 avril à Genève https://github.com/advent-of-craft/advent-of-craft