Middle+
What do you consider bad in code and what would you like to replace immediately?
sobes.tech AI
Answer from AI
- Global variables (
val,varat the object level, with many direct accesses). - Using
lateinit varwithout a strong need (prefer nullablevalor initialization). - Long, complex functions (more than 10-15 lines of business logic).
- Lack or insufficiency of tests (unit tests, instrumental tests).
- Code duplication (copy-paste).
- Tight coupling of components (Class A directly creates/uses Class B instead of using DI or interfaces).
- Insufficient comments for non-obvious parts of the code.
- Lack of error handling or using empty
catchblocks. - Dependence on specific implementations instead of abstractions (e.g., direct use of
Contextin ViewModel). - Suboptimal use of collections (e.g., frequent list manipulations instead of sets/maps).
- Ignoring linter recommendations (Checkstyle, Detekt).
I would immediately replace:
- Using
findViewByIdwith View Binding or Data Binding. - Direct use of
AsyncTaskwith Coroutines, RxJava, or WorkManager. - Manual lifecycle management (e.g., adding/removing listeners in
onResume/onPause) with Ktx extensions or Lifecycle-aware components. - Old navigation approaches with Navigation Component.
- Using
Bundleto pass complex objects between activities/fragments with Safe Args, Parcelize, or serialization.
// Example of bad code: Global variable
class BadExampleActivity : AppCompatActivity() {
var globalCounter = 0 // Bad, hard to track changes
// ...
}
// Example of better approach: Local scope variable
class GoodExampleActivity : AppCompatActivity() {
private var localCounter = 0 // Visible only here
fun incrementCounter() {
localCounter++
}
// ...
}
// Example of bad code: lateinit var without strong need
class AnotherBadExample {
lateinit var data: String // Can throw UninitializedPropertyAccessException
}
// Example of better approach: Nullable val or initialization
class AnotherGoodExample {
val data: String? = null // Safe
// Or:
val initializedData: String = "Initial Value"
}
// Example of bad code: findViewById
class FindViewByIdActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView = findViewById<TextView>(R.id.myTextView) // Boilerplate, nullability issues
textView.text = "Hello"
}
}
// Example of better approach: View Binding
class ViewBindingActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.myTextView.text = "Hello" // Safe, type-safe
}
}