Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
60
353k
source
stringclasses
2 values
# Requirements We do not write code for the sake of writing code: we develop software to _help people perform tasks_. These people can be "anyone on Earth" for widely-used software such as GitHub, "people who do a specific job" for internal applications, or even a single person whose life can be helped with software. In order to know _what_ software to develop, we must know what user needs: their _requirements_. ## Objectives After this lecture, you should be able to: - Define what user requirements are - Formalize requirements into _personas_ and _user stories_ - Develop software based on formalized requirements - Understand _implicit_ vs _explicit_ requirements ## What are requirements? A requirement is something users need. For instance, a user might want to move from one place to another. They could then use a car. But perhaps the user has other requirements such as not wanting or being able to drive, in which case a train could satisfy their requirements. Users may also have more specific requirements, such as specifically wanting a low-carbon means of transportation, and having to travel between places that are far from public transport, in which case an electric car powered with low-carbon electricity could be a solution. Requirements are _not_ about implementation details. A specific kind of electric motor no a specific kind of steel for the car doors are not user requirements. However, users may have needs that lead to such choices being made by the system designers. Sometimes you may encounter a division between "functional" and "non-functional" requirements, with the latter also being known as "quality attributes". "Functional" requirements are those that directly relate to features, whereas "non-functional" ones include accessibility, security, performance, and so on. The distinction is not always clear, but it is sometimes made anyway. Defining requirements typically starts by discussing with users. This is easier if the software has a small and well-defined set of users, such as software specifically made for one person to do their job in a company. It is harder if the software has a large and ill-defined set of users, such as a search engine or an app to listen to music. It is important, when listening to what users say, to keep track of what they _need_ rather than what they _want_. What users claim they want is heavily influenced by what they already know and use. For instance, someone used to traveling by horse who needs to go across a mountain might ask for a "flying horse", when in fact their need is crossing the mountain, and thus a train with a tunnel or a plane would satisfy their requirements. Similarly, before the modern smart phone, users would have asked for old-style phones purely because they did not even know a smart phone was feasible, even if now they actually like their smart phone more than they liked their old phone. What users want can be ambiguous, especially when there are many users. If you select cells with "100" and "200" in a spreadsheet program such as Microsoft Excel and expand the selection, what should happen? Should Excel fill the new cells with "300", "400", and so on? Should it repeat "100" and "200" ? What if you expand a selection containing the lone cell "Room 120" ? Should it be repeated or should it become "Room 121", "Room 122", and so on? There is no perfect answer to these questions, as any answer will leave some users unsatisfied, but a developer must make a choice. Not listening to users' requirements can be costly, as Microsoft found out with Windows 8. Windows 8's user interface was a major reinvention of the Windows interface, using a "start screen" rather than a menu, with full-screen apps that could be tiled rather than moved. It was a radical departure from the Windows that users knew, and it was a commercial failure. Microsoft had to bring back the start menu, and abandoned the concept of tiled full-screen apps. However, Apple later did something similar for a new version of their iPad operating system, and it worked quite well there, perhaps because users have different expectations on desktops and tablets. ## How can we formalize requirements? Once you've discussed with plenty of users and gotten many ideas on what requirements users have, how do you consolidate this feedback into actionable items? This is what formalizing requirements is about, and we will discuss formalizing _who_ with "personas" and _what_ with "user stories". Who is the software for? Sometimes the answer to that question is obvious because it is intended for a small and specific set of users, but most large pieces of software are intended for many people. In fact, large pieces of software typically have way too many users for any kind of personalized process to scale. Instead, you can use _personas_ to represent groups of users. A persona is an _abstract_ person that represents a group of similar users. For instance, in a music app, one persona might be Alice, a student, who uses the app in her commute on public transport. Alice is not a real person, and she does not need specific features such as a hair color or a nationality. Instead, Alice is an abstract representation of many people who could use the app and all have similar features from the app's point of view, namely that they use the app on public transport while commuting to their school, university, or other similar place. Alice's requirements might lead to features such as downloading podcasts in advance at home, and listening with the screen turned off. Another persona for the same app might be Bob, a pensioner, who uses the app while cooking and cleaning. Bob is not a real person either, but instead represents a group of potential users who aren't so familiar with the latest technology and want to use the app while performing tasks at home. While one can create personas for many potential groups of users, not all of them will make the cut. Still for the music app example, another persona could be Carol, a "hacker" who wants to listen to pirated music. Carol would need features such as loading existing music tracks into the app and bypassing copyright protection. Is the app intended for people like Carol? That's up to the developers to decide. One last word about personas: avoid over-abstracting. Personas are useful because they represent real people in ways that are helpful to development. If your personas end up sounding like "John, a user who uses the app" or "Jane, a person who has a phone", they will not be useful. Similarly, if you already know who exactly is in a group of users, there is no need to abstract it. "Sam, a sysadmin" is not a useful persona if your app has exactly one sysadmin: use the real person instead. --- #### Exercise What personas could a video chat app have? <details> <summary>Example solutions (click to expand)</summary> <p> Anne, a manager who frequently talks to her team while working remotely. Basil, a pensioner who wants to video chat his grandkids to stay in touch. Carlos, a doctor who needs to talk to patients as part of a telemedicine setup. </p> </details> --- What can users do? After defining who the software is for, one must decide what features to build. _User stories_ are a useful tool to formalize features based on requirements, including who wants the feature, what the feature is, and what the context is. Context is key because the same feature could be implemented in wildly different ways based on context. For instance, "sending emails with information" is a feature a software system might have. If the context is that users want to archive information, the emails should include very detailed information, but their arrival time matters little. If the context is that users want a notification as soon as something happens, the emails should be sent immediately, and great care should be taken to avoid ending up in a spam filter. If the context is that users want to share data with their friends who don't use the software, the emails should have a crisp design that contains only the relevant information so they can be easily forwarded. There are many formats for user stories; in this course, we will use the three-part one "_as a ... I want to ... so that ..._". This format includes the user who wants the feature, which could be a persona or a specific role, the feature itself, and some context explaining why that user wants that feature. For instance, "As a student, I want to watch course recordings, so that I can catch up after an illness". This user story lets developers build a feature that is actually useful to the person: it would not be useful to this student, for instance, to build a course recording feature that is an archive accessible once the course has ended, since presumably the student will not be ill for the entire course duration. Going back to our music app example, consider the following user story: "As Alice, I want to download podcasts in advance, so that I can save mobile data". This implies the app should download the entire podcast in advance, but Alice still does have mobile data, she just doesn't want to use too much of it. A similar story with a different context could be "As a commuter by car, I want to download podcasts in advance, so that I can use the app without mobile data". This is a different user story leading to a different feature: now the app cannot use mobile data at all, because the commuter simply does not have data at some points of their commute. To evaluate user stories, remember the "INVEST" acronym: - *I*ndependent: the story should be self-contained - *N*egotiable: the story is not a strict contract but can evolve - *V*aluable: the story should bring clear value to someone - *E*stimable: the developers should be able to estimate how long the story will take to implement - *S*mall: the story should be of reasonable size, not a huge "catch-all" story - *T*estable: the developers should be able to tell what acceptance criteria the story has based on its text, so they can test their implementation Stories that are too hard to understand and especially too vague will fail the "INVEST" test. #### Exercise What user stories could a video chat app have? <details> <summary>Example solutions (click to expand)</summary> <p> As Anne, I want to see my calendar within the app, so that I can schedule meetings without conflicting with my other engagements. As Basil, I want to launch a meeting from a message my grandkids send me, so that I do not need to spend time configuring the app. As a privacy enthusiast, I want my video chats to be encrypted end-to-end, so that my data cannot be leaked if the app servers get hacked. </p> </details> #### Exercise Which of the following are good user stories and why? 1. As a user, I want to log in quickly, so that I don't lose time 2. As a Google account owner, I want to log in with my Gmail address 3. As a movie buff, I want to view recommended movies at the top on a dark gray background with horizontal scroll 4. As an occasional reader, I want to see where I stopped last time, so that I can continue reading 5. As a developer, I want to improve the log in screen, so that users can log in with Google accounts <details> <summary>Solutions (click to expand)</summary> <p> 1 is too vague, 2 is acceptable since the reason is implicit and obvious, 3 is way too specific, 4 is great, and 5 is terrible as it relates to developers not users. </p> </details> ## How can we develop from requirements? You've listened to users, you abstracted them into personas and their requirements into user stories, and you developed an application based on that. You're convinced your personas would love your app, and your implementation answers the needs defined by the user stories. After spending a fair bit of time and money, you now have an app that you can demo to real users... and they don't like it. It's not at all what they envisioned. What went wrong? What you've just done, asking users for their opinion on the app, is _validation_: checking if what you specified is what users want. This is different from _verification_, which is checking if your app correctly does what you specified. One key to successful software is to do validation early and often, rather than leaving it until the end. If what you're building isn't what users want, you should know as soon as possible, instead of wasting resources building something nobody will use. To do this validation, you will need to build software in a way that can be described by users, using a _common language_ with them and _integrating_ them into the process so they can give an opinion. We will see two ways to do this. First, you need a _common language_ with your users, as summarized by Eric Evans in his 2003 book "Domain-Driven Design". Consider making some candy: you could ask people in advance whether they want some candy containing NaCl, $C_{24}$ $H_{36}$ $O_{18}$, $C_{36}$ $H_{50}$ $O_{25}$, $C_{125}$ $H_{188}$ $O_{80}$, and so on. This is a precise definition that you could give to chemists, who would then implement it. However, it's unlikely an average person will understand until your chemists actually build it. Instead, you could ask people if they want candy with "salted caramel". This is less precise, as one can imagine different kinds of salted caramel, but much more understandable by the end users. You don't need to create salted caramel biscuits for people to tell you whether they like the idea or not, and a discussion about your proposed candy will be much more fruitful using the term "salted caramel" than using any chemical formula. In his book, Evans suggests a few specific terms that can be taught to users, such as "entity" for objects that have an identity tied to a specific property, "value object" for objects that are data aggregates without a separate identity, and so on. The point is not which exact terms you use, but the idea that you should design software in a way that can be easily described to users. Consider what a user might call a "login service", which identifies users by what they know as "email addresses". A programmer used to the technical side of things might call this a `PrincipalFactory`, since "principals" is one way to call a user identity, and a "factory" is an object that creates objects. The identifiers could be technically called "IDs". However, asking a user "What should happen when the ID is not found? Should the principal returned by the factory be `null`?" will yield puzzled looks. Most users do not know any of these terms. Instead, if the object in the code is named `LoginService`, and takes in objects of type `Email` to identify users, the programmer can now ask the user "What should happen when the email is not found? Should the login process fail?" and get a useful answer. Part of using the _right_ vocabulary to discuss with people is also using _specific_ vocabulary. Consider the term "person". If you ask people at a university what a "person" is, they will mumble some vague answer about people having a name and a face, because they do not deal with general "people" in their jobs. Instead, they deal with specific kinds of people. For instance, people in the financial service deal with "employees" and "contractors", and could happily teach you exactly what those concepts are, how they differ, what kind of attributes they have, what operations are performed on their data, and so on. Evans calls this a "bounded context": within a specific business domain, specific words have specific meanings, and those must be reflected in the design. Imagine trying to get a financial auditor, a cafeteria employee, and a professor to agree on what a "person" is, and to discuss the entire application using a definition of "person" that includes all possible attributes. It would take forever, and everyone would be quite bored. Instead, you can talk to each person separately, represent these concepts separately in code, and have operations to link them together via a common identity, such as one function `get_employee(email)`, one function `get_student(email)`, and so on. Once you have a common language, you can also write test scenarios in a way users can understand. This is _behavior-driven development_, which can be done by hand or with the help of tools such as [Cucumber](https://cucumber.io/) or [Behave](https://behave.readthedocs.io/). The idea is to write test scenarios as three steps: "_given ... when ... then ..._", which contain an initial state, an action, and a result. For instance, here is a Behave example from their documentation: ``` Scenario Outline: Blenders Given I put <thing> in a blender, when I switch the blender on then it should transform into <other thing> Examples: Amphibians | thing | other thing | | Red Tree Frog | mush | Examples: Consumer Electronics | thing | other thing | | iPhone | toxic waste | | Galaxy Nexus | toxic waste | ``` Using this text, one can write functions for "putting a thing in a blender", "switching on the blender", and "checking what is in the blender", and Behave will run the functions for the provided arguments. Users don't have to look at the functions themselves, only at the text, and they can then state whether this is what they expected. Perhaps only blue tree frogs, not red ones, need to turn into mush. Or perhaps the test scenario is precisely what they need, and developers should go implement the actual feature. The overall workflow is as follows: 1. Discuss with users to get their requirements 2. Translate these requirements into user stories 3. Define test scenarios based on these user stories 4. Get feedback on these scenarios from users 5. Repeat as many times as needed until users are happy, at which point implementation can begin #### Exercise What language would you use to discuss a course registration system at a university (or any other system you use frequently), and what test scenarios could you define? <details> <summary>Example solutions (click to expand)</summary> <p> A course registration system could have students, which are entities identified by a university e-mail who have a list of courses and grades associated with the courses, and lecturers, which are associated with the courses they teach and can edit said courses. Courses themselves might have a name, a code, a description, and a number of credits. Some testing scenarios might be "given that a user is already enrolled in a course, when the user tries to enroll again, then that has no effect", or "given that a lecturer is in charge of a course, when the lecturer sets grades for a student in the course, then that student's grade is updated". </p> </details> ## What implicit requirements do audiences have? Software engineers design systems for all kinds of people, from all parts of the world, with all kinds of needs. Often some people have requirements that are _implicit_, yet are just as required as the requirements they will explicitly tell you about. Concretely, we will see _localization_, _internationalization_, and _accessibility_. Sometimes these are shortened to "l10n", "i18n", and "a11y", each having kept their start and end letter, with the remaining letters being reduced to their number. For instance, there are 10 letters between "l" and "n" in "localization", thus "l10n". _Localization_ is all about translations. Users expect all text in programs to be in their language, even if they don't explicitly think about it. Instead of `print("Hello " + user)`, for instance, your code should use a constant that can be changed per language. It is tempting to have a `HELLO_TEXT` constant with the value `"Hello "` for English, but this does not work for all languages because text might also come after the user name, not only before. The code could thus use a function that takes care of wrapping the user name with the right text: `print(hello_text(user))`. Localization may seem simple, but it also involves double-checking assumptions in your user interface and your logic. For instance, a button that can hold the text "Log in" may not be wide enough when the text is the French "Connexion" instead. A text field that is wide enough for each of the words in "Danube steamship company captain" might overflow with the German "Donaudampfschifffahrtsgesellschaftkapitän". Your functions that provide localized text may need more information than you expect. English nouns have no grammatical gender, so all nouns can use the same text, but French has two, German has three, and Swahili has [eighteen](https://en.wikipedia.org/wiki/Swahili_grammar#Noun_classes)! English nouns have one "singular" and one "plural" form, and so do many languages such as French, but this is not universal; Slovenian, for instance, has one ending for 1, one for 2, one for 3 and 4, and one for 5 and more. Translations can have bugs just like software can. For instance, the game Champions World Class Soccer's German translation infamously has a bug in which "shootout" is not, as it should, translated to "schiessen", but instead to "scheissen", which has an entirely different meaning despite being one letter swap apart. Another case of German issues is [in the game Grandia HD](https://www.nintendolife.com/news/2019/08/random_amazingly_grandia_hds_translation_gaffe_is_only_the_second_funniest_german_localisation_mistake): missing an attack displays the text "fräulein", which is indeed "miss" but in an entirely different context. Localization is not something you can do alone unless you are translating to your native language, since nobody knows all features of all languages. Just like other parts of software, localization needs testing, in this case by native speakers. _Internationalization_ is all about cultural elements other than language. Consider the following illustration: <p align="center"><img alt="Illustration of (from left to right) a dirty t-shirt, a washing machine, a clean t-shirt" src="images/washing.svg" width="50%" /></p> What do you see? Since you're reading English text, you might think this is an illustration of a t-shirt going from dirty to clean through a washing machine. But someone whose native language is read right to left, such as Arabic, might see the complete opposite: a t-shirt going from clean to dirty through the machine. This is rather unfortunate, but it is the way human communication works: people have implicit expectations that are sometimes at odds. Software thus needs to adapt. Another example is putting "Vincent van Gogh" in a list of people sorted by last name. Is Vincent under "G" for "Gogh" or under "V" for "van Gogh"? That depends on who you ask: Dutch people expect the former, Belgians the latter. Software needs to adapt, otherwise at least one of these two groups will be confused. Using the culture-specific format for dates is another example: "10/01" mean very different dates to an American and to someone from the rest of the world. One important part of localization is people's names. Many software systems out there are built with odd assumptions about people's names, such as "they are composed entirely of letters", or "family names have at least 3 letters", or simply "family names are something everyone has". In general, [programmers believe many falsehoods about names](https://shinesolutions.com/2018/01/08/falsehoods-programmers-believe-about-names-with-examples/), which leads to a lot of pain for people who have names that do not comply to those falsehoods, such as people with hyphens or apostrophes in their names, people whose names are one or two letters long, people from cultures that do not have a concept of family names, and so on. Remember that _a person's name is never invalid_. Like localization, internationalization is not something you can do alone. Even if you come from the region you are targeting, that region is likely to contain many people from many cultures. Internationalization needs testing. _Accessibility_ is a property software has when it can be used by everyone, even people who cannot hear, cannot see, do not have hands, and so on. Accessibility features include closed captions, text-to-speech, dictation, one-handed keyboards, and so on. User interface frameworks typically have accessibility features documented along with their other features. These are not only useful to people who have permanent disabilities, but also to people who are temporarily unable to use some part of their body. For instance, closed captions are convenient for people in crowded trains who forgot their headphones. Text-to-speech is convenient for people who are doing something else while using an app on their phone. Features designed for people without hands are convenient for parents holding their baby. Accessibility is not only a good thing to do from a moral standpoint: it is often legally required, especially in software for government agencies. It is also good even from a selfish point of view: a more accessible app has more potential customers. ## Are all requirements ethical? We've talked about requirements from users under the assumption that you should do whatever users need. But is that always the case? Sometimes, requirements conflict with your ethics as an engineer, and such conflicts should not be brushed aside. Just because "a computer is doing it" does not mean the task is acceptable or that it will be performed without any biases. The computer might be unbiased, but it is executing code written by a human being, which replicates that human's assumptions and biases, as well as all kinds of issues in the underlying data. For instance, there have been many variants of "algorithms to predict if someone will be a criminal", using features such as people's faces. If someone were to go through a classroom and tell every student "you're a criminal" or "you're not a criminal", one would reasonably be upset and suspect all kinds of bad reasons for these decisions. The same must go for a computer: there is no magical "unbiased", "objective" algorithm, and as a software engineer you should always be conscious of ethics. ## Summary In this lecture, you learned: - Defining and formalizing user needs with requirements, personas, and user stories - Developing based on requirements through domain-driven design and behavior-driven development - Understanding implicit requirements such as localization, internationalization, accessibility, and ethics You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Performance Producing correct results is not the only goal of software. Results must be produced in reasonable time, otherwise users may not wait for a response and give up. Providing a timely response is made harder by the interactions between software components and between software and hardware, as well as the inherent conflicts between different definitions of performance. As a software engineer, you will need to find out what kind of performance matters for your code, measure the performance of your code, define clear and useful performance goals, and ensure the code meets these goals. You will need to keep performance in mind when designing and writing code, and to debug the performance issues that cause your software to not meet its goals. ## Objectives After this lecture, you should be able to: - Contrast different metrics and scales for performance - Create benchmarks that help you achieve performance objectives - Profile code to find performance bottlenecks - Optimize code by choosing the right algorithms and tradeoffs for a given scenario ## What is performance? There are two key metrics for performance: _throughput_, the number of requests served per unit of time, and _latency_, the time taken to serve one request. In theory, we would like latency to be constant per request and throughput constant over time, but in practice, this is usually never the case. Some requests fundamentally require more work than others, such ordering a pizza with 10 toppings compared to a pizza with only cheese and tomatoes. Some requests go through different code paths because engineers made tradeoffs, such as ordering a gluten-free pizza taking more time because instead of maintaining a separate gluten-free kitchen, the restaurant has to clean its only kitchen. Some requests compete with other requests for resources, such as ordering a pizza right after a large table has placed an order in a restaurant with only one pizza oven. Latency thus has many sub-metrics in common use: mean, median, 99th percentile, and even latency just for the first request, i.e., the time the system takes to start. Which of these metrics you target depends on your use case, and has to be defined in collaboration with the customer. High percentiles such as the 99th percentile make sense for large systems in which many components are involved in any request, as [Google describes](https://research.google/pubs/pub40801/) in their "Tail at Scale" paper. Some systems actually care about the "100th percentile", i.e., the _worst-case execution time_, because performance can be a safety goal. For instance, when an airplane pilot issues a command, the plane must reply quickly. It would be catastrophic for the plane to execute the command minutes after the pilot has issued it, even if the execution is semantically correct. For such systems, worst-case execution time is typically over-estimated through manual or automated analysis. Some systems also need no variability at all, i.e., _constant-time_ execution. This is typically used for cryptographic operations, whose timing must not reveal any information about secret keys or passwords. In a system that serves one request at a time, throughput is the inverse of mean latency. In a system that serves multiple requests at a time, there is no such correlation. For instance, one core of a dual-core CPU might process a request in 10 seconds while another core has served 3 requests in that time, thus the throughput was 4 requests per 10 seconds but the latency varied per request. We used "time" as an abstract concept above, but in practice you will use concrete units such as minutes, seconds, or even as low as nanoseconds. Typically, you will care about the _bottleneck_ of the system: the part that takes the most time. There is little point in discussing other parts of the system since their performance is not key. For instance, if it takes 90 seconds to cook a pizza, it is not particularly useful to save 0.5 seconds when adding cheese to the pizza, or to save 10 nanoseconds in the software that sends the order to the kitchen. If you're not sure of how long a nanosecond is, check out [Grace Hopper's thought-provoking illustration](https://www.youtube.com/watch?v=gYqF6-h9Cvg) (the video has manually-transcribed subtitles you can enable). Grace Hopper was a pioneer in programming languages. With her team, she designed COBOL, the first language that could execute English-like commands. As she [recalled](https://www.amazon.com/Grace-Hopper-Admiral-Computer-Contemporary/dp/089490194X) it, "_I had a running compiler and nobody would touch it. They told me computers could only do arithmetic_". Thankfully, she ignored the naysayers, or we wouldn't be programming in high-level languages today! _Amdahl's law_ states that the speedup achieved by optimizing one component is at most that component's share of overall execution time. For instance, if a function takes 2% of total execution time, it is not possible to speed up the system more than 2% by optimizing that function, even if the function itself is made orders of magnitude faster. As you can tell, the word "performance" hides a lot of details, and "improving performance" is usually too abstract a goal. Optimizing a system requires clear goals defined in terms of specific workloads and metrics, and an understanding of which parts of the system currently take the most time. Performance objectives for services used by customers are typically defined in terms of _Service Level Indicators_, which are measures such as "median request latency", _Service Level Objectives_, which define goals for these measures such as "under 50ms", and _Service Level Agreements_, which add consequences to objectives such as "or we reimburse 20% of the customer's spending that month". Picking useful objectives is a key first step. "As fast as possible" is usually not useful since it requires too many tradeoffs, as [pizza chain Domino's found out](https://www.nytimes.com/1993/12/22/business/domino-s-ends-fast-pizza-pledge-after-big-award-to-crash-victim.html) after their promise of reimbursing late pizzas led to an increase in car crashes for their drivers. Systems should be fast enough, not perfect. What "enough" is depends on the context. Some software systems have specific performance requirements. Other times the performance requirements are implicit, making them harder to define. For instance, in 2006 Google [found](http://glinden.blogspot.com/2006/11/marissa-mayer-at-web-20.html) that traffic dropped 20% if their search results took 0.9s to show instead of 0.4s. In 2017, Akamai [found](https://www.akamai.com/uk/en/about/news/press/2017-press/akamai-releases-spring-2017-state-of-online-retail-performance-report.jsp) that even a 100ms increase in page load time could lead to a 7% drop in sales. In general, if users feel that an interface is "too slow", they won't like it, and if they have another choice they may use it instead. ## How can one measure performance? The process of measuring performance is called _benchmarking_, and it is a form of testing for performance. Like tests, benchmarks are usually automated, and come with issues such as how to isolate a specific component rather than always benchmark the entire system. Benchmarks for individual functions are typically called _microbenchmarks_, while benchmarks for entire systems are "end to end". In theory, benchmarking is a simple process: start a timer, perform an action, stop the timer. But in practice, there are many tricky parts. How precise is the timer? What's the timer's resolution? How variable is the operation? How many measurements should be taken for the results to be valid? Should outliers be discarded? What's the best API on each OS to time actions? How to avoid "warm up" effects? And caching effects? Are compiler optimizations invalidating the benchmark by changing the code? You should never write your own benchmarking code. (Unless you become an expert in benchmarking, at which point you will know you can break this rule.) Instead, use an existing benchmarking framework, such as JMH for Java, BenchmarkDotNet for .NET, or pytest-benchmark for Python. In practice, to benchmark some code, you first need to define the workload you will use, i.e., the inputs, and the metric(s) you care about. Then you need a _baseline_ for your benchmark. Absolute performance numbers are rarely useful, instead one usually compares to some other numbers, such as the performance of the previous version of the software. For low-level code or when benchmarking operations that take very little time, you may also need to set up your system in specific ways, such as configuring the CPU to not vary its frequency. It is very easy to accidentally write benchmark code that is meaningless in a non-obvious way. Always ask your colleagues to review your benchmark code, and provide the code whenever you provide the results. Try small variations of the code to see if you get small variations in the benchmark results. If you have any, reproduce previous results to ensure that your overall setup works. Beware of the "small input problem": it is easy to miss poorly-performing algorithms by only benchmarking with small inputs. For instance, if an operation on strings is in `O(n^3)` of the string length and you only use a string of size 10, that is 1000 operations, which is instantaneous on any modern CPU. And yet the algorithm is likely not great, since `O(n^3)` is usually not an optimal solution. Make sure you are actually measuring what you want to measure, rather than intermediate measurements that may or may not be representative of the full thing. For instance, [researchers found](https://dl.acm.org/doi/abs/10.1145/3519939.3523440) that some garbage collectors for Java had optimized for the time spent in the garbage collector at the expense of the time taken to run an app overall. By trying to minimize GC time at all costs, some GCs actually increased the overall running time. Finally, remember that it is not useful to benchmark and improve code that is already fast enough. While microbenchmarking can be addictive, you should spend your time on tasks that have impact to end users. Speeding up an operation from 100ms to 80ms can feel great, but if users only care about the task taking less than 200ms, they would probably have preferred you spend time on adding features or fixing bugs. ## How can one debug performance? Just like benchmarking is the performance equivalent of testing, _profiling_ is the performance equivalent of debugging. The goal of profiling is to find out how much time each operation in a system takes. There are two main kinds of profilers: _instrumenting_ profilers that add code to the system to record the time before and after each operation, and _sampling_ profilers that periodically stop the program to take a sample of what operation is running at that time. A sampling profiler is less precise, as it could miss some operations entirely if the program happens to never be running them when the profiler samples, but it also has far less overhead than an instrumenting profiler. It's important to keep in mind that the culprit of poor performance is usually a handful of big bottlenecks in the system that can be found and fixed with a profiler. The average function in any given codebase is fast enough compared to those bottlenecks, and thus it is important to profile before optimizing to ensure an engineer's time is well spent. For instance, a hobbyist once managed to [cut loading times by 70%](https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/) in an online game by finding the bottlenecks and fixing them. Both of them were `O(n^2)` algorithms that could be fixed to be `O(n)` instead. There are plenty of profilers for each platform, and some IDEs come with their own. For instance, Java has VisualVM. ## How can one improve performance? The typical workflow is as follows: 1. Double-check that the code is actually correct and that it is slower than what users need (otherwise there is no point in continuing) 2. Identify the bottleneck by profiling 3. Remove any unnecessary operations 4. Make some tradeoffs, if necessary 5. Go to step 1 Identifying the problem always requires measurements. Intuition is often wrong when it comes to performance. See online questions such as ["Why is printing "B" dramatically slower than printing "#"?"](https://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing) or ["Why does changing 0.1f to 0 slow down performance by 10x?"](https://stackoverflow.com/questions/9314534/why-does-changing-0-1f-to-0-slow-down-performance-by-10x). Once a problem is found, the first task is to remove any unnecessary operations the code is doing, such as algorithms that can be replaced by more efficient ones without losing anything other than development time. For instance, a piece of code may use a `List` when a `Set` would make more sense because the code mostly checks for membership. Or a piece of code may be copying data when it could use a reference to the original data instead, especially if the data can be made immutable. This is also the time to look for existing faster libraries or runtimes, such as [PyPy](https://www.pypy.org/) for Python, that are usually less flexible but are often enough. If necessary, after fixing obvious culprits that do not need complex tradeoffs, one must make serious tradeoffs. Unfortunately, in practice, performance tradeoffs occur on many axes: latency, throughput, code readability and maintainability, and sub-axes such as specific kinds of latency. ### Separating common cases One common tradeoff is to increase code size to reduce latency by adding specialized code for common requests. Think of how public transport is more efficient than individual cars, but only works for specific routes. Public transport cannot entirely replace cars, but for many trips it can make a huge difference. If common requests can be handled more efficiently than in the general case, it is often worthwhile to do so. ### Caching It is usually straightforward to reduce latency by increasing memory consumption through _caching_, i.e., remembering past results. In fact, the reason why modern CPUs are so fast is because they have multiple levels of caches on top of main memory, which is slow. Beware, however: caching introduces potential correctness issues, as the cache may last too long, or return obsolete data that should have been overwritten with the results of a newer query. ### Speculation and lazy loading You go to an online shop, find a product, and scroll down. "Customers who viewed this item also viewed..." and the shop shows you similar items you might want to buy, even before you make further searches. This is _speculation_: potentially lowering latency and increasing throughput if the predictions are successful, at the cost of increasing resource use and possibly doing useless work if the predictions are wrong. The opposite of speculation is _lazy loading_: only loading data when it is absolutely needed, and delaying any loading until then. For instance, search engines do not give you a page with every single result on the entire Internet for your query, because you will most likely find what you were looking for among the first results. Instead, the next results are only loaded if you need them. Lazy loading reduces the resource use for requests that end up not being necessary, but requires more work for requests that are actually necessary yet were not executed early. ### Streaming and batching Instead of downloading an entire movie before watching it, you can _stream_ it: your device will load the movie in small chunks, and while you're watching the first few chunks the next ones can be downloaded in the background. This massively decreases latency, but it also decreases throughput since there are more requests and responses for the same amount of overall data. The opposite of streaming is _batching_: instead of making many requests, make a few big ones. For instance, the postal service does not come pick up your letters every few minutes, since most trips would be a waste; instead, they come once or twice a day to pick up all of the letters at once. This increases throughput, at the expense of increasing latency. ## Summary In this lecture, you learned: - Defining performance: latency, throughput, variability, and objectives - Benchmarking and profiling: measuring and understanding performance and bottlenecks - Tradeoffs to improve performance: common cases, caching, speculation vs lazy loading, and streaming vs batching You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Debugging > **Prerequisite**: You are _strongly_ encouraged, though not strictly required, to use an IDE for the exercises about debugging in this lecture. > Alternatively, you can use Java's built-in command-line debugger, `jdb`, but it is far less convenient than a graphical user interface. Writing code is only one part of software engineering; you will often spend more time _reading_ code than writing code. This may be to understand a piece of code so you can extend it, or _debug_ existing code by finding and fixing bugs. These tasks are a lot easier if you write code with readability and debuggability in mind, and if you know how to use debugging tools. ## Objectives After this lecture, you should be able to: - Develop _readable_ code - Use a _debugger_ to understand and debug code - Isolate the _root cause_ of a bug - Develop _debuggable_ code ## What makes code readable? Take a look at [planets.py](exercises/lecture/planets.py) in the in-lecture exercise folder. Do you find it easy to read and understand? Probably not. Did you spot the fact that sorting doesn't work because the code uses a function that returns the sorted list, but does not use its return value, rather than an in-place sort? It's a lot harder to spot that bug when you have to use so much brain power just to read the code. Unfortunately, hard-to-read code doesn't only happen in exercises within course lecture notes. Consider the following snipped from the ScalaTest framework: ```scala package org.scalatest.tools object Runner { def doRunRunRunDaDoRunRun(...): Unit } ``` What does this method do? The method name isn't going to help you. It's a reference to [a song from 1963](https://en.wikipedia.org/wiki/Da_Doo_Ron_Ron). Sure, it's a funny reference, but wouldn't you rather be reading a name that told you what the method does? Worse, [the method has 21 parameters](https://github.com/scalatest/scalatest/blob/282da2aff8f439906fe5e7d9c3112c84019545e7/jvm/core/src/main/scala/org/scalatest/tools/Runner.scala#L1044-L1066). You can of course understand what the method does if you spend enough time on it, but should you have to? Let's talk about five components of code readability: naming, documentation, comments, formatting, and consistency. ### Names First, an example of _naming_ without even using code: measurement errors. If you measure the presence of something that's absent, that's a `type I error`. If you measure the absence of something that's present, that's a `type II error`. These kinds of errors happen all the time in, for instance, tests to detect viruses. However, it's easy to forget which is type `I` and which is type `II`. And even if you remember, a typo duplicating a character can completely change the meaning of a sentence. Instead, you can use `false positive` and `false negative`. These names are easier to understand, easier to remember, and more resilient to spelling mistakes. Names in code can also make the difference between code that's easy to understand and code that's hard to even mentally parse. A variable named `isUserOnline` in Java is fine... as long as it really is for an "is the user online?" boolean variable, that is. If it's an integer, it's a lot more confusing. And if you're writing Python instead, it's also a problem since Python uses underscores to separate words, a.k.a. "snake case", so it should be `is_user_online`. A variable named `can_overwrite_the_data` is quite a long name, which isn't a problem by itself, but it's redundant: of course we're overwriting "data", the name is too vague. Names are not only about variable, method, or class names. Consider the following method call: ```java split("abc", "a", true, true) ``` What does this method do? Good question. What if the call looked like this instead, with constants or enums? ```java split("abc", "a", SplitOptions.REMOVE_EMPTY_ENTRIES, CaseOptions.IGNORE_CASE) ``` This is the same method call, but we've given names instead of values, and now the meaning is clearer. These constants are only a workaround for Java's lack of named parameters, though. In Scala, and other languages like C#, you could call the method like this: ```scala split("abc", separator = "a", removeEmptyEntries = true, ignoreCase = true) ``` The code is now much more readable thanks to explicit names, without having to write extra code. A cautionary tale in good intentions with naming is _Hungarian notation_. Charles Simonyi, a Microsoft engineer from Hungary, had the good idea to start his variable names with the precise data type the variables contained, such as `xPosition` for a position on the X axis, or `cmDistance` for a distance in centimeters. This meant anyone could easily spot the mistake in a like such as `distanceTotal += speedLeft / timeLeft`, since dividing speed by time does not make a distance. This became known as "Hungarian notation", because in Simonyi's native Hungary, names are spelled with the family name first, e.g., "Simonyi Károly". Unfortunately, another group within Microsoft did not quite understand what Simonyi's goal was, and instead thought it was about the variable type. So they wrote variable names such as `cValue` for a `char` variable, `lIndex` for a `long` index, and so on, which makes the names harder to read without adding any more information than is already in the type. This became known as "Systems Hungarian", because the group was in the operating systems division, and unfortunately Systems Hungarian made its way throughout the "Win32" Windows APIs, which were the main APIs for Windows until recently. Lots of Windows APIs got hard-to-read names because of a misunderstanding! Once again, naming is not the only way to solve this issue, only one way to solve it. In the F# programming language, you can declare variables with units, such as `let distance = 30<cm>`, and the compiler will check that comparisons and computations make sense given the units. --- #### Exercise The following names all look somewhat reasonable, why are they poor? - `pickle` (in Python) - `binhex` (in Python) - `LinkedList<E>` (in Java's `java.util`) - `vector<T>` (in C++'s `std`) - `SortedList` (in C#'s `System.Collections`) <details> <summary>Answers (click to expand)</summary> <p> `pickling` is a rather odd way to refer to serializing and deserializing data as "preserving" it. `binhex` sounds like a name for some binary and hexadecimal utilities, but it's actually for a module that handles an old Mac format. A linked list and a doubly linked list are not the same thing, yet Java names the latter as if it was the former. A vector has a specific meaning in mathematics; C++'s `vector` is really a resizeable array. `SortedList` is an acceptable name for a sorted list class. But the class with that name is a sorted map! </p> </details> --- Overall, names are a tool to make code clear and succinct, as well as consistent with other code so that readers don't have to explicitly think about names. ### Documentation _Documentation_ is a tool to explain _what_ a piece of code does. Documentation is the main way developers learn about the code they use. When writing code, developers consult its documentation comments, typically within an IDE as tooltips. Documentation comments should thus succinctly describe what a class or method does, including information developers are likely to need such as whether it throws exceptions, or whether it requires its inputs to be in some specific format. ### Comments _Comments_ are a tool to _why_ a piece of code does what it does. Importantly, comments should not say _how_ a piece of code does what it does, as this information already exists in the code itself. Unfortunately, not all code is "self-documenting". Comments are a way to explain tricky code. Sometimes, code has to be written in a way that looks overly complicated or wrong because the code is working around some problem in its environment, such as a bug in a library, or a compiler that only produces fast assembly code in specific conditions. Consider the following good example of a comment, taken from an old version of the Java development kit's `libjsound`: ```c /* Workaround: 32bit app on 64bit linux gets assertion failure trying to open ports. Until the issue is fixed in ALSA (bug 4807) report no midi in devices in the configuration. */ if (jre32onlinux64) { return 0; } ``` This is a great example of an inline comment: it explains what the external problem is, what the chosen solution is, and refers to an identifier for the external problem. This way, a future developer can look up that bug in ALSA, a Linux audio system, and check if was fixed in the meantime so that the code working around the bug can be deleted. Inline comments are a way to explain code beyond what code itself can do, which is often necessary even if it ideally should not be. This explanation can be for the people who will review your code before accepting your proposed changes, or for colleagues who will read your code when working on the codebase months later. Don't forget that one of these "colleagues" is likely "future you". No matter how clear you think a piece of code is right now, future you will be grateful for comments that explain the non-obvious parts. ### Formatting Formatting code is all about making it easier to read code. You don't notice good formatting, but you do notice bad formatting, and it makes it harder to focus. Here is a real world example of bad formatting: ```c if (!update(&context, &params)) goto fail; goto fail; ``` Did you spot the problem? The code looks like the second `goto` is redundant, because it's formatted that way. But this is C. The second `goto` is actually outside of the scope of the `if`, and is thus always executed. This was a real bug that triggered [a vulnerability](https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/) in Apple products. Some languages enforce at least some formatting consistency, such as Python and F#. But as you saw with the `planets.py` exercise earlier, that does not mean it's impossible to format one's code poorly. ### Consistency Should you use `camelCase` or `snake_case` for your names? 4 or 8 spaces for indentation? Or perhaps tabs? So many questions. This is what _conventions_ are for. The entire team decides, once, what to do. Then every member of the team accepts the decisions, and benefits from a consistent code style without having to explicitly think about it. Beware of a common problem called _bikeshedding_ when deciding on conventions. The name comes from the story illustrating it: a city council meeting has two items on the agenda, the maintenance of a nuclear power plant and the construction of a bike shed. The council quickly approves the nuclear maintenance, which is very expensive, because they all agree that this maintenance is necessary to continue to provide electricity to the city. Then the council spends an hour discussing the plans for the bike shed, which is very cheap. Isn't it still too expensive? Surely the cost can be reduced a bit, a bike shed should be even cheaper. Should it be blue or red? Or perhaps gray? How many bikes does it need to contain? It's easy to spend lots of time on small decisions that ultimately don't matter much, because it's easy to focus on them. But that time should be spent on bigger decisions that are more impactful, even if they are harder to discuss. Once you have agreed on a convention, you should use tools to enforce it, not manual efforts. Command-line tools exist, such as `clang-format` for C code, as well as tools built into IDEs, which can be configured to run whenever you save a file. That way, you no longer have to think about what the team's preferences are, tools do it for you. ## How can one efficiently debug a program? Your program just got a bug report from a user: something doesn't work as expected. Now what? The presence of a bug implies that the code's behavior doesn't match the intent of the person who wrote it. The goal of _debugging_ is to find and fix the _root cause_ of the bug, i.e., the problem in the code that is the source of the bug. This is different from the _symptoms_ of the bug, in the same way that symptoms of a disease such as loss of smell are different from a root cause such as a virus. You will find the root cause by repeatedly asking "_why?_" when you see symptoms until you get to the root cause. For instance, let's say you have a problem: you arrived late to class. Why? Because you woke up late. Why? Because your alarm didn't ring. Why? Because your phone had no battery. Why? Because you forgot to plug your phone before going to sleep. Aha! That's the cause of the bug. If you had stopped at, say, "your alarm didn't ring", and tried to fix it by adding a second phone with an alarm, you would simply have two alarms that didn't ring, because you would forget to plug in the second phone as well. But now that you know you forgot to plug in your phone, you can attack the root cause, such as by putting a post-it above your bed reminding you to charge your phone. You could in theory continue asking "why?", but it stops being helpful after a few times. In this case, perhaps the "real" root cause is that you forget things often, but you cannot easily fix that. At a high level, there are three steps to debugging: reproduce the bug, isolate the root cause, and debug. Reproducing the bug means finding the conditions under which it appears: - What environment? Is it on specific operating systems? At specific times of the day? In specific system languages? - What steps need to be taken to uncover the bug? These could be as simple as "open the program, click on the 'login' button, the program crashes", or more complex, such as creating multiple users with specific properties and then performing a sequence of tasks that trigger a bug. - What's the expected outcome? That is, what do you expect to happen if there is no bug? - What's the actual outcome? This could be simply "a crash", or it could be something more complex, such as "the search results are empty even though there is one item matching the search in the database" - Can you reproduce the bug with an automated test? This makes it easier and less error-prone to check if you have fixed the bug or not. Isolating the bug means finding roughly where the bug comes from. For instance, if you disable some of your program's modules by commenting out the code that uses them, does the bug still appear? Can you find which modules are necessary to trigger the bug? You can also isolate using version control: does the bug exist in a previous commit? If so, what about an even older commit? Can you find the one commit that introduced the bug? If you can find which commit introduced the bug, and the commit is small enough, you have drastically reduced the amount of code you need to look at. Finally, once you've reproduced and isolated the bug, it's time to debug: see what happens and figure out why. You could do this with print statements: ```c printf("size: %u, capacity: %u\n", size, capacity); ``` However, print statements are not convenient. You have to write potentially a lot of statements, especially if you want to see the values within a data structure or an object. You may not even be able to see the values within an object if they are private members, at which point you need to add a method to the object just to print some of its private members. You also need to manually remove prints after you've fixed the bug. Furthermore, if you realize while executing the program that you forgot to print a specific value, using prints forces you to stop the program, add a print, and run it again, which is slow. Instead of print statements, use a tool designed for debugging: a debugger! ### Debuggers A debugger is a tool, typically built into an IDE, that lets you pause the execution of a program wherever you want, inspect what the program state is and even modify the state, and generally look at what a piece of code is actually doing without having to modify that piece of code. One remark about debuggers, and tools in general: some people think that not using a tool, and doing it the "hard" way instead, somehow makes them better engineers. This is completely wrong, it's the other way around: knowing what tools are available and using them properly is key to being a good engineer. Just like you would ignore people telling you to not take a flashlight and a bottle of water when going hiking in a cave, ignore people who tell you to not use a debugger or any other tool you think is useful. Debuggers also work for software that runs on other machines, such as a server, as long as you can launch a debugging tool there, you can run the graphical debugger on your machine to debug a program on a remote machine. There are also command-line debuggers, such as `jdb` for Java or `pdb` for Python, though these are not as convenient since you must manually input commands to, e.g., see what values variables have. The one prerequisite debuggers have is a file with _debug symbols_: the link between the source code and the compiled code. That is, when the program executes a specific line of assembly code, what line is it in the source code? What variables exist at that point, and in which CPU registers are they? This is of course not necessary for interpreted languages such as Python, for which you have the source code anyway. It is technically possible to run a debugger without debug symbols, but you then have to figure out how the low-level details map to high-level concepts yourself, which is tedious. Let's talk about five key questions you might ask yourself while debugging, and how you can answer them with a debugger. _Does the program reach this line?_ Perhaps you wonder if the bug triggers when a particular line of code executes. To answer this question, use a _breakpoint_, which you can usually do by right-clicking on a line and selecting "add a breakpoint" from the context menu. Once you have added a breakpoint, run the program in debug mode, and execution will pause once that line is reached. Debuggers typically allow more advanced breakpoints as well, such as "break only if some condition holds", or "break once every N times this line is executed". You can even use breakpoints to print things instead of pausing execution. Wait, didn't we just say prints weren't a good idea? The reason why printing breakpoints are better is that you don't need to edit the code, and thus don't need to revert those edits later, and you can change what is printed where while the program is running. _What's the value of this variable?_ You've added a breakpoint, the program ran to it and paused execution, now you want to see what's going on. In an IDE, you can typically hover your mouse over a variable in the source code to see its value while the program is paused, as well as view a list of all local variables. This includes the values within data structures such as arrays, and the private members in classes. You can also execute code to ask questions, such as `n % 12 == 0` to see if `n` is currently a multiple of 12, or `IsPrime(n)` if you have an `IsPrime` method and want to see if what it returns for `n`. _What if instead...?_ You see that a variable has a value you didn't expect, and wonder if the bug would disappear if it had a different value. Good news: you can try exactly that. Debuggers typically have some kind of "command" window where you can write lines such as `n = 0` to change the value of `n`, or `lst.add("x")` to add `"x"` to the list `lst`. _What will happen next?_ The program state looks fine, but maybe the next line is what causes the problem? "Step" commands let you execute the program step-by-step, so that you can look at the program state after executing each step to see when something goes awry. "Step into" will let you enter any method that is called, "step over" will go to the next line instead of entering a method, and "step out" will finish executing the current method. Some debuggers have additional tools, such as a "smart" step that only goes inside methods with more than a few lines. Depending on the programming language and the debugger, you might even be able to change the instruction pointer to whichever line of code you want, and edit some code on the fly without having to stop program execution. Note that you don't have to use the mouse to run the program and run step by step: debuggers typically have keyboard shortcuts, such as using F5 to run, F9 to step into, and so on, and you can usually customize those. Thus, your workflow will be pressing a key to run, looking at the program state after the breakpoint is hit, then pressing a key to step, looking at the program state, stepping again, and so on. _How did we get here?_ You put a breakpoint in a method, the program reached it and paused execution, but how did the program reach this line? The _call stack_ is there to answer this: you can see which method called you, which method called that one, and so on. Not only that, but you can view the program state at the point of that call. For instance, you can see what values were given as arguments to the method who called the method who called the method you are currently in. _What happened to cause a crash?_ Wouldn't it be nice if you could see the program state at the point at which there was a crash on a user's machine? Well, you can! The operating system can generate a _crash dump_ that contains the state of the program when it crashes, and you can load that crash dump into a debugger, along with the source code of the program and the debugging symbols, to see what the program state was. This is what happens when you click on "Report the problem to Microsoft" after your Word document crashed. Note that this only works with crashes, not with bugs such as "the behavior is not what I expect" since there is no automated way to detect such unexpected behavior. ### Debugging in practice When using a debugger to find the root cause of a bug, you will add a breakpoint, run the program until execution pauses to inspect the state, optionally make some edits to the program given your observations, and repeat the cycle until you have found the root cause. However, sometimes you cannot figure out the problem on your own, and you need help. This is perfectly normal, especially if you are debugging code written by someone else. In this case, you can ask a colleague for help, or even post on an Internet forum such as [StackOverflow](https://stackoverflow.com). Come prepared, so that you can help others help you. What are the symptoms of the bug? Do you have an easy way to reproduce the bug? What have you tried? Sometimes, you start explaining your problem to a colleague, and during your explanation a light bulb goes off in your head: there's the problem! Your colleague then stares at you, happy that you figured it out, but a bit annoyed to be interrupted. To avoid this situation, start by _rubber ducking_: explaining your problem to a rubber duck, or to any other inanimate object. Talk to the object as if it was a person, explaining what your problem is. The reason this works is that when we explain a problem to someone else, we typically explain what is actually happening, rather than what we wish was happening. If you don't understand the problem while explaining it to a duck, at least you have rehearsed how you will explain the bug, and you will be able to better explain it to a human. There is only one way to get better at debugging: practice doing it. Next time you encounter a bug, use a debugger. The first few times, you may be slower than you would be without one, but after that your productivity will skyrocket. --- #### Exercise Run the code in the [binary-tree](exercises/lecture/binary-tree) folder. First, run it. It crashes! Use a debugger to add breakpoints and inspect what happens until you figure out why, and fix the bugs. Note that the crash is not the only bug. <details> <summary>Solution (click to expand)</summary> <p> First, there is no base case to the recursive method that builds a tree, so you should add one to handle the `list.size() == 0` case. Second, the bounds for sub-lists are off: they should be `0..mid` and `mid+1..list.size()`. There is a correctness bug: the constructor uses `l` twice, when it should set `right` to `r`. This would not have happened if the code used better names! We provide a [corrected version](exercises/solutions/lecture/BinaryTree.java). </p> </details> ## What makes code debuggable? The inventor [Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage) once said about a machine of his "_On two occasions, I have been asked 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?'_ _I am not able to rightly apprehend the kind of confusion of ideas that could provoke such a question._" It should be clear that a wrong input cannot lead to a correct output. Unfortunately, often a wrong input leads to a wrong output _silently_: there is no indication that anything wrong happened. This makes it hard to find the root cause of a bug. If you notice something is wrong, is it because the previous operation did something wrong? Or because the operation 200 lines of code earlier produced garbage that then continued unnoticed until it finally caused a problem? [Margaret Hamilton](https://en.wikipedia.org/wiki/Margaret_Hamilton_\(software_engineer\)), who coined the term "software engineering" to give software legitimacy based on her experience developing software for early NASA missions, [said](https://www.youtube.com/watch?v=ZbVOF0Uk5lU) of her early work "we learned to spend more time up front [...] so that we wouldn't waste all that time debugging". We will see three methods to make code debuggable: defensive programming, logging, and debug-only code. ### Defensive programming Bugs are attacking you, and you must defend your code and data! That's the idea behind _defensive programming_: make sure that problems that happen outside of your code cannot corrupt your state or cause you to return garbage. These problems could for instance be software bugs, humans entering invalid inputs, humans deliberately trying to attack the software, or even hardware corruption. It may seem odd to worry about hardware corruption, but it happens more often than one thinks; for instance, a single bit flip can turn `microsoft.com` into `microsfmt.com`, since `o` is usually encoded as `01101101` in binary, which can flip to `01101111`, the encoding for `m`. Software that intends to talk to `microsoft.com` could thus end up receiving data from `microsfmt.com` instead, which may be unrelated, specifically set up for attacks, or [an experiment to see how much this happens](http://dinaburg.org/bitsquatting.html). Instead of silently producing garbage, code should fail as early as possible. The closest a failure is to its root cause, the easier it is to debug. The key tool to fail early is _assertions_. An assertion is a way to check whether the code actually behaves in the way the engineer who wrote it believes it should. For instance, if a piece of code finds the `index` of a `value` in an `array`, an engineer could write the following immediately after finding `index`: ```java if (array[index] != val) { throw new AssertionError(...); } ``` If this check fails, there must be a bug in the code that finds `index`. The "isolate the bug" step of debugging is already done by the assertion. What should be done if the check fails, though? Crash the program? This depends on the program. Typically, if there is a way to cut off whatever caused the problem from the rest of the program, that's a better idea. For instance, the current _request_ could fail. This could be a request made to a server, for instance, or an operation triggered by a user pressing a button. The software can then display a message stating an error occurred, enabling the user to either retry or do something else. However, some failures are so bad that it is not reasonable to continue. For instance, if the code loading the software's configuration fails an assertion, there is no point in continuing without the configuration. An assertion that must hold when calling a method is a _precondition_ of that method. For instance, an `int pickOne(int[] array)` method that returns one of the array's elements likely has as precondition "the array isn't `null` and has at least `1` element". The beginning of the method might look like this: ```java int pickOne(int[] array) { if (array == null || array.length == 0) { throw new IllegalArgumentException(...); } // ... } ``` If a piece of code calls `pickOne` with a null or empty array, the method will throw an `IllegalArgumentException`. Why bother checking this explicitly when the method would fail early anyway if the array was null or empty, since the method will dereference the array and index its contents? The type of exception thrown indicates _whose fault it is_. If you call `pickOne` and get a `NullPointerException`, it is reasonable to assume that `pickOne` has a bug, because this exception indicates the code of `pickOne` believes a given reference is non-null, since it dereferences it, yet in practice the reference is null. However, if you call `pickOne` and get an `IllegalArgumentException`, it is reasonable to assume that your code has a bug, because this exception indicates you passed an argument whose value is illegal. Thus, the type of exception helps you find where the bug is. An assertion that must hold when a method returns is a _postcondition_ of that method. In our example, the postcondition is "the returned value is some value within the array", which is exactly what you call `pickOne` to get. If `pickOne` returns a value not in the array, code that calls it will yield garbage, because the code expected `pickOne` to satisfy its contract yet this did not happen. It isn't reasonable to insert assertions every time one calls a method to check that the returned value is acceptable; instead, it's up to the method to check that it honors its postcondition. For instance, the end of `pickOne` might look like this: ```java int result = ... if (!contains(array, result)) { throw new AssertionError(...); } return result; ``` This way, if `result` was computed incorrectly, the code will fail before corrupting the rest of the program with an invalid value. Some assertions are both pre- and postconditions for the methods of an object: _object invariants_. An invariant is a condition that always hold from the outside. It may be broken during an operation, as long as this is not visible to the outside world because it is restored before the end of the operation. For instance, consider the following fields for a stack: ```java class Stack { private int[] values; private int top; // top of the stack within `values` } ``` An object invariant for this class is `-1 <= top < values.length`, i.e., either `top == -1` which means the stack is empty, or `top` points to the top value of the stack within the array. One way to check invariants is to write an `assertInvariants` method that asserts them and call it at the end of the constructor and the beginning and end of each method. All methods of the class must preserve the invariant so that they can also rely on it holding when they get called. This is one reason encapsulation is so useful: if anyone could modify `values` or `top` without going through the methods of `Stack`, there would be no way to enforce this invariant. Consider the following Java method: ```java void setWords(List<String> words) { this.words = words; } ``` It seems trivially correct, and yet, it can be used in the following way: ``` setWords(badWords); badWords.add("Bad!"); ``` Oops! Now the state of the object that holds `words` has been modified from outside of the object, which could break any invariants the object is supposed to have. To avoid this and protect one's state, _data copies_ are necessary when dealing with mutable values: ```java void setWords(List<String> words) { this.words = new ArrayList<>(words); } ``` This way, no changes can occur to the object's state without its knowledge. The same goes for reads, with `return this.words` being problematic and `return new ArrayList<>(this.words)` avoiding the problem. Even better, if possible the object could use an _immutable_ list for `words`, such as Scala's default `List[A]`. This fixes the problem without requiring data copies, which slow down the code. --- #### Exercise Check out the code in the [stack](exercises/lecture/stack) folder, which contains an `IntStack` class and a usage example. Add code to `IntStack` to catch problems early, and fix any bugs you find in the process. First, look at what the constructor should do. Once you've done that, add an invariant and use it, and a precondition for `push`. Then fix any bugs you find. <details> <summary>Solution (click to expand)</summary> <p> First, the constructor needs to throw if `maxSize < 0`, since that is invalid. Second, the stack should have the invariant `-1 <= top < values.length`, as discussed above. After adding this invariant, note that `top--` in `pop` can break the invariant since it is used unconditionally. The same goes for `top++` in `push`. These need to be changed to only modify `top` if necessary. To enable the users of `IntStack` to safely call `push`, one can expose an `isFull()` method, and use it as a precondition of `push`. We provide a [corrected version](exercises/solutions/lecture/Stack.java). </p> </details> ### Logging _What happened in production?_ If there was a crash, then you can get a crash dump and open it in a debugger. But if it's a more subtle bug where the outcome "looks wrong" to a human, how can you know what happened to produce this outcome? This is where _logging_ comes in: recording what happens during execution so that the log can be read in case something went wrong. One simple way to log is print statements: ```python print("Request: " + request) print("State: " + state) ``` This works, but is not ideal for multiple reasons. First, the developer must choose what to log at the time of writing the program. For instance, if logging every function call is considered too much for normal operation, then the log of function calls will never be recorded, even though in some cases it could be useful. Second, the developer must choose how to log at the time of writing the program. Should the log be printed to the console? Saved to a file? Both? Perhaps particular events should send an email to the developers? Third, using the same print function for every log makes it hard to see what's important and what's not so important. Instead of using a specific print function, logging frameworks provide the abstraction of a log with multiple levels of importance, such as Python's logging module: ```python logging.debug("Detail") logging.info("Information") logging.warning("Warning") logging.error("Error") logging.critical("What a Terrible Failure") ``` The number of log levels and their name changes in each logging framwork, but the point is that there are multiple ones and they do not imply anything about where the log goes. Engineers can write logging calls for everything they believe might be useful, using the appropriate log level, and decide _later_ what to log and where to log. For instance, by default, "debug" and "info" logs might not even be stored, as they are too detailed and not important enough. But if there is currently a subtle bug in production, one can enable them to see exactly what is going on, without having to restart the program. It may make sense to log errors with an email to the developers, but if there are lots of errors the developers are already aware of, they might decide to temporarily log errors to a file instead, again without having to restart the program. It is important to think about privacy when writing logging code. Logging the full contents of every request, for instance, might lead to logging plain text passwords for a "user creation" function. If this log is kept in a file, and the server is hacked, the attackers will have a nice log of every password ever set. ### Debug-only code What about defensive programming checks and logs that are too slow to reasonably enable in production? For instance, if a graph has as invariant "no node has more than 2 edges", but the graph typically has millions of nodes, what to do? This is where _debug-only_ code comes in. Programming languages, their runtimes, and frameworks typically offer ways to run code only in debug mode, such as when running automated tests. For instance, in Python, one can write an `if __debug__:` block, which will execute only when the code is not optimized. It's important to double-check what "debug" and "optimized" mean in any specific context. For instance, in Python `__debug__` is `True` by default, unless the interpreter is run with the `-O` switch, for "optimize". In Java, assertions are debug-only code but they are disabled by default, and can be enabld with the `-ea` switch. Scala has multiple levels of debug-only code that are all on by default but can be selectively disabled with the `-Xelide-below` switch. Even more important, before writing debug-only code, think hard about what is "reasonable" to enable in production given the workloads you have. Spending half a second checking an invariant is fine in a piece of code that will take seconds to run because it makes many web requests, for instance, even though half a second is a lot in CPU time. Keep in mind what [Tony Hoare](https://en.wikipedia.org/wiki/Tony_Hoare), one of the pioneers of computer science and especially programming languages and verification, once said in his ["Hints on Programming Language Design"](https://dl.acm.org/doi/abs/10.5555/63445.C1104368): "_It is absurd to make elaborate security checks on debugging runs, when no trust is put in the results,_ _and then remove them in production runs, when an erroneous result could be expensive or disastrous._ _What would we think of a sailing enthusiast who wears his life-jacket when training on dry land_ _but takes it off as soon as he goes to sea?_" ## Summary In this lecture, you learned: - How to write readable code: naming, formatting, comments, conventions - How to debug code: reproducing bugs, using a debugger - How to write debuggable code: defensive programming, logging, debug-only code You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Asynchrony You're writing an app and want it to download data and process it, so you write some code: ```java data = download(); process(data); ``` This works fine if both of these operations finish in the blink of an eye... but if they take more than that, since these operations are all your code is doing, your user interface will be frozen, and soon your users will see the dreaded "application is not responding" dialog from the operating system. Even if your app has no user interface and works in the background, consider the following: ```java firstResult = computeFirst(); secondResult = computeSecond(); compare(firstResult, secondResult); ``` If `computeFirst` and `computeSecond` are independent, the code as written is likely a waste of resources, since modern machines have multiple CPU cores and thus your app could have computed them in parallel before executing the comparison on both results. Even if you have a single CPU core, there are other resources, such as the disk: ```java for (int i = 0; i < 100; i++) { chunk = readFromDisk(); process(chunk); } ``` As written, this code will spend some of its time reading from the disk, and some of its time processing the data that was read, but never both at the same time, which is a waste of resources and time. These examples illustrate the need for _asynchronous code_. For instance, an app can start a download in the background, show a progress bar while the download is ongoing, and process the data once the download has finished. Multiple computations can be executed concurrently. A disk-heavy program can read data from the disk while it is processing data already read. ## Objectives After this lecture, you should be able to: - Understand _asynchrony_ in practice - Build async code with _futures_ - Write _tests_ for async code - _Design_ async software components ## What are async operations? Asynchronous code is all about starting an operation without waiting for it to complete. Instead, one schedules what to do after the completion. Asynchronous code is _concurrent_, and if resources are available it can also be _parallel_, though this is not required. There are many low-level primitives you could use to implement asynchrony: threads, processes, fibers, and so on. You could then use low-level interactions between those primitives, such as shared memory, locks, mutexes, and so on. You could do all of that, but low-level concurrency is _very hard_. Even experts who have spent years understanding hardware details regularly make mistakes. This gets even worse with multiple kinds of hardware that provide different guarantees, such as whether a variable write is immediately visible to other threads or not. Instead, we want a high-level goal: do stuff concurrently. An asynchronous function is similar to a normal function, except that it has two points of return: synchronously, to let you know the operation has started, and asynchronously, to let you know the operation has finished. Just like a synchronous function can fail, an asynchronous function can fail, but again at two points: synchronously, to let you know the operation cannot even start, perhaps because you gave an invalid argument, and asynchronously, to let you know the operation has failed, perhaps because there was no Internet connection even after retrying in the background. We would like our asynchronous operations to satisfy three goals: they should be composable, they should be completion-based, and they should minimize shared state. Let's see each of these three. ### Composition When baking a cake, the recipe might tell you "when the melted butter is cold _and_ the yeast has proofed, _then_ mix them to form the dough". This is a kind of composition: the recipe isn't telling you to stand in front of the melted butter and watch it cool, rather it lets you know what operations must finish for the next step and what that next step is. You are free to implement the two operations however you like; you could stand in front of the butter, or you could go do something else and come back later. Composition is recursive: once you have a dough, the next step might be "when the dough has risen _and_ the filling is cold, _then_ fill the dough". Again, this is a composition of asynchronous operations into one big operation representing making a filled dough. The two previous examples were _and_, but _or_ is also a kind of composition. The recipe might tell you "bake for 30 minutes, _or_ until golden brown". If the cake looks golden brown after 25 minutes, you take it out of the oven, and forget about the 30 minutes. One important property of composition is that errors must implicitly compose, too. If the ripe strawberries you wanted to use for the filling splash on the floor, your overall "bake a cake" operation has failed. The recipe doesn't explicitly tell you that, because it's a baking convention that if any step fails, you should stop and declare the whole operation a failure, unless you can re-do the failed operation from scratch. Maybe you have other strawberries you can use instead. ### Completion If you have a cake you'd like to bake, you could ask a baker "please let me know when you've finished baking the cake", which is _completion-based_. Alternatively, you could ask them "please let me know when the oven is free" and then bake it yourself, which is a bit lower level and gives you more control. This is _readiness-based_, and some older APIs, such as those found on Unix, were designed that way. The problem with readiness-based operations is that they lead to inefficiencies due to concurrent requests. The baker just told you the oven was ready, but unbeknownst to you, another person has put their cake in the oven before you've had time to get there. Now your "put the cake in the oven" operation will fail, and you have to ask the baker to let you know when the oven is free again, at which point the same problem could occur. ### Minimizing shared state Multiple asynchronous operations might need to read and write to the same shared state. For instance, the task of counting all elements in a large collection that satisfy some property could be parallelized by dividing the collection into chunks and processing multiple chunks in parallel. Each sub-task could then increment a global counter after every matching element it sees. However, shared state introduces an exponential explosion in the number of paths through a piece of software. There is one path in which the code of sub-task 1 accesses the shared state first, and one in which sub-task 2 accesses it first, and so on for each sub-task and for each shared state access. Even with a simple counter, one already needs to worry about atomic updates. With more complex shared state, one needs to worry about potential bugs that only happen with specific "interleavings" of sub-task executions. For instance, there may be a crash only if sub-task 3 accessed shared state first, followed by 2, followed by 3 again, followed by 1. This may only happen to a small fraction of users. Then one day, a developer speeds up the code of sub-task 3, and now the bug happens more frequently because the problematic interleaving is more common. The next day, a user gets an operating system update which slightly changes the scheduling policy of threads in the kernel. Now the bug happens all the time for this user, because the operating system happens to choose an order of execution that exposes the bug on that user's machine. Asynchronous operations must minimize shared state, for instance by computing a local result, then merging all local results into a single global result at the end. One extreme form of minimizing state is _message passing_: operations send each other messages rather than directly accessing the same state. For instance, operations handling parts of a large collection could do their work and then send their local result as a message to another "monitor" operation which is responsible for merging these results. Message passing is the standard way to communicate for operations across machines already, so it can make sense to do it even on a single machine. One interesting use of this is the [Multikernel](https://www.sigops.org/s/conferences/sosp/2009/papers/baumann-sosp09.pdf), an operating system that can run on multiple local CPUs each of a different architecture, because it uses only message passing and never shared memory, thus what each local thread runs on is irrelevant. ## How can we write maintainable async code? A simple and naïve way to write asynchronous code is with _callbacks_. Instead of returning a value, functions take an additional callback argument that is called with the value once it's ready: ```java void send(String text, Consumer<String> callback); send("hello", reply -> { System.out.println(reply); }); ``` One can call an asynchronous function within a callback, leading to nested callbacks: ```java send("hello", reply -> { send("login", reply2 -> { // ... }); }); ``` But this becomes rather messy. And we haven't even discussed errors yet, which need another callback: ```java void send( String text, Consumer<String> callback, Consumer<Exception> errorCallback ); ``` Code that uses callbacks frequently ends in "callback hell": ```java send("hello", reply -> { send("login", reply2 -> { send("join", reply3 -> { send("msg", reply4 -> { send("msg", reply5 -> { send("logout", reply6 -> { // ... }); }); }); }); }); }); ``` This code is hard to read and to maintain, because callbacks are _too_ simple and low-level. They do not provide easy ways to be composed, especially when dealing with errors as well. The resulting code is poorly structured. Just because something is simple does not mean it is good! Instead of overly-simple callbacks, modern code uses _futures_. A future is an object that represents an operation in one of three states: in progress, finished successfully, or failed. In Java, futures are represented with the `CompletableFuture<T>` class, where T is the type of the result. Since `void` is not a type, Java has the type `Void` with a capital `V` to indicate no result, thus an asynchronous operation that would return `void` if it was synchronous instead returns a `CompletableFuture<Void>`. `CompletableFuture`s can be composed with synchronous operations and with asynchronous operations using various methods. ### Composing `CompletableFuture`s The `thenAccept` method creates a future that composes the current one with a synchronous operation. If the current future fails, so does the overall future; but if it succeeds, the overall future represents applying the operation to the result. And if the operation fails, the overall future has failed: ```java CompletableFuture<String> future = // ... return future.thenAccept(System.out::println); ``` Sometimes a failure can be replaced by some kind of "backup" value, such as printing the error message if there is one instead of not printing anything. The `exceptionally` method returns a future that either returns the result of the current future if there is one, or transforms the future's exception into a result: ```java return future.exceptionally(e -> e.getMessage()) .thenAccept(System.out::println); ``` One may wish to not potentially wait forever, such as when making a network request if the server is very slow or the network connectivity is just good enough to connect but not good enough to transmit data at a reasonable rate. Implementing timeouts properly is difficult, but thankfully the Java developers provided a method to do it easily: ```java return future.orTimeout(5, TimeUnit.SECONDS) .exceptionally(e -> e.getMessage()) .thenAccept(System.out::println); ``` The returned combined future represents: - Printing the result of the original future, if it completes successfully within 5s - Printing the failure of the original future, if it fails within 5s - Printing the message from the timeout error, if the original future takes more than 5s Futures can be composed with asynchronous operations too, such as with `thenCompose`: ```java CompletableFuture<String> getMessage(); CompletableFuture<Void> log(String text); return getMessage().thenCompose(log); ``` The returned future represents first getting the message, then logging it, or failing if either of these operations fail. Composing futures in parallel and doing something with both results can be done with the `thenCombine` method: ```java CompletableFuture<String> computeFirst(); CompletableFuture<String> computeSecond(); return computeFirst().thenCombine(computeSecond(), (a, b) -> a + b); ``` The resulting future in this example represents doing both operations concurrently and returning the concatenation of their results, or failing if either future fails or if the combination operation fails. One can compose more than two futures into one that executes them all concurrently with a method such as allOf: ``` CompletableFuture<Void> uploads = ...; for (int n = 0; n < uploads.length; n++) { uploads[n] = ... } return CompletableFuture.allOf(uploads); ``` In the loop, each upload will start, and by the time the loop has ended, some of the uploads may have finished while others may still be in progress. The resulting future represents the combined operation. One can also use `anyOf` to represent the operation of waiting for any one of the futures to finish and ignoring the others. Refer to the [Javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/CompletableFuture.html) for the exact semantics of these operations on failures. _A quick warning about rate limits._ We have just seen code that allows one to easily upload a ton of data at the same time. Similar code can be written with an operation to download data, or to call some API that triggers an operation. However, in practice, many websites will rate limit users to avoid one person using too many resources. For instance, at the time of this writing, GitHub allows 5000 requests per hour. Doing too many operations in a short time may get you banned from an API, so look at the documentation of any API you're using carefully before starting hundreds of futures representing API calls. ### Creating `CompletableFuture`s One can create a future and complete it after some work in a background thread like so: ```java var future = new CompletableFuture<String>(); new Thread(() -> { // ... do some work ... future.complete("hello"); }).start(); return future; ``` Instead of `complete`, one can use `completeExceptionally` to fail the future instead, giving the exception that caused the failure as an argument instead of the result. This code forks execution into two logical threads: one that creates `future`, creates and starts the threads, and returns `future`; and one that contains the code in the `Thread` constructor. By the time `return future` executes, the future may already have been completed, or it may not. The beauty of futures is that the code that obtains the returned future doesn't have to care. Instead, it will use composition operations, which will do the right thing whether the future is already completed, still in progress, or will fail. Creating a Future representing a background operation is common enough that there is a helper method for it: ```java return CompletableFuture.supplyAsync(() -> { // ... do some work ... return "hello"; // or throw an exception to fail the Future }); ``` Sometimes one wants to create a future representing an operation that is already finished, perhaps because the result was cached. There is a method for that too: ```java return CompletableFuture.completedFuture("hello"); ``` However, creating futures is a low-level operation. Most code composes futures created by lower-level layers. For instance, a TCP/IP stack might create futures. Another reason to create futures is when adapting old asynchronous code that uses other patterns, such as callbacks. --- #### Exercise Take a look at the four methods in [`Basics.java`](exercises/lecture/src/main/java/Basics.java), and complete them one by one, based on the knowledge you've just acquired. You can run `App.java` to see if you got it right. <details> <summary>Suggested solution (click to expand)</summary> <p> - Printing today's weather is done by composing `Weather.today` with `System.out.println` using `thenAccept` - Uploading today's weather is done by composing `Weather.today` with `Server.upload` using `thenCompose` - Printing either weather is done using `acceptEither` on two individual futures, both of which use `thenApply` to prefix their results, with `System.out.println` as the composition operation - Finally, `Weather.all` should be composed with `orTimeout` and `exceptionallyCompose` to use `Weather.today` as a backup We provide a [solution example](exercises/solutions/lecture/src/main/java/Basics.java). </p> </details> --- ### Sync over async Doing the exercise above, you've noticed `App.java` uses `join()` to block until a future finishes and either return the result or throw the error represented by the future. There are other such "sync over async" operations, such as `isDone()` and `isCompletedExceptionallly()` to check a future's status. "Sync over async" operations are useful specifically to use asynchronous operations in a context that must be synchronous, typically because you are working with a framework that expects a synchronous operation. Java's `main()` method must be synchronous, for instance. JUnit also expects `@Test`s to be synchronous. This is not true of all frameworks, e.g., C# can have asynchronous main methods, and most C# testing frameworks support running asynchronous test methods. You might also need to use methods such as `isDone()` if you are implementing your own low-level infrastructure code for asynchronous functions, though that is a rare scenario. In general, everyday async functions must _not_ use `join()` or any other method that attempts to synchronously wait for or interact with an asynchronous operation. If you call any of these methods on a future outside of a top-level method such as `main` or a unit test, you are most likely doing something wrong. For instance, if in a button click handler you call `join()` on a `CompletableFuture` representing the download of a picture, you will freeze the entire app until the picture is downloaded. Instead, the button click handler should compose that future with the operation of processing the picture, and the app will continue working while the download and processing happen in the background. ### Sync errors Another form of synchrony in asynchronous operations is synchronous errors, i.e., signalling that an asynchronous operation could not even be created. Unlike asynchronous errors contained in Futures, which in Java are handled with methods such as `exceptionally(...)`, synchronous errors are handled with the good old `try { ... } catch { ... }` statement. Thus, if you call a method that could fail synchronously or asynchronously and you want to handle both cases, you must write the error handling code twice. Only use sync errors for bugs, i.e., errors that are not recoverable and indicate something has gone wrong such as an `IllegalArgumentException`: ```java CompletableFuture<Void> send(String s) { if (s == null) { // pre-condition violated, the calling code has a bug throw new IllegalArgumentException(...); } ... } ``` You will thus not have to duplicate error handling logic, because you will not handle unrecoverable errors. **Never** do something like this in Java: ```java CompletableFuture<Void> send(String s) { if (internetUnavailable) { // oh well, we already know it'll fail, we can fail synchronously...? throw new IOError(...); } ... } ``` This forces all of your callers to handle both synchronous and asynchronous exceptions. Instead, return a `CompletableFuture` that has failed already: ```java if (internetUnavailable) { return CompletableFuture.failedFuture(new IOError(...)); } ``` This enables your callers to handle that exception just like any other asynchronous failure: with future composition. Another thing you should **never** do is return a `null` future: ```java if (s.equals("")) { // nothing to do, might as well do nothing...? return null; } ``` While Java allows any value of a non-primitive type to be `null`, ideally `CompletableFuture` would disallow this entirely, as once again this forces all of your callers to explicitly handle the `null` case. Instead, return a `CompletableFuture` that is already finished: ```java if (s.equals("")) { return CompletableFuture.completedFuture(null); } ``` ### Cancellation One form of failure that is expected is _cancellation_: a future might fail because it has been explicitly canceled. Canceling futures is a common operation to avoid wasting resources. For instance, if a user has navigated away from a page which was still loading pictures, there is no point in finishing the download of these pictures, decoding them from raw bytes, and displaying them on a view that is no longer on screen. Cancellation is not only about ignoring a future's result, but actually stopping whatever operation was still ongoing. One may be tempted to use a method such as `Thread::stop()` in Java, but this method is obsolete for a good reason: forceful cancellation is dangerous. The thread could for instance be holding a lock when it is forcefully stopped, preventing any other thread from ever entering the lock. (`CompletableFuture` has a `cancel` method with a `mayInterruptIfRunning` parameter, but this parameter only exists because the method implements the more general interface `CompletionStage`; as the documentation explains, the parameter is ignored because forcefully interrupting a computation is not a good idea in general) Instead, cancellation should be _cooperative_: the operation you want to cancel must be aware that cancellation is a possibility, and provide a way to cancel at well-defined points in the operation. Some frameworks have built-in support for cancellation, but in Java you have to do it yourself. One way to do it is to pass around an `AtomicBoolean` value, which serves as a "box" to pass by reference a flag indicating whether a future should be canceled. Because this is shared state, you must be disciplined in its use: only write to it outside of the future, and only read from it inside of the future. The computation in the future should periodically check whether it should be canceled, and if so throw a cancellation exception instead of continuing: ```java for (int step = 0; step < 100; step++) { if (cancelFlag.get()) { throw new CancellationException(); } ... } ``` ### Progress If you've implemented cancellation and let your users cancel ongoing tasks, they might ask themselves "should I cancel this or not?" after a task has been running for a while. Indeed, if a task has been running for 10 minutes, one may want to cancel it if it's only 10% done, whereas if it's 97% done it's probably be better to wait. This is where _progress_ indication comes in. You can indicate progress in units that make sense for a given operation, such as "files copied", "bytes downloaded", or "emails sent". Some frameworks have built-in support for progress, but in Java you have to do it yourself. One way to do it is to pass around an `AtomicInteger` value, which serves as a "box" to pass by reference a counter indicating the progress of the operation relative to some maximum. Again, because this is shared state, you must be disciplined in its use, this time the other way around: only read from it outside of the future, and only write to it from inside of the future. The computation in the future should periodically update the progress: ```java for (int step = 0; step < 100; step++) { progress.set(step); ... } progress.set(100); ``` It is tempting to define progress in terms of time, such as "2 minutes remaining". However, in practice, the duration of most operations cannot be easily predicted. The first 10 parts of a 100-part operation might take 10 seconds, and then the 11th takes 20 seconds on its own; how long will the remaining 89 take? Nobody knows. This leads to poor estimates. One way to show something to users without committing to an actual estimate is to use an "indeterminate" progress bar, such as a bar that continuously moves from left to right. This lets users know something is happening, meaning the app has not crashed, and is typically enough if the operation is expected to be short so users won't get frustrated waiting. --- #### Exercise Take a look at the three methods in [`Advanced.java`](exercises/lecture/src/main/java/Advanced.java), and complete them one by one, based on the knowledge you've just acquired. Again, you can run `App.java` to see if you got it right. <details> <summary>Suggested solution (click to expand)</summary> <p> - `Server.uploadBatch` should be modified to support cancellation as indicated above, and then used in a way that sets the cancel flag if the operation times out using `orTimeout` - Converting `OldServer.download` can be done by creating a `CompletableFuture<String>` and passing its `complete` and `completeExceptionally` methods as callbacks - Reliable downloads can be implemented in the equivalent of a recursive function: `download` composed with `reliableDownload` if it fails, using `exceptionallyCompose` We provide a [solution example](exercises/solutions/lecture/src/main/java/Advanced.java). </p> </details> --- ### In other languages We have seen futures in Java as `CompletableFuture`, but other languages have roughly the same concept with different names such as `Promise` in JavaScript, `Task<T>` in C#, and `Future` in Rust. Importantly, operations on these types don't always have the exact same semantics, so be sure to read their documentation before using them. Some languages have built-in support for asynchronous operations. Consider the following C# code: ```csharp Task<string> GetAsync(string url); async Task WriteAsync() { var text = await GetAsync("epfl.ch"); Console.WriteLine(text); } ``` `Task<T>` is C#'s future equivalent, so `GetAsync` is an asynchronous operation that takes in a string and returns a string. `WriteAsync` is marked `async`, which means it is an asynchronous operation. When it calls `GetAsync`, it does so with the `await` operator, which is a way to compose futures while writing code that looks and feels synchronous. To be clear, `WriteAsync` is an asynchronous operation and does not block. It is equivalent to explicitly returning `GetAsync("epfl.ch")` composed with `Console.WriteLine`, C#'s equivalent of `System.out.println`. But because the language supports it, the compiler does all of the future composition, an engineer can write straightforward asynchronous code without having to explicitly reason about future composition. It is still possible to explicitly compose futures, such as with `Task.WhenAll` to compose many futures into one. Handling failures is also easier: ```csharp try { var text = await GetAsync("epfl.ch"); Console.WriteLine(text); } catch (Exception) { ... } ``` Whether `GetAsync` fails synchronously or asynchronously, the handling is in the `catch` block, and the compiler takes care of transforming this code into code that composes futures in the expected way. Similarly, Kotlin uses "coroutines", a form of lightweight threads, which can be suspended by `suspend` functions: ```kotlin suspend fun getAsync(url: String): String suspend fun writeAsync() { val content = getAsync("epfl.ch") println(content) } ``` Once again, this code is fully asynchronous: when `writeAsync` calls `getAsync`, it can get _suspended_, and the language runtime will then schedule another coroutine that is ready to run, such as one that updates the user interface with a progress bar. Kotlin can also handle both kinds of failures with a `catch` block. ### Futures as functions Now that we've seen different kinds of futures, let's take a step back and think of what a future is at a high level. There are two fundamental operations for futures: (1) turning a value, or an error, to a future; and (2) combining a future with a function handling its result into a new future. The first operation, creation, is two separate methods in Java's `CompletableFuture`: `completedFuture` and `failedFuture`. The second operation, transformation, is the `thenCompose` method in Java, which takes a future and a function from the result to another future and returns the aggregate future. You may have already seen this pattern before. Consider Java's `Optional<T>`. One can create a full or empty optional with the `of` and `empty` methods, and transform it with the `flatMap` method. In the general case, there are two operations on a "value of T" type: create a `Value<T>` from a `T`, and map a `Value<T>` with a `T -> Value<U>` function to a `Value<U>`. Mathematically-inclined folks use different names for these. "Create" is called "Return", "Map" is called "Bind", and the type is called a _monad_. What's the use of knowing about monads? You can think of monads as a kind of design pattern, a "shape" for abstractions. If you need to represent some kind of "box" that can contain values, such as an optional, a future, or a lists, you already know many useful methods you should provide: the ones you can find on optionals, futures, and lists. Consider the following example from the exercises: ```java return Weather.today() .thenApply(w -> "Today: " + w) .acceptEither( Weather.yesterday() .thenApply(w->"Yesterday: " + w), System.out::println ); ``` You know this code operates on futures because you've worked with the codebase and you know what `Weather.today()` and `Weather.yesterday()` return. But what if this was a different codebase, one where these methods return optionals instead? The code still makes sense: if there is a weather for today, transform it and print it, otherwise get the weather for yesterday, transform it and print it. Or maybe they return lists? Transform all elements of today's prediction, and if there are none, use the elements of yesterday's predictions instead, transformed; then print all these elements. ## How should we test async code? Consider the following method: ```java void printWeather() { getString(...) .thenApply(parseWeather) .thenAccept(System.out::println); } ``` How would you test it? The problem is that immediately after calling the method, the `getString` future may not have finished yet, so one cannot test its side effect yet. It might even never finish if there is an infinite loop in the code, or if it expects a response from a server that is down. One commonly used option is to sleep via, e.g., `Thread.sleep`, and then assume that the operation must have finished. **Never, ever, ever, ever sleep in tests for async code**. It slows tests down immensely since one must sleep the whole duration regardless of how long the operation actually takes, it is brittle since a future version of the code may be slower, and most importantly it's unreliable since the code could sometimes take more time due to factors out of your control, such as continuous integration having fewer resources because many pull requests are open and being tested. The fundamental problem with the method above is its return value, or rather the lack of a return value. Tests cannot access the future, they cannot even name it, because the method does not expose it. To be testable, the method must be refactored to expose the future: ```java CompletableFuture<Void> printWeather() { return getString(...) .thenApply(parseWeather) .thenAccept(System.out::println); } ``` It is now possible to test the method using the future it returns. One option to do so is this: ```java printWeather().thenApply(r -> { // ... test? ... }); ``` However, this is a bad idea because the lambda will not run if the future fails or if it never finishes, so the test will pass even though the future has not succeeded. In fact, the test does not even wait for the future to finish, so the test may pass even if the result is wrong because the lambda will execute too late! To avoid these problems, one could write this instead: ```java printAnswer().join(); // ... test ... ``` But this leaves one problem: if the code is buggy and the future never completes, `join()` will block forever and the tests will never complete. To avoid this problem, one can use the timeout method we saw earlier: ```java printWeather() .orTimeout(5, TimeUnit.SECONDS) .join(); // ... test ... ``` There is of course still the issue unrelated to asynchrony that the method has an implicit dependency on the standard output stream, which makes testing difficult. You can remove this dependency by returning the `CompletableFuture<String>` directly instead of printing it, which makes tests much simpler: ```java String weather = getWeather() .orTimeout(5, TimeUnit.SECONDS) .join(); // ... test weather ... ``` Exposing the underlying future is the ideal way to test asynchronous operations. However, this is not always feasible. Consider an app for which we want to test a button click "end-to-end", i.e., by making a fake button click and testing the resulting changes in the user interface. The button click handler must typically have a specific interface, including a `void` return type: ```java @Override void onClick(View v) { ... } ``` One cannot return the future here, since the `void` return type is required to comply with the button click handler interface. Instead, one can add an explicit callback for tests: ```java @Override void onClick(View v) { // ... callback.run(); } public void setCallback(...) { ... } ``` Tests can then set a callback and proceed as usual: ```java setCallback(() -> { // ... can we test here? }); // ... click the button ... ``` However, this now raises another problem: how to properly test callback-based methods? One way would be to use low-level classes such as latches or barriers to wait for the callback to fire. But this is a reimplementation of the low-level code the authors of `CompletableFuture` have already written for us, so we should be reusing that instead! ```java var future = new CompletableFuture<Void>(); setCallback(() -> future.complete(null)); // ... click the button ... future.orTimeout(5, TimeUnit.SECONDS) .join(); ``` We have reduced the problem of testing callbacks to a known one, testing futures, which can then be handled as usual. --- #### Exercise Take a look at the three tests in [`WeatherTests.java`](exercises/lecture/src/test/java/WeatherTests.java), and complete them one by one, based on the knowledge you've just acquired. <details> <summary>Suggested solution (click to expand)</summary> <p> - As we did above, call `orTimeout(...)` then `join()` on `Weather.today()`, then assert that its result is `"Sunny"` - Create a `CompletableFuture<Void>`, call its `complete` method in the callback of `WeatherView`, then wait for it with a timeout after executing `WeatherView.clickButton()`, and test the value of `WeatherView.weather()` - There are multiple ways to do the last exercise; one way is to return the combination of the two futures with `allOf` in `printWeather`, and replace `System.out::println` with a `Consumer<String>` parameter, then test it with a consumer that adds values to a string; another would be a more thorough refactoring of `printWeather` that directly returns a `CompletableFuture<List<String>>` We provide a [solution example](exercises/solutions/lecture/src/test/java/WeatherTests.java). </p> </details> --- ## How does asynchrony interact with software design? Which operations should be sync and which should be async, and why? This is a question you will encounter over and over again when engineering software. One naïve option is to make everything asynchronous. Even `1 + 1` could be `addAsync(1, 1)`! This is clearly going too far. It's important to remember that _asynchrony is viral_: if a method is async, then the methods that call it must also be async, though it can itself call sync methods. A sync method that calls an async method is poor design outside of the very edges of your system, typically tests and the main method, because it will need to block until the async method is done, which can introduce all kinds of issues such as UI freezes or deadlocks. This also applies to inheritance: if a method might be implemented in an asynchronous way, but also has other synchronous implementations, it must be async. For instance, while fetching the picture for an album in a music player may be done from a local cache in a synchronous way, it will also sometimes be done by downloading the image from the Internet. Thus, you should make operations async if they are expected to be implemented in an asynchronous way, typically I/O operations. One policy example is the one in the [Windows Runtime APIs](https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/concurrency#asynchronous-operations-and-windows-runtime-async-functions), which Microsoft introduced with Windows 8. Any operation that has the potential to take more than 50 milliseconds to complete returns a future instead of a synchronous result. 50ms may not be the optimal threshold for everything, but it is a reasonable and clear position to take that enables engineers to decide whether any given operation should be asynchronous. Remember the "YAGNI" principle: "_You Aren't Gonna Need It". Don't make operations async because they might perhaps one day possibly maybe need to be async. Only do so if there is a clear reason to. Think of how painful, or painless, it would be to change from sync to async if you need it later. One important principle is to be consistent. Perhaps you are using an OS that gives you asynchronous primitives for reading and writing to files, but only a synchronous primitive to delete it. You could expose an interface like this: ```java class File { CompletableFuture<String> read(); CompletableFuture<Void> write(String text); void delete(); } ``` However, this is inconsistent and surprising to developers using the interface. Instead, make everything async, even if deletion has to be implemented by returning an already-completed future after synchronously deleting the file: ```java class File { CompletableFuture<String> read(); CompletableFuture<Void> write(String text); CompletableFuture<Void> delete(); } ``` This offers a predictable and clear experience to developers using the interface. What if you need to asynchronously return a sequence of results? For instance, what should the return type of a `downloadImagesAsync` method be? It could be `CompletableFuture<List<Image>>`, if you want to batch the results. Or it could be `List<CompletableFuture<Image>>`, if you want to parallelize the downloads. But if you'd like to return "a sequence of asynchronous operations", what should you return? Enter "reactive" programming, in which you react to events such as downloads, clicks, or requests, each of which is an asynchronous event. For instance, if you have a "flow" of requests, you could `map` it to a flow of users and their data, then `filter` it to remove requests from users without the proper access right, and so on. In other words, it's a monad! Thus, you already mostly know what operations exist and how to use it. Check out [ReactiveX.io](https://reactivex.io) if you're interested, with libraries such as [RxJava](https://github.com/ReactiveX/RxJava). ## Summary In this lecture, you learned: - Asynchrony: what it is, how to use it, and when to use it - Maintainable async code by creating and combining futures - Testable async code with reliable and useful tests You can now check out the [exercises](exercises/)!
CS-305: Software engineering
# Infrastructure > **Prerequisites**: Before following this lecture, you should: > - Install Git. On Windows, use [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) as Git is designed mostly for Linux. > On macOS, see [the git documentation](https://git-scm.com/download/mac). On Linux, Git may already be installed, or use your distribution's package manager. > If you have successfully installed Git, running `git --version` in the command line should show a version number. > - Create a GitHub account (you do not have to use an existing GitHub account, you can create one just for this course if you wish) > - Set up an SSH key for GitHub by following [their documentation](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account) > - Tell Git who you are by running `git config --global user.name 'your_name'` with your name and `git config --global user.email 'your_email'` with the e-mail you used for GitHub > - Choose an editor Git will open to write a summary of your changes with `git config --global core.editor 'your_editor'`, since Git defaults to `vi` which is hard to use for newcomers. > On Windows with WSL you can use `notepad.exe`, which will open Windows's Notepad. > On macOS you can use `open -e -W -n` which will open a new TextEdit window. > On Linux you can use your distribution's built-in graphical text editor, or `nano`. > > If you use Windows with WSL, note that running `explorer.exe .` from the Linux command line will open Windows's Explorer in the folder your command-line is, which is convenient. > > Optionally, you may want to set the Git config setting `core.autocrlf` to `true` on Windows and `input` on Linux and macOS, > so that Git converts between Unix-style line endings (`\n`) and Windows-style line separators (`\r\n`) automatically. Where do you store your code, and how do you make changes to it? If you're writing software on your own, this is not a problem, as you can use your own machine and change whichever files you want whenever you want. But if you're working with someone else, it starts being problematic. You could use an online cloud service where you store files, and coordinate who changes which file and when. You could email each other changes to sets of files. But this does not work so well when you have more people, and it is completely unusable when you have tens or hundreds of people working on the same codebase. This is where infrastructure comes in. ## Objectives - Contrast old and new _version control_ systems - Organize your code with the _Git_ version control system - Write useful descriptions of code changes - Avoid mistakes with _continuous integration_ ## What is version control? Before we talk about how to manage your code using a version control system, we must define some terms. A _repository_ is a location in which you store a codebase, such as a folder on a remote server. When you make a set of changes to a repository, you are _pushing_ changes. When you retrieve the changes that others have made from the repository, you are _pulling_ changes. A set of changes is called a _commit_. Commits have four main components: who, what, when, and why. "Who" is the author of the commit, the person who made the changes. "What" is the contents of the commit, the changes themselves. "When" is the date and time at which the commit was made. This can be earlier than when the commit was actually pushed to a repository. "Why" is a message associated with the commit that explains why the changes were made, such as detailing why there was a bug and why the new code fixes the bug. The "why" is particularly important because you will often have to look at old changes later and understand why they were made. Sometimes, a commit causes problems. Perhaps a commit that was supposed to improve performance also introduces a bug. Version control systems allow you to _revert_ this commit, which creates a new commit whose contents are the reverse of the original one. That is, if the original commit replaced "X" by "Y", then the revert commit replaces "Y" with "X". Importantly, the original commit is not lost or destroyed, instead a new revert commit is created. Commits are put together in a _history_ of changes. Initially, a repository is empty. Then someone adds some content in a commit, then more content in another commit, and so on. The history of a repository thus contains all the changes necessary to go from nothing to the current state. Some of these changes could be going back and forth, such as revert commits, or commits that replace code that some previous commit added. At any time, any developer with access to the repository can look at the entire history to see who made what changes when and why. _1st generation_ version control systems were essentially a layer of automation on manual versioning. As we mentioned earlier, if you are developing with someone else, you might put your files somewhere and coordinate who is changing what and when. A 1st generation system helps you do that with fewer mistakes, but still fundamentally uses the same model. With 1st generation version control, if Alice wants to work on file A, she "checks out" the file. At that point, the file is locked: Alice can change it, but nobody else can. If Bob wants to also check out file A, the system will reject his attempt. Bob can, however, check out file B if nobody else is using it. Once Alice is done with her work, she creates a commit with her changes, and releases the lock. At that point, Bob can check out file A and make his changes. 1st generation version control systems thus act as locks at the granularity of files. They prevent developers from making parallel changes to the same file, which prevents some mistakes but isn't very convenient. For instance, Alice might want to modify function X in file A, while Bob wants to modify function Y in file A. These changes won't conflict, but they still cannot do them in parallel, because locks in 1st generation version control are at the file granularity. Developers moved on from 1st generation systems because they wanted more control over _conflicts_. When two developers want to work on the same file at the same time, they should be able to, as long as they can then _merge_ their changes into one unified version. Merging changes isn't always possible automatically. If two developers changed the same function in different ways, for instance, they probably need to have a chat to decide which changes should be kept. Another feature that makes sense if a system can handle conflicts and merges is _branches_. Sometimes, developers want to work on multiple copies of the codebase in parallel. For instance, you might be working on some changes that improve performance, when a customer comes in with a bug report. You could fix the bug and commit it with your performance changes, but the resulting commit is not convenient. If you later need to revert the performance changes, for instance, you would also revert the bugfix because it's in the same commit. Instead, you create a branch for your performance changes, then you switch to a branch for the bugfix, and you can work on both in parallel. When your bugfix is ready, you can _merge_ it into the "main" branch of the repository, and the same goes for the performance changes. One common use of branches is for versions: you can release version 1.0 of your software, for instance, and create a branch representing the state of the repository for that version. You can then work on the future version 2.0 in the "main" branch. If a customer reports a bug in version 1.0, you can switch to the branch for version 1.0, fix the bug, release the fix, then go back to working on version 2.0. Your changes for version 1.0 did not affect your main branch, because you made them in another branch. The typical workflow with branches for modern software is that you will create a branch starting from the main branch of the repository, then add some commits to the branch to fix a bug or add a feature or perform whatever task the branch is for, and then ask a colleague to review it. If the colleague asks for some changes, such as adding more code comments, you can add a commit to the branch with these changes. Once your colleague is happy, you can merge the branch's commits into the main branch. Then you can create another branch to work on something else, and so on. Your colleagues are themselves also working on their own branches. This workflow means everyone can push whatever commits they want on their branch without conflicting with others, even if their work isn't quite finished yet. Often it is a good idea to _squash_ a branch's commits into a single commit and merge the resulting commit into the main branch. This combines all of the branch's changes into one clean commit in the history of the main branch, rather than having a bunch of commits that do a few small changes each but make no sense without each other. In the case of branches that represent versions, one sometimes needs to apply the same changes to multiple branches. For instance, while developing version 2.0 in the main branch, you may find a bug, and realize that the bug also exists in version 1.0. You can make a commit fixing the bug in version 2.0, and then _cherry pick_ the commit into the branch for version 1.0. As long as the change does not conflict with other changes made in the version 1.0 branch, the version control system can copy your bugfix commit into a commit for another branch. _2nd generation_ version control systems were all about enabling developers to handle conflicts. Alice can work on file A without the need to lock it, and Bob can also work on file A at the same time. If Alice pushes her changes first, the system will accept them, and when Bob then wants to apply his changes, two things can happen. One possibility is that the changes can be merged automatically, for instance because the changes are on two different parts of the file. The other possibility is that the changes conflict and must be merged manually. Bob then has to choose what to do, perhaps by asking Alice, and produce one "merged" version of the file that can be pushed. The main remaining disadvantage of 2nd generation version control is its centralization. There is one repository that developers work with, hosted on one server. Committing changes requires an Internet connection to that server. This is a problem if the server is down, or a developer is in a place without access to the Internet, or any other issue that prevents a developer from reaching the server. _3rd generation_ version control systems are all about decentralization. Every machine has its own repository. It is not a "backup" or a "replica" of some "main" repository, but just another clone of the repository. Developers can make commits locally on their own repository, then push these commits to other clones of the repository, such as on a server. Developers can also have multiple branches locally, with different commits in each, and push some or all of these branches to other clones of the repository. This all works as long as the repositories have compatible histories. That is, one cannot push a change to a repository that isn't based on the same history as one's local repository. In practice, teams typically agree on one "main" repository that they will all push commits to, and work locally on their clone of that repository. While from the version control system's point of view all repository clones are equal, it is convenient for developers to agree on one place where everyone puts their changes. The main version control system in use today is _Git_. Git was invented by Linus Torvalds, who invented Linux, because he was tired of the problems with the previous version control system he used for Linux. There are also other 3rd generation version control systems such as Mercurial and Bazaar, but Git is by far the most used. Many developers use public websites to host the "main" repository clone of their projects. The most famous these days is GitHub, which uses Git but isn't technically related to it. GitHub not only stores a repository clone, but can also host a list of "issues" for the repository, such as bugs and feature requests, as well as other data such as a wiki for documentation. There are also other websites with similar features such as GitLab and BitBucket, though they are not as popular. An example of a project developed on GitHub is [the .NET Runtime](https://github.com/dotnet/runtime), which is developed mainly by Microsoft employees and entirely using GitHub. Conversations about bugs, feature requests, and code reviews happen in the open, on GitHub. ## How does one use Git? Now that we've seen the theory, let's do some practice! You will create a repository, make some changes, and publish it online. Then we'll see how to contribute to an existing online repository. Git has a few basic everyday commands that we will see now, and many advanced commands we won't discuss here. You can always look up commands on the Internet, both basic and advanced ones. You will eventually remember the basics after using them enough, but there is no shame at all in looking up what to do. We will use Git on the command line for this tutorial, since it works the same everywhere. However, for everyday tasks you may prefer using graphical user interfaces such as [GitKraken](https://www.gitkraken.com/), [GitHub Desktop](https://desktop.github.com/), or the Git support in your favorite IDE. Start by creating a folder and _initializing_ a repository in that folder: ```sh ~$ mkdir example ~$ cd example ~/example$ git init ``` Git will tell you that you have initialized an empty Git repository in `~/example/.git/`. This `.git/` folder is a special folder Git uses to store metadata. It is not part of the repository itself, even though it is in the repository folder. Let's create a file: ```sh $ echo 'Hello' > hello.txt" ``` We can now ask Git what it thinks is going on: ```sh $ git status ... Untracked files: hello.txt ``` Git tells us that it sees we added `hello.txt`, but this file isn't tracked yet. That is, Git won't include it in a commit unless we explicitly ask for it. So let's do exactly that: ```sh $ git add -A ``` This command asks Git to include all current changes in the repository for the next commit. If we make more changes, we will have to ask for these new changes to be tracked as well. But for now, let's ask Git what it thinks: ```sh $ git status ... Changes to be committed: new file: hello.txt ``` Now Git knows we want to commit that file. So let's commit it: ```sh $ git commit ``` This will open a text editor for you to type the commit message in. As we saw earlier, the commit message should be a description of _why_ the changes were made. Often the very first commit in a repository sets up the basic file structure as an initial commit, so you could write `Initial commit setting up the file` or something similar. You will then see output like this: ```sh [...] Initial commit. 1 file changed, 1 insertion(+) create mode 100644 hello.txt ``` Git repeats the commit message you put, here `Initial commit.`, and then tells you what changes happened. Don't worry about that `mode 100644`, it's more of an implementation detail. Let's now make a change by adding one line: ```sh $ echo 'Goodbye' >> hello.txt ``` We can ask git for the details of what changes we did: ```sh $ git diff ``` This will show a detailed list of the differences between the state of the repository as of the latest commit and the current state of the repository, i.e., we added one line saying `Goodbye`. Let's track the changes we just made: ```sh $ git add -A ``` What happens if we ask for a list of differences again? ```sh $ git diff ``` ...Nothing! Why? Because `diff` by default shows differences that are not tracked for the next commit. There are three states for changes to files in Git: modified, staged, and committed. By default changes are modified, then with `git add -A` they are staged, and with `git commit` they are committed. We have been using `-A` with `git add` to mean "all changes", but we could in fact add only specific changes, such as specific files or even parts of files. In order to see staged changes, we have to ask for them: ```sh $ git diff --staged ``` We can now commit our changes. Because this is a small commit that does not need much explanation, we can use `-m` to write the commit message directly in the command: ```sh $ git commit -m 'Say goodbye' ``` Let's now try out branches, by creating a branch and switching to it: ```sh git switch -c feature/today ``` The slash in the branch name is nothing special to Git, it's only a common naming convention to distinguish the purpose of different branches. For instance, you might have branches named `feature/delete-favorites` or `bugfix/long-user-names`. But you could also name your branch `delete-favorites` or `bugfix/long/user/names` if you'd like, as long as everybody using the repository agrees on a convention for names. Now make a change to the single line in the file, such as changing "Hello" to "Hello today". Then, track the changes and commit them: ```sh $ git add -A && git commit -m 'Add time' ``` You will notice that Git tells you there is `1 insertion(+), 1 deletion (-)`. This is a bit odd, we changed one line, why are there two changes? The reason is that Git tracks changes at the granularity of lines. When you edit a line, Git sees this as "you deleted the line that was there, and you added a new line". The fact that the "deleted" and the "added" lines are similar is not relevant. If you've already used Git before, you may have heard of the `-a` to `git commit`, which could replace the explicit `git add -A` in our case. The reason we aren't using it here, and the reason why you should be careful if using it, is that `-a` only adds changes to existing files. It does not add changes to new files or deleted files. This makes it very easy to accidentally forget to include some new or deleted files in the commit, and to then have to make another commit with just these files, which is annoying. Anyway, we've made a commit on our `feature/today` branch. In case we want to make sure that we are indeed on this branch, we can ask Git: ```sh $ git branch ``` This will output a list of branches, with an asterisk `*` next to the one we are on. Let's now switch to our main branch. Depending on your Git version, this branch might have different names, so look at the output of the previous command and use the right one, such as `master` or `main`: ```sh $ git switch main ``` To see what happens when two commits conflict, let's make a change to our `hello.txt` file that conflicts with the other branch we just made. For instance, replace "Hello" with "Hello everyone". Then, track the change and commit it as before. At this point, we have two branches, our main branch and `feature/today`, that have diverged: they both have one commit that is not in the other. Let's ask Git to merge the branches, that is, add the commits from the branch we specify into the current branch: ```sh $ git merge feature/today ``` Git will optimistically start with `Auto-merging hello.txt`, but this will soon fail with a `Merge conflict in hello.txt`. Git will ask us to fix conflicts and commit the result manually. What does `hello.txt` look like now? ```sh $ cat hello.txt <<<<<<< HEAD Hello everyone ======= Hello today >>>>>>> feature/today Goodbye ``` Let's take a moment to understand this. The last line hasn't changed, because it's not a part of the conflict. The first line has been expanded to include both versions: between the `<<<` and `===` is the version in `HEAD`, that is, the "head", the latest commit, in the current branch. Indeed, on our main branch the first line was `Hello everyone`. Between the `===` and the `>>>` is the version in `feature/today`. What we need to do is manually merge the changes, i.e., edit the file to replace the conflict including the `<<<`, `===`, and `>>>` lines with the merged changes we want. For instance, we could end up with a file containing the following: ```sh $ cat hello.txt Hello everyone today Goodbye ``` This is one way to merge the file. We could also have chosen `Hello today everyone`, or perhaps we would rather discard one of the two changes and keep `Hello everyone` or `Hello today`. Or perhaps we want yet another change, we could have `Hello hello` instead. Git does not care, it only wants us to decide what the merged version should be. Once we have made our merge changes, we should add the changes and commit as before: ```sh $ git add -A && git commit -m 'Merge' ``` Great. Wait, no, actually, not so great. That's a pretty terrible commit message. It's way too short and not descriptive. Thankfully, _because we have not published our changes to another clone of the repository yet_, we can make changes to our commits! This is just like how a falling tree makes no sound if there's no one around to hear it. If nobody can tell, it did not happen. We can change our commit now, and when we push it to another clone the clone will only see our modified commit. However, if we had already pushed our commit to a clone, our commit would be visible, so we could not change it any more as the clone would get confused by a changing commit since commits are supposed to be immutable. To change our commit, which again should only be done if the commit hasn't been pushed yet, we "amend" it: ```sh $ git commit --amend -m 'Merge the feature/today branch' ``` We have only modified the commit message here, but we could also modify the commit contents, i.e., the changes themselves. Sometimes we make changes we don't actually want, for instance temporary changes while we debug some code. Let's make a "bad" change: ```sh $ echo 'asdf' >> hello.txt ``` We can restore the file to its state as of the latest commit to cancel this change: ```sh $ git restore hello.txt ``` Done! Our temporary changes have disappeared. You can also use `.` to restore all files in the current directory, or any other path. However, keep in mind that "disappeared" really means disappeared. It's as if we never changed the file, as the file is now in the state it was after the latest commit. Do not use `git restore` unless you actually want to lose your changes. Sometimes we accidentally add files we don't want. Perhaps a script went haywire, or perhaps we copied some files by accident. Let's make a "bad" new file: ```sh $ echo 'asdf' > mistake.txt ``` We can ask Git to "clean" the repository, which means removing all untracked files and directories. However, because this will delete files, we'd better first run it in "dry run" mode using `-n`: ```sh $ git clean -fdn ``` This will show a list of files that _would_ be deleted if we didn't include `-n`. If we're okay with the proposed deletion, let's do it: ```sh $ git clean -fd ``` Now our `mistake.txt` is gone. Finally, before we move on to GitHub, one more thing: keep in mind that Git only tracks _files_, not _folders_. Git will only keep track of folders if they are a part of a file's path. So if we create a folder and ask Git what it sees, it will tell us there is nothing, because the folder is empty: ```sh $ mkdir folder $ git status ``` If you need to include an "empty" folder in a Git repository for some reason, you should add some empty file in it so that Git can track the folder as part of that file. Let's now publish our repository. Go to [GitHub](https://github.com) and create a repository using the "New" button on the home page. You can make it public or private, but do not create files such as "read me" files or anything else, just an empty repository. Then, follow the GitHub instructions for an existing repository from the command line. Copy and paste the commands GitHub gives you. These commands will add the newly-created GitHub repository as a "remote" to your local repository, which is to say, another clone of the repository that Git knows about. Since it will be the only remote, it will also be the default one. The default remote is traditionally named `origin`. The commands GitHub provide will also push your commits to this remote. Once you've executed the commands, you can refresh the page on your GitHub repository and see your files. Now make a change to your `hello.txt`, track the change, and commit it. You can then sync the commit with the GitHub repository clone: ```sh $ git push ``` You can also get commits from GitHub: ```sh $ git pull ``` Pulling will do nothing in this case, since nobody else is using the repository. In a real-world scenarios, other developers would also have a clone of the repository on their machine and use GitHub as their default remote. They would push their changes, and you would pull them. Importantly, `git pull` only synchronizes the current branch. If you would like to sync commits from another branch, you must `git switch` to that branch first. Similarly, `git push` only synchronizes the current branch, and if you create a new branch you must tell it where to push with `-u` by passing both the remote name and the branch name: ```sh $ git switch -c example $ git push -u origin example ``` Publishing your repository online is great, but sometimes there are files you don't want to publish. For instance, the binary files compiled from source code in the repository probably should not be in the repository, since they can be recreated easily and would only take up space. Files that contain sensitive data such as passwords should also not be in the repository, especially if it's public. Let's simulate a sensitive file: ```sh $ echo '1234' > password.txt ``` We can tell Git to pretend this file doesn't exist by adding a line with its name to a special file called `.gitignore`: ```sh $ echo 'password.txt' >> .gitignore ``` Now, if you try `git status`, it will tell you that `.gitignore` was created but ignore `password.txt` since you told Git to ignore it. You can also ignore entire directories. Note that this only works for files that haven't been committed to the repository yet. If you had already made a commit in which `password.txt` exists, adding its name to `.gitignore` will only ignore future changes, not past ones. If you accidentally push to a public repository a commit with a file that contains a password, you should assume that the password is compromised and immediately change it. There are bots that scan GitHub looking for passwords that have been accidentally committed, and they will find your password if you leave it out there, even for a few seconds. Now that you have seen the basics of Git, time to contribute to an existing project! You will do this through a _pull request_, which is a request that the maintainers of an existing project pull your changes into their project. This is a GitHub concept, as from Git's perspective it's merely syncing changes between clones of a repository. Go to <https://github.com/sweng-example/hello> and click on the "Fork" button. A _fork_ is a clone of the repository under your own GitHub username, which you need here because you do not have write access to `sweng-example/hello` so you cannot push changes to it. Instead, you will push changes to your fork, to which you have write access, and then ask the maintainers of `sweng-example/hello` to accept the change. You can create branches within a fork as well, as a fork is just another clone of the repository. Typically, if you are a collaborator of a project, you will use a branch in the project's main repository, while if you are an outsider wanting to propose a change, you will create a fork first. Now that you have a forked version of the project on GitHub, click on the "Code" button and copy the SSH URL, which should start with `git@github.com:`. Then, ask Git to make a local clone of your fork, though you should go back to your home directory first, since creating a repository within a repository causes issues: ```sh $ cd ~ $ git clone git@github.com:... ``` Git will clone your fork locally, at which point you can make a change, commit, and push to your fork. Once that's done, if you go to your fork on GitHub, there should be a banner above the code telling you that the branch in your fork is 1 commit ahead of the main branch in the original repository. Click on the "Contribute" button and the "Open pull request" button that shows up, then confirm that you want to open a pull request, and write a description for it. Congratulations, you've made your first contribution to an open source project! The best way to get used to Git is to use it a lot. Use Git even for your own projects, even if you do not plan on using branches. You can use private repositories on GitHub as backups, so that even if your laptop crashes you will not lose your code. There are many advanced features in Git that can be useful in some cases, such as `bisect`, `blame`, `cherry-pick`, `stash`, and many more. Read the [official documentation](https://git-scm.com/docs/) or find online advanced tutorials for more if you're curious! ## How does one write good commit messages? Imagine being an archaeologist and having to figure out what happened in the past purely based on some half-erased drawings, some fossils, and some tracks. You will eventually figure out something that could've happened to cause all this, but it will take time and you won't know if your guess is correct. Wouldn't it be nice if there was instead a journal that someone made, describing everything important they did and why they did it? This is what commit messages are for: keep track of what you do and why you did it, so that other people will know it even after you're done. Commit messages are useful to people who will review your code before approving it for merging in the main branch, and to your colleagues who investigate bugs months after the code was written. Your colleagues in this context include "future you". No matter how "obvious" or "clear" the changes seems to you when you make them, a few months later you won't remember why you did something the way you did it. The typical format of a commit message is a one-line summary followed by a blank line and then as many lines as needed for details. For instance, this is a good commit message: ``` Fix adding favorites on small phones The favorites screen had too many buttons stacked on the same row. On phones with small screens, there wasn't enough space to show them all, and the "add" button was out of view. This change adds logic to use multiple rows of buttons if necessary. ``` As we saw earlier, "squashing" commits is an option when merging your code into the main branch, so not all commits on a branch need to have such detailed messages. Sometimes a commit is just "Fix a typo" or "Add a comment per the review feedback". These commits aren't important to understand the changes, so their messages will be dropped once the branch is squashed into a single commit while being merged. The one-line summary is useful to get an overview of the history without having to see every detail. You can see it on online repositories such as GitHub, but also locally. Git has a `log` command to show the history, and `git log --oneline` will show only the one-line summary of each commit. A good summary should be short and in the imperative mood. For instance: - "Fix bug #145" - *Add an HD version of the wallpaper" - "Support Unicode 14.0" The details should describe _what_ the changes do and _why_ you did them, but not _how_. There is no point in describing how because the commit message is associated with the commit contents, and those already describe how you changed the code. ## How can we avoid merging buggy code? Merging buggy code to the main branch of a repository is an annoyance for all contributors to that repository. They will have to fix the code before doing the work they actually want to do, and they may not all fix it in the same way, leading to conflicts. Ideally, we would only accept pull requests if the resulting code compiles, is "clean" according to the team's standards, and has been tested. Different teams have different ideas of what "clean" code is, as well as what "testing" means since it could be manual, automated, performed on one or multiple machines, and so on. When working in an IDE, there will typically be menu options to analyze the code for cleanliness, to compile the code, to run the code, and to run automated tests if the developers wrote some. However, not everyone uses the same IDE, which means they may have different definitions of what these operations mean. The main issue with using operations in an IDE to check properties about the code is that humans make mistakes. On a large enough projects, human mistakes happen all the time. For instance, it's unreasonable to expect hundreds of developers to never forget even once to check that the code compiles and runs. Checking for basic mistakes also a poor use of people's time. Reviewing code should be about the logic of the code, not whether every line is syntactically valid, that's the compiler's job. We would instead like to _automate_ the steps we need to check code. This is done using a _build system_, such as CMake for C++, MSBuild for C#, or Gradle for Java. There are many build systems, some of which support multiple languages, but they all fundamentally provide the same feature: build automation. A build system can invoke the compiler on the right files with the right flags to compile the code, invoke the resulting binary to run the code, and even perform more complex operations such as downloading dependencies based on their name if they have not been downloaded already. Build systems are configured with code. They typically have a custom declarative language embedded in some other language such as XML. Here is an example of build code for MSBuild: ```xml <Project Sdk="Microsoft.NET.Sdk"> <ItemGroup> <PackageReference Include="Microsoft.Z3" Version="4.10.2" /> </ItemGroup> </Project> ``` This code tells MSBuild that (1) this is a .NET project, which is the runtime typically associated with C#, and (2) it depends on the library `Microsoft.Z3`, specifically its version `4.10.2`. One can then run MSBuild with this file from the command line, and MSBuild will compile the project after first downloading the library it depends on if it hasn't been downloaded already. In this case, the library name is associated with an actual library by looking up the name on [NuGet](https://www.nuget.org/), the library catalog associated with MSBuild. Build systems remove the dependency on an IDE to build and run code, which means everyone can use the editor they want as long as they use the same build system. Most IDEs can use build system code as the base for their own configuration. For instance, the file above can be used as-is by Visual Studio to configure a project. Build systems enable developers to build, run, and check their code anywhere. But it has to be somewhere, so which machine or machines should they use? Once again, using a developer's specific machine is not a good idea because developers customize their machine according to their personal preferences. The machines developers use may not be representatives of the machines the software will actually run on when used by customers. Just as we defined builds using code through a build system, we can define environments using code! Here is an example of environment definition code for the Docker container system, which you do not need to understand: ``` FROM node:12-alpine RUN apk add python g++ make COPY . . RUN yarn install CMD ["node", "src/index.js"] EXPOSE 3000 ``` This code tells Docker to use the `node:12-alpine` base environment, which has Node.js preinstalled on an Alpine Linux environment. Then, Docker should run `apk add` to install specific packages, including `make`, a build system. Docker should then copy the current directory inside of the container, and run `yarn install` to invoke Node.js's `yarn` build system to pre-install dependencies. The file also tells Docker the command to run when starting this environment and the HTTP port to expose to the outside world. Defining an environment using code enables developers to run and test their code in specific environments that can be customized to match customers' environments. Developers can also define multiple environments, for instance to ensure their software can run on different operating systems, or on operating systems in different languages. We have been using the term "machine" to refer to the environment code runs in, but in practice it's unlikely to be a physical machine as this would be inefficient and costly. Pull requests and pushes happen fairly rarely given that modern computers can do billions of operations per second. Provisioning one machine exclusively for one project would be a waste. Instead, automated builds use _virtual machines_ or _containers_. A virtual machine is a program that emulates an entire machine inside it. For instance, one can run an Ubuntu virtual machine on Windows. From Windows's perspective, the virtual machine is just another program. But for programs running within the virtual machine, it looks like they are running on real hardware. This enables partitioning resources: a single physical machine can run many virtual machines, especially if the virtual machines are not all busy at the same time. It also isolates the programs running inside the virtual machine, meaning that even if they attempt to break the operating system, the world outside of the virtual machine is not affected. However, virtual machines have overhead, especially when running many of them. Even if 100 virtual machines all run the exact same version of Windows, for instance, they must all run an entire separate instance of Windows including the Windows kernel. This is where _containers_ come in. Containers are a lightweight form of virtual machines that share the host operating system's kernel instead of including their own. Thus, there is less duplication of resources, at the cost of less isolation. Typically, services that allow anyone to upload code will use virtual machines to isolate it as much as possible, whereas private services can use containers since they trust the code they run. Using build systems and virtual machines to automatically compile, run, and check code whenever a developer pushes commits is called _continuous integration_, and it is a key technique in modern software development. When a developer opens a pull request, continuous integration can run whatever checks have been configured, such as testing that the code compiles and passes some static analysis. Merging can then be blocked unless continuous integration succeeds. Thus, nobody can accidentally merge broken code into the main branch, and developers who review pull requests don't need to manually check that the code works. Importantly, whether a specific continuous integration run succeeds or fails means that there exists a machine on which the code succeeds or fails. It is possible that code works fine on the machine of the developer who wrote it, yet fails in continuous integration. A common response to this is "but it works on my machine!", but that is irrelevant. The goal of software is not to work on the developer's machine but to work for users. Problems with continuous integration typically stem from differences between developers' machines and the virtual machines configured for continuous integration. For instance, a developer may be testing a phone app on their own phone, with a test case of "open the 'create item' page and click the 'no' button", which they can do fine. But their continuous integration environment may be set up with a phone emulator that has a small screen with few pixels, and the way the app is written means the 'no' button is not visible: <p align="center"><img alt="Illustration of the phones example." src="images/phones.svg" width="50%" /></p> The code thus does not work in the continuous integration environment, not because of a problem with continuous integration, but because the code does not work on some phones. The developer should fix the code so that the "No" button is always visible, perhaps below the "Yes" button with a scroll bar if necessary. --- #### Exercise: Add continuous integration Go back to the GitHub repository you created, and add some continuous integration! GitHub includes a continuous integration service called GitHub Actions, which is free for basic use. Here is a basic file you can use, which should be named `.github/workflows/example.yml`: ```yaml on: push jobs: example: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - run: echo "Hello!" ``` After pushing this file to the GitHub repository and waiting for a few seconds, you should see a yellow circle next to the commit indicating GitHub Actions is running, which you can also see in the "Actions" tab of the repository. This is a very basic action that only clones the repository and prints text. In a real-world scenario, you would at least invoke a build system. GitHub Actions is quite powerful, as you can read on [the GitHub Actions documentation](https://docs.github.com/en/actions). --- Version control, continuous integration, and other such tasks were typically called "operations", and were done by a separate team from the "development" team. However, nowadays, these concepts have combined into "DevOps", in which the same team does both, which makes it easier for developers to configure exactly the operations they want. ## Summary In this lecture, you learned: - Version control systems, and the differences between 1st, 2nd, and 3rd generation - Git: how to use it for basic scenarios, and how to write good commit messages - Continuous integration: build systems, virtual machines, and containers You can now check out the [exercises](exercises/)!
CS-305: Software engineering
"# Design\n\nImagine if, in order to display \"Hello, World!\" on a screen, you had to learn how eve(...TRUNCATED)
CS-305: Software engineering
"# Design Patterns\n\nThis document contains a curated list of common design patterns, including con(...TRUNCATED)
CS-305: Software engineering
"# Teamwork\n\nWorking on your own typically means engineering a small application, such as a calcul(...TRUNCATED)
CS-305: Software engineering
"# Testing\n\n> **Prerequisite**: Before following this lecture, you should make sure you can build (...TRUNCATED)
CS-305: Software engineering
"# Mobile Platforms\n\nThis lecture's purpose is to give you a high-level picture of what the univer(...TRUNCATED)
CS-305: Software engineering
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
1