Skip to content

Instantly share code, notes, and snippets.

@manhduy
manhduy / clean_code.md
Created April 21, 2024 09:02 — forked from wojteklu/clean_code.md
Summary of 'Clean code' by Robert C. Martin

Code is clean if it can be understood easily – by everyone on the team. Clean code can be read and enhanced by a developer other than its original author. With understandability comes readability, changeability, extensibility and maintainability.


General rules

  1. Follow standard conventions.
  2. Keep it simple stupid. Simpler is always better. Reduce complexity as much as possible.
  3. Boy scout rule. Leave the campground cleaner than you found it.
  4. Always find root cause. Always look for the root cause of a problem.

Design rules

@HiltAndroidApp
class App : Application() {
}
@Test
fun test_DisplaySum_WhenSumLiveDataChange() {
//Given
val scenario = launchActivity<CalculatorActivity>()
//When
sum.postValue(10)
//Then
onView(withId(R.id.tvSum)).check(matches(withText("10")))
}
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class CalculatorActivityTest {
@BindValue
@JvmField
val viewModel = mockk<CalculatorViewModel>(relaxed = true)
@get:Rule
var hiltRule = HiltAndroidRule(this)
android {
defaultConfig {
...
testInstrumentationRunner "com.duyha.hilttestingsample.TestRunner"
}
}
class TestRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
}
@Before
fun setUp() {
calculatorService = mockk<CalculatorService>()
viewModel = CalculatorViewModel(calculatorService)
}
@Test
fun test_SumReturnFromCalculator_LiveDataChanged() {
//Given
every { calculatorService.sum(a, b) } returns sum
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Singleton
@Provides
fun provideCalculator(): Calculator = Calculator()
}
@AndroidEntryPoint
class CalculatorActivity : AppCompatActivity() {
private val viewModel: CalculatorViewModel by viewModels()
...
}
@HiltViewModel
class CalculatorViewModel @Inject constructor(
private val calculator: Calculator
) : ViewModel() {
...
}