<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tove Brantberg on Medium]]></title>
        <description><![CDATA[Stories by Tove Brantberg on Medium]]></description>
        <link>https://medium.com/@tove.brantberg?source=rss-58df0f97a8f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*izG9Es233p2cK2f7J_agMA.png</url>
            <title>Stories by Tove Brantberg on Medium</title>
            <link>https://medium.com/@tove.brantberg?source=rss-58df0f97a8f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:40:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tove.brantberg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reflection based QA Tool]]></title>
            <link>https://medium.com/toca-boca-tech-blog/reflection-based-qa-tool-821291073178?source=rss-58df0f97a8f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/821291073178</guid>
            <category><![CDATA[qa-tool]]></category>
            <dc:creator><![CDATA[Tove Brantberg]]></dc:creator>
            <pubDate>Wed, 10 May 2023 08:35:55 GMT</pubDate>
            <atom:updated>2023-05-10T08:35:55.869Z</atom:updated>
            <content:encoded><![CDATA[<p>After a project has been on the road for a few years, it is almost inevitable for the tooling to start to age and become unwieldy to work with. Tools are often built for a need that mutates along the way, and are rarely built with a robust base - when the need for debug tools arises, they are needed right then and not after a technical planning sprint. Additionally, the people who end up implementing tools is a very diverse group from QA technicians to server side devs to game devs. This is not a problem, in itself, but will eventually become one when people inadvertently pull to different directions.</p><p>At Toca, we reached the point where our tools started to feel cumbersome. Our QA tool was controlled by one monolith of a class (2600 lines!) with only a few ‘sets of tools’ having been implemented into classes of their own. UI code and functionality were also mixed together, making most of the lines in the monolith concerned with initialising buttons. Then there was the fact that the actual menu within the game itself had been a couple of pages in the beginning but now had 18 of them, making it slow to find the tool you were looking for. The final nail to the coffin was that the tools hadn’t been maintained — when QA went through them button by button, half of them were not even working anymore.</p><p>The QA tool had all the hallmarks of something that had grown too big for its foundations. It had been great in the beginning, but we’d clearly reached the point where we could either start fixing it piece by piece or should do something more drastic.</p><p>In the end, it came down to ‘drastic’ being easier. Going through all tools and fixing them was doable but would take time. We could’ve quite easily broken the monolith down into more classes and improved the organisation of code side of things. Breaking up the connection between visual code and the functionality, however, would be a lot more work. And if we started on that, we might as well start afresh and not be chained by the restraints of the old system.</p><p>Our QA Tool v. 2.0 work began with the following guidelines:</p><ul><li>UI and functionality should be separated.</li><li>We wanted to avoid monoliths now <em>and in the future</em>. Something that would encourage good separation and structure would be crucial (we wanted to ‘make it hard to do wrong’).</li><li>Finally, we still wanted to encourage the concept of ‘anyone can add to the tool’. Our original tool was built by a QA Engineer (Go Roy!)— we wanted something that QA would feel welcome to continue working with, and extend the same to any other group touching the code and needing tools of their own.</li></ul><p>From these ideas, we distilled the core concept: UI building would be handled in one place, functionality elsewhere. Something would act as a glue between them. For the glue, we chose reflection.</p><p>Reflection is not performant enough to work in the normal UI but for a QA tool it was perfectly fine. It also allowed us to create the QA functionality without having to know or care about how the UI layer would look like or be built. This, we surmised, would fulfil the criteria of ‘easy to extend’. Reflection needed to be touched and handled only by the core system and it wouldn’t need much maintenance after the initial setup. Rest of the code could now be virtually free from UI concerns and thus tighter and lighter.</p><p>(On the visual UI side of things, we wanted to lean in harder to the Toca Boca aesthetic. Why can’t our tools be playful and fun? We did a similar overhaul to the visuals as we did to the code. We added colours and a little whimsy to brighten our days 🎉 However, details of this and other UX concerns belong to a different blog post.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FcA4s_3_YTgwD4Jr8n1Jg.png" /></figure><p><strong>QA Tool v. 2.0 breakdown</strong></p><p>The new QA tool is divided into four distinct elements: <em>The QA Tool Collections</em>, <em>Custom Attributes</em>, <em>The Reflection Engine</em> and the <em>UI Factory</em>. The QA Tool Collections are scripts where we implement our ‘tools’. These tools are decorated with Attributes that carry visual information (“this tool should be button”). The Reflection Engine collect these tools and their attributes and passes this information on to an UI Factory. The UI Factories are responsible for the visual implementation in each environment (such as in app and web).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSEj1sRpNlRBsAc27ZazIA.png" /></figure><p><strong>The QA Tool Collections</strong></p><p>We wanted to encourage a decentralised approach. Instead of having all tools end up in a big monolith, we wanted each area of the game to have their own little classes. This became possible with the use of reflection. With reflection, we didn’t need to tie the tool-scripts together in a concrete way: no lists needed, and there would be no reason to ‘skip corners and just have them in the same file’ anymore.</p><p>We went from having a big QA-file to things like ‘Home Designer Tools’, ‘Banner Tools’ and ‘Location Tools’. The only thing all of these tool collections had to have in common was that they implemented the abstract QAToolCollection-base class. This allowed our Reflection Engine to pick them up easily. Where these scripts physically lived and what they were named didn’t really matter. Splitting and adding new classes became simple — just plug in the abstract base class and get to writing.</p><p>In these tool collections, each QA tool is represented by a method that is decorated with attributes. The attributes is all the ‘UI’ code needed, allowing the classes to stay small. Implementing a new QA tool now means creating a function that covers the QA functionality and then adding an appropriate visualisation option with an attribute. As long as this function is in a QAToolCollection-script somewhere, it will be picked up and added to the tool automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GI4mKnGRbBxkBnDD288kbw.png" /><figcaption>Code needed to create a “Unlock All” button in the GameMode page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Clhf4QIwZhVoOnWV7vSKmw.png" /><figcaption>How the Unlock All button looks like in game.</figcaption></figure><p><strong>The Reflection Engine</strong></p><p>The heart of our new QA tool is the Reflection Engine. It’s simply one script that does the following: it collects all the tools by using the abstract base class as a guide, then parses the found tools into what we call ‘QA commands’ using the attributes, and then passes a list of QA commands to the UI Factories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed9f4e000c1316cfab57a3bab045ce8e/href">https://medium.com/media/ed9f4e000c1316cfab57a3bab045ce8e/href</a></iframe><p>The parsing step wraps the incoming data in a way that makes it easier to implement by the UI layer. The end result, QA Command, has an access for getting the name (all buttons in the QA tool will always have a name) and tooltip (optional to implement but available for all types of commands). It also includes the method that the UI can call when the user interacts with it.</p><p>Finally, the QA command will also carry information about which category a command belongs to. Category is an attribute like everything else in our system. It can be applied to a class (ie. a QAToolCollection) or a method. When we create a QA Command for a method, we pass in all relevant categories (found in its class or found decorating the method itself). When the UI is then built in the factory, these categories are used to create the different pages of the tool.</p><p><strong>UI Factory</strong></p><p>There is an UI Factory for each environment. Only the one within the game is currently fully implemented and will be the focus here. The idea with the separation of logic and UI is that we can add factories as the need arises. Each factory needs to implement their own version of all the ‘visual elements’ defined by the attributes but can share the underlying ‘QA commands’ with each other. The factory’s job is to interpreted the attributes and provide a way for the user of the QA tool to trigger the different commands.</p><p>In our case, the in-game factory works with Unity UI prefabs. We have prefabs for things like toggles, buttons, date pickers and input fields. The factory takes the incoming list of QA Commands and looks for which attribute they have, passes that to a builder and then adds the resulting element to the UI. All this is very simple for simple elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96159dd559ef17dba3408a800c969e1a/href">https://medium.com/media/96159dd559ef17dba3408a800c969e1a/href</a></iframe><p>Finally, the UI factory has control over some environment specific ‘navigational’ elements. These vary between the different environments — web tool has different assumptions of screen space and interaction method and navigates differently. In the in-game factory, we create a central menu for the different categories by using the same list of QA commands provided (building a dictionary out of it), added a search (still using the same dictionary, the search can target both the visible names and the method names wrapped within the QA commands) and even favouriting functionality for quick access to the commands the user uses the most! However, more detail about this work belongs to an UX blog post.</p><p><strong>Custom Attributes</strong></p><p>As we were planning our new QA system, we focused on distilling the QA tool down to its essence. What we came up with was: <em>A QA tool is a collection of ‘commands’ with a simple user interface that allows accessing them</em>. These commands sometimes need some information to act correctly (say location name when trying to decide where to teleport to) but most often are a button or a toggle to change some internal state.</p><p>We found that attributes would allow us to contain all this information. The attributes we created have three elements that intertwine. The attribute itself defines a certain type of UI component: [Button]. It accepts information relevant to the creation of the UI: [Button(“Name”)]. Finally, this attribute is connected to a method, which is the ‘QA action’. When we build the UI, we use the attribute to pass on the key information. We know the QA action wants to be visualised as a button, the button should use the name specified, and when pressed, the QA action should trigger.</p><p>Then there are attributes that have a bit more complexity to them. A [Toggle] defines a QA action that has two states. In order to have the UI state reflect the underlying data, the attribute accepts a link to this data: [Toggle(DataSource = nameof(dataPoint))]. The use of reflection here allows us to pass in a name of a field, property or a function, giving us flexibility in defining our datasources. For the person adding new QA tools, the complexity is still kept minimal. They only need to focus on defining something that returns a bool-state: the guts of the attribute handles the rest.</p><p>On the surface, the logic is a one-liner. The actual complexity is hidden within the attributes. All our custom attributes extend from a base class that encapsulates the ‘converting’ of DataSources. This means that for each new attribute we create, we simply need to focus on the converting of the extracted data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1ec2637516d314bd3c635a492fcca83/href">https://medium.com/media/d1ec2637516d314bd3c635a492fcca83/href</a></iframe><p>The Extract Data that happens within the base class is once again based on reflection. Using reflection, it finds the field or method passed into the DataSource of the attribute and extracts the ‘data’ out of it. It is this data that is passed onto the PostExtractData handled within each individual attribute where it gets it final, usable form.</p><p>The examples here are of the simple cases, but we’ve managed to push the system to create popups that contain other QA Commands, collections of buttons that are automatically created from a single source (say a enum) and so on. Reflection allows us to freely select our sources and all we need to do is to convert the data into our desired format as we build the UI.</p><p><strong>Evaluation</strong></p><p>We are now at the beginning of the journey of using the QA tool 2.0. We have converted the entirety of our old tool to the system and can report that it was a quick and painless process. It took only a week to move everything to the new system! During this time, we improved and did fine-tuning of our attributes so it is very likely that it will get even faster to add new tools. Requesting a new tool to tool being available has gotten down to a matter of hours.</p><p>Initial feedback has been that people are happy to work with the new system. Server devs are excited they can add their tools without having to understand how the UI system is setup in Unity (something that caused tools to be slow and cumbersome to implement for them!). QA engineers have also given the thumbs up. We feel confident in saying that the new system is easy to grasp for the ‘end user’. The clearest sign of success of them all is that we’ve started adding new tools and updating the existing ones — creating tools is no longer a major project but something that can be included in a normal feature delivery flow.</p><p><strong>Challenges</strong></p><p>We are happy with our choice of using reflection. The code structure is light and easy to deal with. However, there are still some limitations to our approach. Because all data passes through our attributes and the visualisation and functionality have been completely severed from each other, it forces the tools to be data only — custom visualisations are more complicated now.</p><p>The biggest issue we have is dealing with ‘live’ data. Since most tools do not need constant querying, we did not implement that into the base system. This means that anything that needs frequent updating (such as FPS meters) become ‘custom implementations’. We did foresee that the attribute based system would be too rigid to cover all situations so we did add a [CustomUI] attribute that allows passing in a custom builder. So far we’ve only needed in a couple of cases but the future will show if we’ll start abusing the custom alternative.</p><p>Finally, for those programmers who end up ‘extending’ the system and thus interacting with the reflection, the new system is technically more complicated than the old one — mainly because most of us are less familiar with reflection. Anything that can build upon something already implemented — a group of toggles isn’t that different from group of buttons — is still pretty straightforward. Everything that is more complex than that does demand understanding of reflection and can be bit of a puzzle. The main challenge we’ve encountered is the lack of good error message by default. We have added error messages to some places now, but it was something we didn’t take into account in the first iteration and could do more work on.</p><p><strong>Final words</strong></p><p>We are very happy now that we took the time to rethink our QA tool — not just what it should have in it but also how it should be built from the very ground up. Switching to reflection meant rebuilding everything and was only possible because the stars were aligned. We didn’t balk at the challenge mainly because we knew we had time to restart if it wouldn’t work out. The QA tool rework was a ‘summer project’ that was completed when there was a lull in the schedule otherwise. It was an unexpected opportunity that ended up well worth the few months we poured into it (from thinking to implementing to converting, including graphics overhaul). Would we have needed to update the tool with a tighter schedule, we would probably not have dared to go this big and drastic with the changes.</p><p>Hopefully, seeing our take on a reflection based QA tool inspires someone else to give it a try. Our experience has been positive almost from the get go. Most programmers in the team had basically no experience of working with reflection but all it really took was one champion who believed in it and who pushed us to learn something new (Thanks Sean!). And the initial goal of the QA tool still holds true: Anyone can add to the tool. Most users never need to even know what is going on in the reflection layer. It is a new challenge for those who need to — but definitely one that can be overcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821291073178" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toca-boca-tech-blog/reflection-based-qa-tool-821291073178">Reflection based QA Tool</a> was originally published in <a href="https://medium.com/toca-boca-tech-blog">Toca Boca Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Case of the Missing Babies]]></title>
            <link>https://medium.com/toca-boca-tech-blog/the-case-of-the-missing-babies-d3ba28f7e9d4?source=rss-58df0f97a8f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3ba28f7e9d4</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[toca-life-world]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Tove Brantberg]]></dc:creator>
            <pubDate>Thu, 04 May 2023 13:01:11 GMT</pubDate>
            <atom:updated>2023-05-04T13:01:11.824Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or debugging in an open play environment in Toca Life World</h4><p><strong>The Background:</strong></p><p>Toca Life World is a 2.5d virtual world where players can freely move characters and objects in. The world is made out of multiple locations. Players can move characters between these through the sidewalk, something of a storage space that can be accessed from every location<em>. </em>There are two flavours of characters in Toca Life World: characters created by Toca that belong to a scene and a set number of user created characters that players can create themselves. The characters come in different age categories. And most importantly to our case, the baby category is unique because characters from other categories can carry them.</p><figure><img alt="An apartment in Toca Life World with two characters sitting on a couch while multiple characters stand on a sidewalk at the lower edge of the picture." src="https://cdn-images-1.medium.com/max/1024/1*yJ4UzYo7OJEQ2TAlDJTD9Q.png" /><figcaption>A location in Toca Life World with the sidewalk visible.</figcaption></figure><p><strong>The Case:</strong></p><p>Reports were coming in that babies were disappearing under mysterious circumstances. The disappeared babies were gone without traces — no obvious crash, no bug trace beyond player feedback, not even repro steps to follow… Then, one faithful day, we accidentally triggered something in editor that gave us a clue. Time for an investigation!</p><p><strong>The investigation:</strong></p><p>What we knew about the disappearing babies was that players simply reported they could not find babies that they were playing with. Sadly, the reports did not include what was the trigger for these disappearances. Then, one day when testing, we noticed an item held by a user created character disappearing and, pun intended, felt like we held the critical clue in our hands.</p><p>To make it even more obvious, something in the code was making babies and items sometimes disappear from the hands of a user created character holding them. Some parts of the reports became obvious at that moment: of course play with babies involved placing them in the hands of other characters. This made sense as a trigger and also as something that the players didn’t think to mention in their feedback. Holding a baby isn’t a special action in the eyes of a player.</p><p>However, simply placing the baby into a user created character’s hands wasn’t enough to cause the bug. There needed to be some additional component to this. This is where we accidentally stumbled upon the critical clue: When we saw an item disappear in the editor, it happened while the item was being held by a character on the sidewalk.</p><p>We had a place. We had something of a suspect. Now we needed the method.</p><p>At this point, complexity of the problem quickly increased. Since the bug was happening on the sidewalk, we started suspecting that something was amiss in our save file.</p><p><strong>Enter the save files</strong></p><p>In Toca Life World each location<strong> </strong>in the app has its own save file that contains a serialised version of everything in that location. The sidewalk is technically a location like any other with an important difference: Instead of storing what is currently in the ‘sidewalk scene’, it’s actually the home for all characters, all the time. Characters are always saved into the sidewalk and simply keep a reference to the location they were last used in. This allows the player to access any character from any location and to play with them everywhere, and we don’t need to go rummaging through saves for individual locations all the time.</p><p>To complicate this further, a character can carry things when they are saved. They can also carry babies which are characters in their own right. This means that when serialising a character, they are serialised with references to everything they were holding and what is holding them. Our serialisation is complicated in order to allow maximum flexibility to our players and we are omitting details here. For this bug, the important bit is that when serialised, being held is a two way street: baby knows about the specific parent and parent knows about the specific baby.</p><p>At this point of the investigation, we knew the problem was related to being held. However, there was no crash or repro so we couldn’t trigger the bug and see how the data looked. We had to resort to manually combing through the code to isolate suspects.</p><p>We learned the following:</p><ol><li>There are two parts to the a character being on the sidewalk: saving and loading. One set of steps applies to the process of storing the character. Loading a character to the sidewalk follows another complex ‘permission to spawn’ process.</li><li>We were dealing with legacy code with assumptions made long ago. There was no expert left at the company who could deal with this code in a fast manner.</li><li>User created characters had some special code, but nothing that would’ve immediately revealed a bug. Additionally, majority of the special code wasn’t in the save/load flow.</li></ol><p>Because of the complexity of the save/load flow and the legacy nature of it, we focused our efforts on the special rules related to user created characters first. This proved out to be a lucky guess as it led us into another part of the code that we hadn’t thought of as interesting at first: creating user created characters.</p><figure><img alt="A picture of Character Creator tool with a new character to the left and options for age on the right. Options for hair, eyes, clothes and so on are visible in a toolbar below." src="https://cdn-images-1.medium.com/max/1024/1*Zaj4GErtxTD7cl2zOrRgLw.png" /><figcaption>Character creator with options for changing the age.</figcaption></figure><p>The usual user path when we save or load something is ultimately simple: In both cases, we can assume that the character already exists somewhere in the save and what we are doing is simply either updating it (save) or copying its data somewhere else (load). This is because Toca Life World is built with everything having a default save: every object, item and character, has a location it starts in. For characters, this means that they have a location they appear in by default but also that they are saved by default in the sidewalk. This is, counterintuitively, also true for user created characters.</p><figure><img alt="A big group of character is default blueprint state without faces, clothes or other default stand behind a glass door." src="https://cdn-images-1.medium.com/max/1024/1*e0aKjUaAmVFo0MgZM6zSdw.png" /><figcaption>User created characters have a default location behind the door of Floople Central</figcaption></figure><p>When a player creates a new character, what they are actually doing is simply modifying one of the predefined user created characters. Although not visible for the players by default, every potential user created character is stored into the sidewalk from the start in a default state. When creating a character, we simply copy over the new data onto one of this bodies and allow it to become visible and appear in the sidewalk.</p><p>However, there is a catch. Two of them in fact. Although this catch wasn’t quite yet the bug we were hunting, we were now hot on the trail.</p><p>The first problem is obvious: When a player deletes a user created character, the deleted character is ‘removed’ from the world and returned to a default state. This means that we need to do something to ensure the game is in a good state after this.</p><p>The second problem has the same consequences but isn’t quite as obvious at first glance: Since a baby can be held by anyone from another category than a baby and this character holding them can be user created — what happens when a player enters the character creator and changes the age of that character? We would end up with a baby holding a baby which the system doesn’t support. In practise, this means that we need to assume the any change in a user created character can be a breaking change. This causes the system to actually treat a modified character as a new character.</p><p>The solution, already implemented, is our ‘trashing’. When we notice a change in the game that needs us to modify the save state, we do a trashing pass to ensure the save state is still valid after. We do this in multiple places but most importantly whenever we either change or delete a user created character.</p><p>This cleaning process is a complex beast. As already mentioned, the save files hold references to full hierarchies. Parent know about children, children know about parents, and every internal element in between. When we remove a user created character, we end up needing to read through the entire sidewalk save file to find anything that is referencing this specific character and sever the connection. This is, for many reasons, not optimal. It is resource intensive, takes time and memory, it is complex and hard to follow because it needs to reflect the maximum complexity possible in the game, and as we now found out with the missing babies, not creating clean saves after all the effort.</p><p>Looking at the trashing was our lightbulb moment. With the new knowledge, we finally managed to create a theory that led to repro steps. In the end, it was as simple as creating a user created character, handing them a baby, and then going into the character creator and changing something in the character. A trashing pass was triggered, and upon returning to the location the baby would be gone and only the user created character would remain.</p><p>With a repro, we could actually slowly process through the trashing code and follow the flow of data. This was mostly a boring process — the depth of the hierarchies meant both recursion in the code as well as an amount of data that couldn’t simply be stepped through. With some well placed breakpoints with conditional stops, we could finally catch the baby in the act of disappearing. We saw its parent enter trashing, lose the connection to the baby, and then enter the game as a fresh new character without issues.</p><p>However, the baby was lost.</p><p><strong>The solution:</strong></p><p>Armed with all the knowledge we had about the baby and its state, we could finally return to the sidewalk loading code. If we’d tried to catch this bug in action in the loading system from the start, we wouldn’t have succeeded. Without travelling through the trashing first, we simply wouldn’t have been able to recognise when the bug was happening. This was because the data was in a truly deceiving state.</p><p>The following was true of the data after it had been corrupted in the trashing process:</p><ol><li>The baby appeared unchanged; it had a current location, the data was not in any way changed, it still had a reference to its parent, and yet it couldn’t load.</li><li>The user created character holding the baby appeared completely unchanged even though we now knew that it had been technically ‘trashed’ and replaced by a new user created character. However, here’s the crucial detail: The <em>new</em> user created character was simply the old character but with all references to the rest of the game reset. When looking at the data, it had the same character id as before and only the reference in its hierarchy to the baby had disappeared. This is because creating a new characters in Toca Life World isn’t actually possible since all characters are created from the start, including the user created. Trashing is a cleanup, not a deletion.</li></ol><p>Since the user created character was loading just fine, we now looked closely at what was happening with the loading of the baby. A character is marked as something that should load if they match the filter of the current sidewalk. This is done by going through everything in the sidewalk that belongs the current category (say, user created characters) and all their children. Critically, this process is done from the base object, or a <em>parent</em> if the object has one. This is because we need all the objects in a hierarchy to load — otherwise we’d have something floating in the air!</p><p>The bug was that the user created character had been cleaned in the process of becoming a ‘new character’ so it didn’t have any children. However, the baby still had a reference to the user created character because the baby hadn’t gone through a cleaning process as it wasn’t the character being removed. When the baby was trying to load, it passed the responsibility to its parent. The parent however didn’t know about the child so it spawned either without it (user created category) or not at all (baby category). The babies disappeared because they couldn’t appear alone on the sidewalk because they had a parent; they weren’t loaded through the parents because the parents had no memory of them. A full reset of the game was needed in order to clean the baby and make it lose the connection to the parent.</p><p>After all the effort, the fix itself was simple. When trashing a parent it loses the reference to a child — we now also make sure to have the child lose the reference to the parent, remembering that our saves are two way constructions. Now the baby can appear onto the sidewalk alone again and be reattached to the user created character by the player.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/878ea79a8657d9dca1fe4cd45e508810/href">https://medium.com/media/878ea79a8657d9dca1fe4cd45e508810/href</a></iframe><p>Oh, and how was the sidewalk being the location related to all of this? It is simply the location where freshly ‘created’ characters end up in and could have been a clue that this was about user created character trashing from the start.</p><p><strong>The takeaway:</strong></p><p>This bug had it all: no repro, legacy code, complex systems and the actual bug and the consequences appearing in completely separate parts of the code. If it hadn’t been for us accidentally unearthing the connection between user created characters, sidewalk and the disappearances, this bug would have sat in the unfinished pile for many more months.</p><p>This bug really highlights our reliance on repros in an open world. Deducing why multiple systems interact in a way that causes undesirable behaviour is very difficult because how far the influence of one system reaches. It is impossible to realise all the consequences at the time of designing a feature: user created characters do not feel like something that can affect loading of an unrelated character. The only tool we really have is repro steps that allow us to narrow our focus to one or two systems and the places where they interact.</p><p>Since fixing this bug, we have started to address some of the major problems here. Realising that we didn’t have anyone comfortable with our loading flow was a harsh awakening. Loading is extremely central to a game that is all about players manipulating locations (saves). We have now refactored those code paths to improve the readability as well as created a flowchart of the flow, including the conditions that need to be fulfilled for something to be loaded. Work remains: for the uninitiated, the full serialisation flow is still daunting.</p><p>We have also introduced tests that help us document the loading logic. Seeing the amount of tests needed is already a good indication of the complexity hidden in there. Besides these unit tests, we have created play mode tests that cover the ‘danger zones’ uncovered in this test. We should now catch user created characters misbehaving a lot earlier. Toca Life World has a classic legacy code base with many areas still lacking test coverage — every bug we catch gives us an opportunity to improve on that.</p><figure><img alt="A dauntingly long list of tests that cover loading with different types of variables." src="https://cdn-images-1.medium.com/max/1024/1*cJqrgPj7cCSfmHeyxCXv0g.png" /><figcaption>A selection of tests that cover loading logic.</figcaption></figure><p>Trashing has also gotten some more love, even though it could use more. The reality of an open game world where the entire state is controlled by players is that trashing becomes equal to the complexity of the world and the most complex thing in the game (potentially after migration, but that is a whole another topic). We still haven’t mapped the entirety of the trashing flow in our documentation!</p><p>What I’ve written now is based on the knowledge I have now. In fact, if I had the knowledge here when I started looking into babies disappearing, that task would’ve probably been easy! However, I did not have any of this knowledge. I knew we had locations and location save files and that something determined when things appeared. The actual investigation was mostly a scramble to keep the knowledge in my head before I lost some key detail.</p><p>To summarise this case, it is all about information. The code needs to be readable, tests are great not only in catching these things but in documenting what should work and what is needed for it to do that. Avoiding legacy areas of code out of fear is what allows these kind of bugs fester — getting rid of cobwebs in code bases is good for multiple reasons.</p><p><strong>Case closed.</strong></p><figure><img alt="Baby in a detective hat with a magnifying glass" src="https://cdn-images-1.medium.com/max/942/1*kSasv9OHNxOyHZRGUkDSUw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3ba28f7e9d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toca-boca-tech-blog/the-case-of-the-missing-babies-d3ba28f7e9d4">The Case of the Missing Babies</a> was originally published in <a href="https://medium.com/toca-boca-tech-blog">Toca Boca Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons from a difficult refactoring journey]]></title>
            <link>https://medium.com/toca-boca-tech-blog/lessons-from-a-difficult-refactoring-journey-e4b877c52a48?source=rss-58df0f97a8f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4b877c52a48</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[lessons-learned]]></category>
            <dc:creator><![CDATA[Tove Brantberg]]></dc:creator>
            <pubDate>Thu, 04 May 2023 13:00:26 GMT</pubDate>
            <atom:updated>2023-05-04T13:00:26.486Z</atom:updated>
            <content:encoded><![CDATA[<p>Many books have been written about refactoring. Smart people have already defined a myriad of ways to approach code that needs updating. However, in practise, the refactoring process easily lacks the foresight needed for a painless journey. This is a post mortem of one such complicated refactoring.</p><figure><img alt="An apartment in Toca LIfe World with two characters sitting on a couch. In the foreground, a group of characters stand in a row on a sidewalk." src="https://cdn-images-1.medium.com/max/1024/1*GUzYB8QuS5vo82tDYXk3MA.png" /><figcaption>A location with the sidewalk open.</figcaption></figure><p>Little bit of background to start with: Toca Life World is a game that gives the players a virtual environment with locations, items and characters. Characters can travel between these locations through a sidewalk which acts as a type of container they can physically stand in. Items can be held by characters and travel with them but never placed directly onto the sidewalk.</p><p>Toca Life World aspires to be an inclusive and welcoming environment, taking into account the diversity of humankind — including our disabilities. Wheelchairs have always been part of many locations but one hasn’t been able to place the wheelchairs directly on the sidewalk as they are classified as items. As a consequence, a character sitting in a wheelchair had to be removed from it before they could be placed into the sidewalk. The only way to transport a wheelchair was to give it to a character to carry — making it impossible to play with wheelchairs in a way that reflected how wheelchairs are used in reality. We wanted to change that.</p><p>In the beginning, we had a simple feature request. Could we make wheelchairs sidewalk compatible? This turned into four months of development, major refactoring and many mistakes. Since this is the internet, here’s a numbered lists of steps we took and our learnings from them:</p><p><strong>1. Map the problem area</strong></p><p>Before we even started on the task, we knew that we didn’t know the code. In fact, we knew that everything related to the sidewalk was ‘legacy’ and there wasn’t anyone at the company who felt comfortable with it. Worse yet, putting wheelchairs on the sidewalk had a reputation as something that had been attempted at some point but that this effort had been abandoned for some reason. No explanation on when, by who or how or even why it had been abandoned existed. In other words, we knew we were walking in blind into something of a jungle.</p><p>Therefore, the first step of the feature journey was to explore the code. For this purpose, we implemented a quick and dirty demo. At this point, we were mostly looking to prove that we could even implement the feature. The demo was intended to be throwaway code where we simply followed the code paths and tweaked them to allow a wheelchair to pass.</p><p>We started from the player interaction and simply started solving problems step by step, not too worried about side-effects. We found out what needed to change to allow the wheelchair to stand on the sidewalk, then what was needed to move it to a save file so it was available at a different locations, continuing until we’d mapped the whole way from one location to the other. The systems originally only allowed characters to be treated this way but we found a relatively contained way to isolate the ‘sidewalk object’ part into a component that we could share between objects we wanted. This allowed us to ‘mask’ wheelchairs as something that could be handed to our sidewalk system and then be spitted out at the other end of it, allowing transportation from one location to the other.</p><p>This process ended up giving us something to demo in less than a week. It only worked on the happy path and had bugs everywhere else but we felt done with it. We’d gotten results way faster than we expected, and with less pain than we’d even thought possible!</p><p><strong>Lesson</strong>:<br>The demo was a great tool. It proved that the feature could be done. We could also now see that majority of the problems were related to the save process (all saving assumed it was dealing with a character and was concerned with things like hands and age — things items didn’t have), and even which files we were mostly going to work in. We felt confident enough to make estimations about the the time needed to complete the feature at this point. We also assumed we had a handle on the scope of the refactoring needed (not major) and that we could do it while implementing the new code. At this point, it felt like all the scaremongering had been based on old information and nothing but vague feelings.</p><p>In hindsight, this demo proved exactly what it set out to prove. It also completely missed what ended up causing the biggest issues during development: exploring the ‘cross-over’ areas between wheelchairs and other features in the game. This blindness was because we didn’t even know there would be interactions between systems. The demo was done with a single character sitting in a wheelchair. We did not test with a user created character (saved differently!), or a wheelchair from our home designer (potential for infinite instantiated wheelchairs!). We also missed to map how complex a hierarchy might get with the wheelchairs — before, the maximum stack was a character holding a character holding an item. Adding one item at the beginning of the stack might not sound like a big change, but it went against all assumptions the system had. This would have unforeseen consequences.</p><p>The point of a demo isn’t to provide solutions for everything. However, the critical mistake we did with the demo was to assume it covered more ground than it did — we failed to grasp how little we knew. In hindsight, we started the demo without exploring the concept of wheelchairs. Spending some time thinking about how wheelchairs interacted with the ecosystem of the game would hopefully have uncovered these ‘cross-over’ moments before we were already knee-deep in the development.</p><p><strong>2. Do throw away your throwaway code</strong></p><p>This is a classic mistake. We did not throw away the demo code. Sometimes its pressure to hit deadlines. In our case, it was hubris since we thought the code was good enough to continue with. The code wasn’t <em>bad</em>, most of it actually survived to the final product. The code wasn’t the real problem here — our haste was. Since we decided to ‘keep at it’ based on the demo, we didn’t pause here to reevaluate what we’d learned and what we were going to do next beyond ‘fix the remaining issues’. We hadn’t even noticed the lesson outlined above — we were entirely ignorant about the edge cases that lay in wait.</p><p><strong>Lesson</strong>:<br>Reimplementing the good parts would not have taken long. Not stopping to really plan our next steps caused way bigger problems down the line. The real question we missed was if we should do a refactoring pass <em>before </em>we added in new functionality. The ‘cross-over’ edge cases would ultimately force us to refactor much more than we’d originally intended. If we’d decided to do the refactoring first and then added the new parts needed for wheelchairs, we would have had a much easier time with the wider reach of the refactoring. It was impossible to do a pure refactoring pass with the demo code in since that added wheelchair specific tweaks. However, we didn’t even think about that when making the decision to continue directly on top of the demo.</p><p><strong>3. Keep focused — and react when focus changes</strong></p><p>During the demo, the goal was focused. We simply needed to make wheelchairs work in the minimal use-case. After the demo stage was over, we widened the scope without really meaning to. Instead of making the wheelchairs work on the sidewalk, we wanted the implementation to be general enough that <em>any item </em>could be added to the sidewalk.</p><p>The focus shifted because we wanted to future proof our solution: there were already plans to experiment with allowing players to start placing more items directly on the sidewalk. Additionally, it would be cleaner to bring items and characters closer together in general. The base load code would be easier to handle with less assumptions — there was no reason for it to be character only. Making it work with only characters and ‘wheelchairs’ would have introduced weird exceptions in the code which would definitely have been a step to the wrong direction!</p><p>The change into a more generalised implementation was not a bad decision per se — it was simply the moment when the ‘refactoring’ started to leak. We were still operating under the assumption that we were simply implementing a feature and doing some normal cleanup in the areas around the code we were touching. However, we’d already changed our focus from a very targeted change to a more general refactoring with wider repercussions.</p><p><strong>Lesson:</strong></p><p>To make generalised code is good! We were future proofing our implementation and improving the code base in one go. However, our mistake was to ignore how much refactoring needed to be done to reach this point. We should have taken a step back and done the generalisation of the code first in a different branch and then come back to implement wheelchairs on top of it. We were now doing both at the same time.</p><p>It wasn’t immediately obvious that we were committing to something that would cost to us down the line. The first two weeks, we were actually making some great gains at a nice velocity. Every day, we had a more stable wheelchair to sidewalk implementation. The code base was also looking more sleek.</p><p>The problems became visible when we started wrapping up the development. We tested the code we’d written with wheelchairs and other items and kept finding all sorts of bugs that we kept filing into Jira to deal with later. There was a sense that not all of the bugs were caused by us — but since we’d touched the loading system, they might be. We were collecting anything that was broken with the sidewalk or loading and quickly had a task list more suitable as a general backlog of improvements than task list for a feature.</p><p>Scoping back down to only wheelchairs was difficult. This became very apparent when we presented the code to other programmers. They immediately raised red flags. They didn’t feel confident with large changes to legacy code. The feature wasn’t simply adding wheelchairs to sidewalk but a major change to how our save to sidewalk flow worked. Reviewing it was hard: there was no red thread to the changes since we were both adding to and promising to keep old behaviour.</p><p>The lesson here was that having a clearly defined goal doesn’t bring focus to just the team working on the feature but also those reviewing it. Because we lacked clear identity, even our reviewers didn’t know what to focus on. This lack of focus was also the first warning sign of the scope that was about to escape us. However, it needed the next mistake to escalate.</p><p><strong>4. Take a step back as not to focus on the wrong things</strong></p><p>Being too close to your code can lead to mistakes. In our case, it meant that we had a hard time seeing it objectively. The feature was not approved because people did not feel confident with it. In hindsight, the main problem was the sprawling scope of it but in the moment, we felt that people were not trusting ‘our’ code. The feedback we got was that the refactoring was risky — what we heard was that they feared we’d introduced regressions. It was a valid concern — we were operating in an area without test coverage and it was very easy for regressions to hide in the complex system — but we wanted the feature out.</p><p>To make others feel more confident with our branch, we simply decided to prove the stability of it. From that point onwards, our goal was to have a ‘crash free branch’ with amazing test coverage. Both technically good goals, but this meant leaning into making this into an even bigger change. We had many knows bugs in this area of the code even before we started working on adding the wheelchairs, and now these known bugs became things that we wanted to fix ‘on the side’ to prove the stability of our change.</p><p><strong>Lesson</strong>:<br>Here, the lack of objectivity led to us doubling down on the wrong things. Instead of descoping and refocusing, we made the scope of the changes even larger by pulling all possible bugs into our task list. The problem was always the scope, not the quality — but we failed to see that in the moment.</p><p>At this point it was very obvious that we were refactoring large chunks of legacy code (as the review pointed out). We should really have taken a step back earlier and reimplemented the refactoring on a clean branch to descope and then returned to the feature instead of coupling the two. Even though we were now aware of it, we were stubbornly continuing with he massive branch. Admitting that the refactoring and wheelchairs should be split made us afraid that we’d get entirely rejected — it would have been proof that we weren’t entirely confident in our code.</p><p><strong>5. Respect your Definition of Done (Or resist the urge to fix everything)</strong></p><p>Despite our unwieldy scope, we reached a point when all the major bugs had been handled. At this point we’d missed our original estimation by two months. During this time we attempted to ‘finish’ the development multiple times only to stumble upon a new bug that revealed something new that was broken. At this point, wheelchairs were rarely even the thing we had issues with. We dug too deep and too greedily and had finally uncovered all the other ‘cross-over’ systems that had rather big bugs in them. Since we ‘needed’ to have a bug free branch, we fixed those as well even though their connection to wheelchairs was tentative at best.</p><p><strong>Lesson</strong>:<br>Actually listen to your definition of done. We were supposed to implementing wheelchairs, and not introducing new bugs with them. We’d tacked on a need to fix even more bugs to prove that our branch was extra stable. In the process of doing that, we’d become the experts of our save system, sidewalk, our trashing, our home designer feature, our character creator… and were now fixing issues that belonged to those systems. We wanted to ensure our branch would ‘pass any test’ and didn’t want to leave anything in that could raise questions about the quality. We were also constantly guilty of fixing something small ‘since we know how to do it’ and improving the code even further and sneaking in refactoring here and there. It took us weeks before we managed to convince ourself to stop with all the small fixes and actually be ‘done’. Here, the lesson really is: Not all problems should be fixed at once.</p><p>Dividing the feature development into milestones would have made everyone involved much happier. Less missed deadlines, less last minute bugs that derailed the sprints. At this point we already dreamed of having done a demo, paused, refactored, remapped and redesigned the sprint plan to handle one cross-over element at a time instead of rushing to patch leaks in all the systems at the same time.</p><p><strong>5. Definition of Done for code review (or resist the urge to fix everything. Again.)</strong></p><p>The final hurdle for our feature was to pass code review. This review was not set for success. The branch was sprawling. It’s only saving grace was that the code hadn’t strayed too far from the main branch thanks to frequent updates from it — but there were small changes everywhere in the code base. In order to review it, one needed to be an expert in multiple systems in the game — and our team were pretty much the only experts available in the most obscure of them. It took multiple days to simply read through the full pull request.</p><p>Here, the same issue that had plagued the development was at full display. The review was equally focused on refactoring and on the feature development. Since what was ‘new’ for the feature and what was imply the ‘new refactored’ was hard to keep track off. Additionally, simply seeing refactoring caused many reviewers to request additional improvements, and turning them down was difficult. We definitely did more refactoring at the review stage than exactly wise.</p><p>For a feature that had now been in development for 3 months, we ended up having two full weeks of nothing but code review adjustments. These numbers are absurd but also indicative of the scope that escaped at both the development and the review.</p><p><strong>Lesson</strong>:</p><p>Keep pull requests small. Had we divided our work into milestones, we could have reviewed each of them separately. The review process would have been more focused by having a focused branch. We didn’t have that luxury now.</p><p>We should also have been more strict with defining clearly how the review process was to be conducted. What were we focusing on? How perfect did we need something to be? Definition of done should not only have been applied on the feature itself but to our review standards. This is something that is not only related to this particular feature but in general to work we are doing at Toca. Our review practises are still evolving! Here, we got amazingly dedicated reviewers — but it also meant that our scope bloated even more…</p><p>The best takeaway here is that sometimes it is best to dare to say no to refactoring requests at the review stage. It is better for everyone to get those in with a separate pull request. Thanks to our test coverage, we did manage to do the last minute refactoring without breaking anything but it was a nerve-wrecking process nevertheless.</p><p>However, the review at the end was definitely worth it. The quality of the code greatly improved. Since we’d been two programmers working on it without much outside input for months, we had some blind spots when it came to readability. Don’t also be afraid to rename variables even if that means losing the legacy naming. We’d kept some old names (since we’d gotten used to their odd idiosyncrasies) but reviewers rightly pointed out that they made no sense anymore. Renaming them to match their modern purpose improved the code base a great deal.</p><p><strong>Final takeaways</strong></p><p>The vague warnings in the beginning that there was ‘something’ in the way were accurate in two ways: We didn’t know this code and needed time to learn it. It was also legacy code and therefore filled with assumptions that excluded wheelchairs. Learning and cleaning both take time — this wouldn’t have been a quick feature even with better process, and we should really have realised that right at the start. ‘Legacy’ really means a combination or ‘we don’t know it anymore’ and ‘it hasn’t seen maintenance in a while’. Extra respect should be given to planning when legacy code is involved even if it might look not that bad at the start.</p><p>Improving code while developing new features is the standard. However, in this case we missed the moment when the refactoring was getting so extensive that it was no longer sustainable to both refactor and work on a new feature. We did notice that we were extending our scope but we were talking about all detours as ‘fixing something for our feature’. We could spend a week not even touching wheelchairs without alarm bells starting to ring.</p><p>The moment we should have paused the feature development was the first time we found an ‘overlap’ with another system. That should have triggered a new investigation in order to map the changed problem area. From the moment we started looking into adjacent systems, we were moving practically blind. We didn’t have a path mapped with a demo and we didn’t have any knowledge about the systems either. This made us very ill equipped for the hard balancing act of deciding what belonged to our feature and what was just existing bugs that we could fix now.</p><p>Obviously, having a bug free codebase is a point of pride for a programmer. However, we were too eager to fix everything and in doing so lost sight of the goal. Having a little more patience would have saved us a lot of pain here. If we could have separated new bugs from legacy bugs — and just ensured we weren’t making it worse in the first iteration, we would’ve been much better positioned for doing a second iteration where we’d tackle those older issues. If we’d taken the time to map the problem areas in these other systems, we would have known what was legacy issues and what we’d introduced. In a perfect world, we would have had a clear Jira backlog of all the bugs we encountered, and could even have offloaded some of the issues to other programmers — who were experts in those other systems!</p><p>Now, it is easy to say that loss aversion played clearly a big part in our mistakes. The team had entered this feature directly after having a big feature cancelled. This made us extra attached to the feature, and extra cautious about taking any distance from it. If we’d put the feature aside to do pure refactoring, we were not sure if we’d allowed to go back to finishing the feature. Next time, we’ll definitely try to be more in touch with our emotions and will know to communicate our fears better. At no point was the rest of the team working against us, but like we feared that we’d have another feature cancelled, they feared we didn’t have a handle on the scope and wouldn’t be able to guarantee the quality.</p><p>The feature did complete — but it was a small miracle it did. We had the luxury of dedicating two people to a feature that itself was small but then grew to contain a major refactoring and refreshing of the code base. Despite the painful process, the code itself is good and will help us plenty going forward. But without the patience of the whole team, it wouldn’t have been possible.</p><p><strong>Bonus Lesson: Celebrate your victories (and learn your lessons)</strong></p><p>The full team at Toca has been supportive through out the ups and downs of the ‘Wheelchair branch’ and that made a huge difference in getting it done. The PR process was also rough for everyone involved but we had some true heroes who took on the challenge. There was much good in the process despite some painful mistakes. Additionally, this feature has been a reminder that difficult process does not need to equal bad end product. We are proud of the code that did end up getting merged — and those wheelchairs might be the most stable thing on the sidewalk now.</p><figure><img alt="A character sitting in a wheelchair, holding a wheelchair in one hand and a baby in the other. The baby is holding a wheelchair in their hand as well." src="https://cdn-images-1.medium.com/max/588/1*fP-ntevCMgFQTQGInrZhrQ.png" /><figcaption>The visible result of four months of work.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b877c52a48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toca-boca-tech-blog/lessons-from-a-difficult-refactoring-journey-e4b877c52a48">Lessons from a difficult refactoring journey</a> was originally published in <a href="https://medium.com/toca-boca-tech-blog">Toca Boca Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>