Slide 1

Slide 1 text

Yoan Thirion #sharingiscaring Clean Code from the point of view of cognition

Slide 2

Slide 2 text

https://bit.ly/3Ok0Hnf https://pyxis-suisse.ch/notre-equipe/coaching-agile-technique/

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

Yoan Thirion #sharingiscaring Clean Code

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

Yoan Thirion #sharingiscaring Code Reading

Slide 8

Slide 8 text

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]); } } }

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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.

Slide 12

Slide 12 text

Yoan Thirion #sharingiscaring How can we improve?

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

Yoan Thirion #sharingiscaring Chunking ?

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

Yoan Thirion #sharingiscaring Write “chunkable” code Help our STM

Slide 22

Slide 22 text

Yoan Thirion #sharingiscaring Design Patterns The holy origins The holy structures CREATIONAL BEHAVIORAL STRUCTURAL The holy behaviors

Slide 23

Slide 23 text

Yoan Thirion #sharingiscaring Design Patterns

Slide 24

Slide 24 text

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.

Slide 25

Slide 25 text

Yoan Thirion #sharingiscaring Write comments High-level https://github.com/adamtornhill/code-maat

Slide 26

Slide 26 text

Yoan Thirion #sharingiscaring Write comments Low-level A burden on the chunking process...

Slide 27

Slide 27 text

Yoan Thirion #sharingiscaring Be better at reading complex code ?

Slide 28

Slide 28 text

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!!!

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

Yoan Thirion #sharingiscaring Areas related to natural languages Technique 4 Text comprehension strategies applied to code Reading code is like reading text

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

Yoan Thirion #sharingiscaring Technique 4 Text comprehension strategies applied to code

Slide 35

Slide 35 text

Yoan Thirion #sharingiscaring Technique 4 Text comprehension strategies applied to code

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

Yoan Thirion #sharingiscaring Technique 5 AI Assistant https://www.cursor.so/

Slide 38

Slide 38 text

Yoan Thirion #sharingiscaring Write better code (from the cognition POV)

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

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 :

Slide 42

Slide 42 text

Yoan Thirion #sharingiscaring Code Smells create a lot of cognitive load https://refactoring.com/catalog/

Slide 43

Slide 43 text

Yoan Thirion #sharingiscaring Long parameter list https://refactoring.com/catalog/ Overload our STM Primitive Obsession Comments Cyclomatic Complexity… Overload our WM

Slide 44

Slide 44 text

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 PrendreLapéro(Func 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...

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

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/

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

Yoan Thirion #sharingiscaring We write code for humans, Not machines

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

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