Mastering Debugging Techniques in HarmonyOS NEXT Development: A Comprehensive Guide
1.Mastering Practical Debugging Techniques in HarmonyOS NEXT Development
I'm Feri, a programmer with over 12 years of experience. I've been deeply involved in development projects, led teams, and even ventured into entrepreneurship. Proficient in Java, embedded systems, Hongmeng (HarmonyOS), artificial intelligence, and more, I'm dedicated to helping fellow programmers grow. Let's journey together! Where there's a will, there's a way!
The world of programming is like a mysterious labyrinth full of unknowns. Have you ever been trapped by tricky bugs during HarmonyOS NEXT development, scratching your head without a clue? Fear not! Today, I'll be your exclusive "Debugging Special Agent Captain," guiding you through three essential practical debugging techniques to crack the code puzzles with ease!
2.Logging Detective: Unveiling Data with Preview and Logs
In the initial debugging phase, logging is like a meticulous "detective," tracking down clues in the code by printing out data. However, this "detective" has specific ways to "interrogate" different types of data:
Primitive Data: For primitive types such as numbers and booleans, you need to "dress them up" with String() or .toString() before they can make a proper "appearance."
Object Data: Complex object types require a "magic transformation" through JSON.stringify to be presented clearly.
Emulator Requirement: When using an emulator, printed messages must have a prefix. It's like attaching a unique label; otherwise, the messages will "hide" and be hard to find!
Here's a "crime scene" code example:
@Entry
@Component
struct Index {
// Recording the click count, like a little counting book
@State cs: number = 1;
build() {
Column() {
Text('Click Count=' + this.cs);
Button('Print for Debugging').onClick(() => {
// Every click adds a number to our little counting book
this.cs++;
// Directly printing the raw number will "cause an error," like going out without proper clothes
// console.log(this.cs) Why does it report an error?
// Dressing up the number allows it to be printed smoothly
console.log(this.cs.toString());
console.log(String(this.cs));
// Complex object data also needs a "transformation"
// console.log({id:1,age:22}) Why does it report an error?
console.log(JSON.stringify({ id: 1, age: 22 }));
// In the emulator, adding a prefix is like giving the message a navigation; otherwise, it will get lost
console.log('Feri'+ this.cs);
});
}
}
}
This method is suitable for simple debugging. It's like shining a flashlight on a small area in front of you, helping you quickly locate basic data issues.
2.Breakpoint Time Machine: Pinpointing Problem Areas
When dealing with complex issues that the logging detective can't solve, breakpoint debugging is like a "time machine," allowing you to pause the code execution and dive deep into the problem scene. Taking emulator debugging as an example, starting this "time - travel journey" only requires three steps:
Step 1: Writing the "Script" (Coding)
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold);
}
.width("100%");
}
.height("100%");
}
}
Step 2: Setting "Time Anchors" (Adding Breakpoints)
A simple click on the left side of the suspicious code line is like planting an anchor in the code's time - space.
Step 3: Launching the "Time - Travel Program"
Click the Debug icon in the upper - right corner, or select the Attach Debugger to Process icon. The code will then pause, just like pressing the pause button on a video. When the code runs to the breakpoint, it stops, highlighting the current position. This allows you to carefully observe variable states and execution flows, leaving no detail overlooked!
Debugging Function Keys: Your Exclusive "Time - Control Buttons"
During this time - travel journey, these function keys act as your "control buttons," enabling you to master the code's execution at will:
Button
Name
Function
Shortcut Key
Resume Program
When the program pauses at a breakpoint, pressing this button is like pressing the play button, and the program continues execution.
F9 (Option+Command+R on macOS)
Step Over
During single - step debugging, it directly moves to the next line. If there are sub - functions within a function, it won't step into the sub - function but executes the entire sub - function as one step, like quickly walking past a familiar street without entering the shops along the way.
F8 (F8 on macOS)
Step Into
During single - step debugging, when encountering a sub - function, it "dives" into the sub - function and continues single - step execution, like exploring a mysterious alley and not missing any details.
F7 (F7 on macOS)
Force Step Into
During single - step debugging, it forces entry into a method, like forcefully pushing open a closed door to check the secrets inside.
Alt+Shift+F7 (Option+Shift+F7 on macOS)
Step Out
When single - step debugging inside a sub - function, clicking Step Out will execute the remaining part of the sub - function and jump back to the upper - level function, like taking an elevator back to the ground floor after exploring inside a building.
Shift+F8 (Shift+F8 on macOS)
Stop
Stops the debugging task, like ending an adventure and returning to the real world.
Ctrl+F2 (Command+F2 on macOS)
Run To Cursor
Runs the program directly to the position where the cursor is located, like teleporting to a specified location.
Alt+F9 (Option+F9 on macOS)
3.HiLog Intelligence Agent: Recording the "Black Box" of Code Execution
During the long journey of application development, HiLog is like a tireless "intelligence agent," silently recording log information at key code points. These logs are like the "black box" of an airplane, documenting every detail of the application's operation.
Compared with the ordinary console, HiLog is more professional and powerful. It provides different levels of log output (info, debug, warn, error, etc.), allowing you to filter important information as needed. However, keep in mind that HiLog logs can print a maximum of 4096 bytes, and longer messages will be truncated!
import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct Index {
build() {
Column() {
Button('Print for Debugging').onClick(() => {
// The domain is like assigning different department numbers to logs
// The tag is the log's unique name
hilog.info(0xFF00, "slj", 'hello');
});
}
}
}
For ease of use and future maintenance, it is recommended to encapsulate or use the @open/log library:
ohpm install @open/log
import log from '@open/log';
log.info(yourData);
With HiLog, you can check the application's running status at any time, analyze whether the code logic is correct, and easily identify hidden problems.
Armed with these three debugging secrets, you now have the "key" to navigate the world of HarmonyOS NEXT development! The next time you encounter a bug, don't panic. Take the initiative with these techniques! If you have any questions during practice or discover more interesting debugging methods, feel free to share them in the comments. Let's upgrade the "Debugging Special Agent Team" together!
Top comments (0)