Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- **Lesson 8. Good Programming Practices**
- **Lesson Objective:**
- The objective of the lesson is to learn how to test and fix your code and effectively use the IDE (Integrated Development Environment) to facilitate work.
- **Agenda:**
- - Questions from the previous lesson and warm-up
- - Switch instruction
- - Tasks
- - Summary
- **Questions from the previous lesson:**
- - What is the syntax of the IF conditional instruction?
- - Which instruction can we use to convert a lowercase letter to uppercase?
- - How to generate a random number?
- **Warm-up Task: English-Polish Flashcards**
- Create a flashcard application that takes a word written in Polish or English from the user, and then, using conditional instructions, prints the word along with its translation. The program should ignore the case of the input characters and work for any configuration, e.g., “KOT”, “Kot”, “kot” should all give “cat”.
- Hint: Remember the possibility of writing multiple conditions for the same case in the switch instruction.
- ```csharp
- Console.Write("Enter a word in Polish or English: ");
- string word = Console.ReadLine().ToLower();
- switch (word)
- {
- case "kot":
- case "cat":
- Console.WriteLine("kot - cat");
- break;
- case "pies":
- case "dog":
- Console.WriteLine("pies - dog");
- break;
- case "dom":
- case "house":
- Console.WriteLine("dom - house");
- break;
- case "kwiat":
- case "flower":
- Console.WriteLine("kwiat - flower");
- break;
- case "krzesło":
- case "chair":
- Console.WriteLine("krzesło - chair");
- break;
- case "jabłko":
- case "apple":
- Console.WriteLine("jabłko - apple");
- break;
- default:
- Console.WriteLine("Word not found in the dictionary.");
- break;
- }
- Console.ReadKey();
- ```
- **Extended Version:**
- Make the program run indefinitely - allow querying for more than one word. Solution: Enclose the entire code in `while(true){...}`.
- **Debugging Code**
- In today's lesson, we will focus on showing methods for effectively analyzing and testing your code to find errors and irregularities. This process is commonly known as debugging, from the English word "debug" and the action "debugging," which literally means "removing bugs."
- The most basic method of finding errors, besides reacting to red messages displayed by the Error List, is using breakpoints.
- Breakpoints, also known as breakpoints, are a tool used in debugging code to stop the program execution at a specific point. Since the program code is executed line by line, breakpoints allow programmers to precisely analyze the program state at the moment of stopping.
- We add them to a specific line by clicking on the light bar to the left of the line numbers. The breakpoint will stop the program BEFORE executing the line. After indicating the red dots, the entire line will be highlighted in red. We can add an infinite number of such points.
- Debugging will automatically start after the standard program start with the Start button or the F5 shortcut. When the code reaches a line with a breakpoint, the program will stop there, and we will be able to analyze the code executed so far.
- To continue the program and move to the next breakpoint, press F5 again or the Start button, which now has changed to Continue. To stop the program, we need to use the stop button marked with a red square.
- We move to the next breakpoint and spend more time on the code executed so far. If some variables have already been declared and calculations performed in the computer's memory, we will be able to track their result or assigned data by hovering over them with the mouse.
- Let's now try to proceed without marking another breakpoint. Since after executing the condition, we don't know to which line the program will jump, we can use the Step Over button or the F10 shortcut.
- In our case, when the program didn't recognize the phrase “mother,” it jumped to the default option and the line displaying the message. This allows us to precisely analyze what is happening in our program and to which segments the conditions take us.
- After pressing F5 or Continue again, the program will start looking for further breakpoints, and if it doesn't find any, it will simply resume work. We can also continue the analysis line by line with the F10 shortcut, Step Over.
- **Task 1: Advanced Calculator**
- Write a program that takes a number and the type of operation to be performed from the user, and then uses the Math library to perform the calculations and print the final value rounded to 2 decimal places. The program should allow calculating the power of its value, the square root, and the logarithm.
- Hint: The English abbreviations for the selected mathematical operations are: pow - power, log - logarithm, sqrt - square root.
- While helping with this task, remind students that after typing the beginning of the command, they receive suggestions from the IDE, and when we put a dot after the library or object name, possible actions appear (we move through them with the arrows and confirm with enter). We also analyze with students what appears in the suggestion, i.e., the method construction, information about what and what type of parameters it accepts, and what it returns.
- Also, note that when a gray suggestion with text to write appears, just press Tab to automatically complete the suggested text.
- **Solution:**
- ```csharp
- Console.WriteLine("Enter the value:");
- int number = int.Parse(Console.ReadLine());
- Console.WriteLine("Choose an operation: \n1. Power \n2. Logarithm \n3. Square Root");
- int operation = int.Parse(Console.ReadLine());
- double result = 0;
- switch (operation)
- {
- case 1:
- result = Math.Pow(number, number);
- break;
- case 2:
- result = Math.Log(number);
- break;
- case 3:
- result = Math.Sqrt(number);
- break;
- default:
- Console.WriteLine("Invalid operation");
- Console.ReadKey();
- return;
- }
- Console.WriteLine("Result = " + Math.Round(result, 2));
- Console.ReadKey();
- ```
- **Debugging Code Continued**
- Before moving on to theory, we provide students with a fragment of a custom method that additionally calculates the factorial. Such a method is not in the Math library, so we create it as an external solution and plug it into the code.
- ```csharp
- static void Main(string[] args)
- {
- Console.WriteLine("Enter the value:");
- int number = int.Parse(Console.ReadLine());
- Console.WriteLine("Choose an operation: \n1. Power \n2. Logarithm \n3. Square Root \n4. Factorial");
- int operation = int.Parse(Console.ReadLine());
- double result = 0;
- switch (operation)
- {
- case 1:
- result = Math.Pow(number, number);
- break;
- case 2:
- result = Math.Log(number);
- break;
- case 3:
- result = Math.Sqrt(number);
- break;
- case 4:
- result = Factorial(number);
- break;
- default:
- Console.WriteLine("Invalid operation");
- Console.ReadKey();
- return;
- }
- Console.WriteLine("Result = " + Math.Round(result, 2));
- Console.ReadKey();
- }
- static double Factorial(int number)
- {
- double factorial = number;
- for (int i = 1; i < number; i++)
- {
- factorial *= i;
- }
- return factorial;
- }
- ```
- We return to debugging and use breakpoints to stop the program at the newly added operation in the switch (case 4).
- If we look at the top bar with options, we will see that jumping between breakpoints and moving to the next executed line are not the only operations we can perform. Let's look at the buttons:
- - **Red square** - stop the program
- - **Blue looping arrow** - (restart) restart the program
- - **Gray arrow to the right** - jump the editor view to the currently stopped line of the program
- - **Blue arrow with a dot pointing down (F11)** - step into the currently executed operation/method NEW FEATURE WE ARE TESTING
- - **Blue curved arrow with a dot in the middle (F10)** - step over to the next line
- - **Blue arrow with a dot pointing up (Shift+F11)** - step out of the currently executed function NEW FEATURE WE ARE TESTING
- With the F11 button, we can step into a method created by us (this won't work for Math or Console). This means that the Step Into option literally goes inside the operation and allows us to analyze it step by step until the program returns to the case. If we want to quickly exit the method, we can use the Shift+F11 Step Out option.
- We test the program with students, comparing the transition using F10 (the debugger won't enter Factorial and will immediately jump to the break) and F11 (the debugger will enter Factorial and allow analyzing it). We verify the same with other cases with Math methods (it shouldn't work).
- **Task 2: Master of Methods**
- - **Easier Version:** Find and explain what the remaining methods of the Math class do. Use IDE hints and the official C# documentation.
- - **Harder Version:** Find and explain what selected methods available in string variables do: Insert(), PadLeft(), PadRight(), Remove(), Replace(), Split(), Substring(), Trim();
- We can divide students into groups, assigning only selected methods. Encourage students to independently find out what specific methods do in the official documentation, which is available in Polish (it is translated by a translator, so it may sound strange at times): [C# Documentation](https://learn.microsoft.com/pl-pl/dotnet/api/system.math.sqrt?view=net-8
- .0)
- Teacher, remember about the possibility of adding badges for activity in the system :)
- **Using AI in a Programmer's Work**
- A) We go to one of the popular AI chatbots and ask for an explanation of the methods from task 2.
- - [Microsoft Copilot](https://copilot.microsoft.com/)
- - [OpenAI ChatGPT](https://chat.openai.com/)
- **Examples:**
- - **Copilot:** How does the Split method of the string variable work in C#?
- - **Chat GPT:** What is the Math.Round method in C#? Does the Math library have a method for calculating Factorial?
- B) We ask AI to explain the Factorial method operation after pasting the code.
- C) We ask AI to add comments to the pasted code fragment.
- **Common Beginner Errors**
- We now move on to discussing the presentation on using the Error List with students. We try not to lecture, but to talk with the students, ask when we might encounter a given error, if they know how to fix it, and if they understand the error message.
- [Error List Presentation](https://docs.google.com/presentation/d/1m7tpe9XTfLHGPv5oSZdEMgviyKytKNP-oBBjdNoAZgw/edit?usp=sharing)
- **Slide Descriptions:**
- - **Slide 2:** A very common error, but the message does not always appear in the correct place. In the case of errors 19-20, we can clearly determine where the character (in this case, the colon) is missing because the exact location is underlined in the code. For the error indicating line 17, the word "switch" is underlined in red, but this line is written correctly; the error concerns the last line of code before it, which is line 15. This line is missing a semicolon at the end, so the program does not know where the previous operation ended and indicates an incorrect end of the next one.
- - **Slide 4:** Another very common error occurs when we forget to write a brace or write too many. It is particularly easy to make this mistake when copying the teacher's code and pasting it into our program. Always carefully count the braces and compare the levels displayed by the IDE. To effectively catch such errors, it is important to care about code formatting and setting indentations at the level of newly opened braces (using the Tab key, we move them back with Shift-Tab; it is worth showing this live along with the auto-formatting shortcut Ctrl + K + D).
- - **Slide 5:** To make it easier to find the erroneous brace, pay attention to a few IDE conveniences (IDE - Integrated Development Environment, in our case Visual):
- 1. In properly formatted code, "levels" from brace to brace are marked with a dashed line.
- 2. Highlighting the opening brace always highlights the closing brace.
- 3. Properly made code blocks can be collapsed to hide their content.
- - **Slide 6:** A very common error in block instructions that are not ended with a semicolon (ifs, switches, fors, etc.), but open braces after them. It is not an obvious error because adding an extra character disrupts the entire code structure, resulting in several or sometimes even a dozen errors. In this case, writing the semicolon in the wrong place caused four errors. Therefore, always start fixing errors in the Error List from the first one because fixing one often fixes the others.
- - **Slide 7:** Sometimes we make a mistake when writing the instruction or variable name, and sometimes we forget about variable scopes. The Error List can indicate exactly which variable or word is a problem; just look at it. However, if the variable is written correctly, but according to the program it still does not exist, verify where the variable was declared. Remember that variables are created only within the given braces (we call this scope). If we want to use a variable declared in a condition, it will no longer exist outside the condition braces for the program. To make the value visible throughout the program, it is best to declare it before the Main method.
- - **Slide 8:** It may happen that we try to assign an unsupported value to a variable or perform an invalid operation on a variable of the wrong type. In this situation, we need to change the designation, use casting or parsing. Ask students how they would fix these errors.
- Not all errors are visible, though. We emphasize this and assign another task.
- **Task 3: Professional Debugger**
- Find as many errors as possible in the calculator program code and fix them. This program compiles but does not do what it should. Although the errors here won't be seen on the error list, they exist and ruin the program's logic.
- **Project with Errors:**
- ```csharp
- int number1, number2;
- string operation;
- int result;
- // Getting the first number
- Console.WriteLine("Enter the first number:");
- number1 = int.Parse(Console.ReadLine());
- // Getting the operation
- Console.WriteLine("Enter the operation (+, -, *, /):");
- operation = int.Parse(Console.ReadLine()).ToString();
- // Getting the second number
- Console.WriteLine("Enter the second number:");
- number2 = int.Parse(Console.ReadLine());
- // Performing the operation
- switch (operation)
- {
- case "+":
- result = number1 + number2;
- break;
- case "-":
- result = number1 - number2;
- break;
- case "*":
- result = number1 * number2;
- break;
- case ":":
- result = number1 / number2;
- break;
- default:
- Console.WriteLine("Invalid operation");
- return;
- }
- // Displaying the result
- Console.WriteLine("Result: " + result);
- ```
- **Properly Working Program with Indicated Errors:**
- ```csharp
- int number1, number2;
- string operation;
- float result; //*-> Change to floating-point type
- Console.WriteLine("Enter the first number:");
- number1 = int.Parse(Console.ReadLine());
- Console.WriteLine("Enter the operation (+, -, *, /):");
- operation = Console.ReadLine(); //*-> Remove double parsing
- Console.WriteLine("Enter the second number:");
- number2 = int.Parse(Console.ReadLine());
- switch (operation)
- {
- case "+":
- result = number1 + number2;
- break;
- case "-":
- result = number1 - number2;
- break;
- case "*":
- result = number1 * number2;
- break;
- case "/": //*-> Check correct character
- if (number2 == 0) //*-> Check division by zero
- {
- Console.WriteLine("Error: Division by zero");
- return;
- }
- result = (float)number1 / number2; //*-> Cast to float for floating-point division
- break;
- default:
- Console.WriteLine("Invalid operation");
- Console.ReadLine(); //*-> Pause the program at the end
- return;
- }
- Console.WriteLine("Result: " + result);
- Console.ReadLine(); //*-> Pause the program at the end
- ```
- **Final Questions:**
- - What is debugging?
- - What are breakpoints?
- - Which keys can we use to navigate through the paused code?
- - What is the Error List?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement