android / architecture-samples

A collection of samples to discuss and showcase different architectural tools and patterns for Android apps.
Apache License 2.0
44.37k stars 11.62k forks source link

[master] ServiceLocator.kt redundant code ? #674

Open BeQuietLee opened 5 years ago

BeQuietLee commented 5 years ago

In app/src/mock/java/com/example/android/architecture/blueprints/todoapp/ServiceLocator.kt,L43. Why repeat tasksRepository ?: in return?

Can the return be simplified as return tasksRepository ?: createTasksRepository(context) ?

    fun provideTasksRepository(context: Context): TasksRepository {
        synchronized(this) {
            return tasksRepository ?: tasksRepository ?: createTasksRepository(context) // HERE!
        }
    }

Thanks for your attention.

0neel commented 4 years ago

I suppose that's an attempt to implement Double-check locking pattern in idiomatic Kotlin-style way. Unfortunately, it's implemented incorrectly since the first null check should be done outside of synchronized block - that's required to avoid synchronization when the property is inited. Otherwise, one of the null-checks is useless.

0neel commented 4 years ago

Actually, it's possible to make it work correctly:

    fun provideTasksRepository(context: Context): TasksRepository {
        return tasksRepository ?: synchronized(this) {
            tasksRepository ?: createTasksRepository(context)
        }
    }

I wouldn't say this improves readability though.

TchaikovDriver commented 4 years ago

Also in this class, L68, in function resetRepository(), synchronization with lock instead of this may cause returning null in function provideTasksRepository(Context).


fun resetRepository() {
        synchronized(lock) {
            runBlocking {
                FakeTasksRemoteDataSource.deleteAllTasks()
            }
            // Clear all data to avoid test pollution.
            database?.apply {
                clearAllTables()
                close()
            }
            database = null
            tasksRepository = null
        }
    }```