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
code Learn programming syntax more quickly How to not forget things Read complex code On thinking about code Reaching a deeper understanding of code On writing code better Get better at naming things Avoiding bad code and cognitive load Getting better at solving complex problems On collaborating on Code Getting better at Handling interruptions How to onboard new developers
programming language, concept, or framework • When reading unfamiliar code or code that you wrote a long time ago • Whenever you start to work in a new business domain
void mian(Int n) { System.out.println(Integer.toBinaryString(n)); } } Lack of easy-to-access information How exactly toBinaryString() works is not readily available Needs to be found somewhere else in the code
LET B$ = "" FOR N1 = N2 TO 0 STEP 0 LET N2 = INT (N1 / 2) LET B$ = STR$ (N1 - N2 * 2) + B$ LET N1 = N2 NEXT N1 PRINT B$ RETURN Lack of processing power in the brain We cannot oversee all the small steps that are being executed
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 LTM • Can store your memories for a very long time • Hard drive of your brain Working Memory • The actual “thinking”, happens in working memory • Processor of the brain 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)
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 That process is called tracing
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) -> 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
following Java 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]); } } }
look at your reproduced code • Annotate which parts of the code you think came from your short-term memory directly and which parts were retrieved from long-term memory • Compare with someone else Information retrieved from your LTM depends on what you have stored there : Less experienced in Java is likely to retrieve a lot less from their LTM
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
experiment Experts and average chess players were asked to remember a chess setup Expert players were able to recall more pieces than average players Experts grouped info in logical ways -> chunks Fit into only 1 slot in STM
and try to remember it as best as you can: Reproduce it on paper abk mrtpi gbar • Easier than the first one! • Because consists of letters that you recognize • 2 sentences were the same length: 3 words, 12 characters, 9 different characters
and try to remember it as best as you can: Reproduce it on paper cat loves cake • Here you can chunk the characters into words. • You can then remember just three chunks: “cat,” “loves,” and “cake.” Like the chess experts
for performing maintenance tasks when the programmers knew that the pattern was present in the code • Write comments (chunk larger pieces of code) High-level comments like “this function prints a given binary tree in order” Low-level comments such as “increment i (by one)” : create a burden on the chunking process The more information you have stored about a specific topic the easier it is to effectively divide information into chunks.
a program that help a programmer to understand what the code does A line of code that your eye falls on which "Now I see” • Act as a trigger for programmers to confirm or refute hypotheses about the source • Simple beacons : self-explaining syntactic code elements Meaningful variable names Operators such as +, >, && / structural statements if, else, and • Compound beacons : larger code structures comprised of simple beacons
a tree class Node: def __init__(self, key): self.left = None self.right = None self.val = key # A function to do in-order tree traversal def print_in_order(root): if root: # First recur on left child print_in_order(root.left) # then print the data of node print(root.val), # now recur on right child print_in_order(root.right) print("Contents of the tree are") print_in_order(tree) • Comments using the word “tree” • Variables called root and tree • Fields called left and right • String contents in the code that concern trees
large extent how efficiently you can read and understand code • The more concepts, data structures, and syntax you know • The more code you can easily chunk, and thus remember and process
Simply paper cards or Post-its of which you use both sides One side has a prompt on it The thing that you want to learn The other side has the corresponding knowledge on it
to practice • Use Apps like Brainscape : allow you to create your own digital flashcards They will remind you when to practice again • After a few weeks, your syntactic vocabulary will have increased Expanding the set of flashcards • When you’re learning a new programming language, framework, or library • When you’re about to Google a certain concept Thinning the set of Flashcards • Keep a little tally on each card of your right and wrong answers • Demonstrate what knowledge is already reliably stored in your long-term memory
memories : • Retrieval practice : actively trying to remember something Retrieval is a more formal word for remembering • Elaboration : actively thinking / connecting new knowledge to existing memories Thinking about what you want to remember : Relating it to existing memories • Making the new memories fit into schemata already stored in your LTM Using elaboration to learn new programming concepts For example, you might try thinking of related concepts in other programming languages • Thinking of alternative concepts in Python or other programming languages • Or thinking of how this concept relates to other paradigms Read / hide code exercises
always have trouble remembering • Make a set of flashcards for each of the concepts and try using them You can also do this collaboratively in a group or team, where you might discover that you are not the only one that struggles with certain concepts.
way that science knows to prevent forgetting is to practice regularly. Each repetition strengthens your memory. You remember the longest if you study over a longer period • In contrast with formal education, where we try to cram all the knowledge into one semester • Revisiting your set of flashcards once a month Enough to help your memory in the long run / relatively doable!
problem What happens in the working memory when we read code? • Like STM the working memory is only capable of processing between 2 and 6 things at a time • In the context of working memory, this capacity is known as the cognitive load.
many cases these refactoring are temporary • Only meant to allow you understand the code • Can be rolled back once your understanding is solidified Refactoring example – replace unfamiliar language constructs Simply rewrite the code to use a regular structure temporarily Optional<Product> product = productList.stream() .filter(p -> p.getId() == id) .findFirst(); public static class Toetsie implements Predicate <Product>{ private int id; Toetsie(int id){ this.id = id } boolean test(Product p){ return p.getID() == this.id; } } Optional<Product> product = productList.stream(). filter(new Toetsie(id)). findFirst(); If new to lambdas Remove extraneous cognitive load 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
the code, or convert it to a PDF • Open it on a tablet so you can make annotations digitally • Circle all the variables Link similar variables • Draw lines between occurrences of the same variable • Helps you to understand where data is used in the program Now have a reference that you can refer to for information about the code’s structure
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 ? 1. Make a list of all the variables 2. Create a table : give each variable its own column 3. Add 1 row for each distinct part of the execution of the code 4. Execute each part of the code : write down the value each variable has afterward in the correct row and column.
in the previous sections : create both a dependency graph and a state table for this Java program public class Calculations { public static void main(String[] args) { char[] chars = {'a', 'b', 'c', 'd'}; // looking for bba calculate(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0); } static void calculate(char[] a, int k, Predicate<int[]> decider) { int n = a.length; if (k < 1 || k > n) throw new IllegalArgumentException("Forbidden"); int[] indexes = new int[n]; int total = (int) Math.pow(n, k); while (total-- > 0) { for (int i = 0; i < n - (n - k); i++) System.out.print(a[indexes[i]]); System.out.println(); if (decider.test(indexes)) break; for (int i = 0; i < n; i++) { if (indexes[i] >= n - 1) { indexes[i] = 0; } else { indexes[i]++; break; } } } }
but it doesn't apply to me I learned a lot and it applies to me Level of knowledge acquired Applicability of this knowledge I didn't learn much and it doesn't apply to me I can apply what little I have learned