You no longer need to put Log.d()
in each line of code!
When we debug applications, we sometimes start to generate logs all over the code to deal with any problem.
class MainActivity : AppCompatActivity() { lateinit var retrofit: Retrofit override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupToolbar() Log.d("MyApp", "Toolbar Set") initRetrofit() Log.d("MyApp", "Retrofit Initialized") var myButton = findViewById<Button>(R.id.search_close_btn) myButton.setOnClickListener { Log.d("MyApp", "My Button Clicked") } Log.d("MyApp", "Activity Creation Done!") } }
It works great, but it happens that we forget to remove the logs before committing, and they “safely” get into the production code.
Good practice is not to leave logs for debugging after it is completed, even if you use ProGuard to automatically remove them in compiled code, as they have a detrimental effect on the overall readability of your code. Like comments, logs can easily begin to diverge from the code around them, at best, becoming useless, and at worst misleading.
The situation is complicated when the removal of logs requires compliance with certain conditions. Now this is not just a useless jumble if else
, but also potentially expensive code.
But it turns out there is a very simple way to solve this problem. IntelliJ and Android Studio allow you to create breakpoints (English breakpoints ) that do not interrupt the execution of the code (yes, this is legal).
First, create a breakpoint on any line, either by clicking on the left side of the editor, or by using the keyboard shortcut Ctrl-F8
. You can then edit the breakpoint either by clicking on it with the right mouse button or by using the key combination Ctrl-Shift-F8
. You will see this window:
Then uncheck the Suspend
box, and you will see more parameters in this modal window:
Now add any logs to the Evaluate and log
field as follows:
And after removing all the logs from the code and adding them to the breakpoints, your code will look clean:
class MainActivity : AppCompatActivity() { lateinit var retrofit: Retrofit override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupToolbar() initRetrofit() var myButton = findViewById<Button>(R.id.search_close_btn) myButton.setOnClickListener { } } }
Much better, right? Now go and use uninterrupted breakpoints! All you need to do is start the application in debug mode, and the messages will be displayed in the console.
Read about other tricks in Android Studio here.
Source: https://habr.com/ru/post/420777/
All Articles