Share
Embed
Blockked, Distilled
Reviewing opinionated architectural decisions applied to Android codebases and products. Presentation given at the following events
- Dextra Special Meetup (Campinas, April 2019)
Ubiratan Soares PRO
April 08, 2019
Transcript
94 slides
-
Ubiratan Soares April / 2019 Reviewing opinionated architectural decisions applied
to Android codebases and products BLOCKKED, DISTILLED -
Extensions Functions Lambda Extensions Operators Overload Extension Properties Infix Notation
Trailing Notation ETC Invoking Instances DSL Markers -
@Test fun `should handle error when caught from proper networking
exception`() { using<Throwable, NetworkingIssue> { burst { values(UnknownHostException("No Internet"), HostUnreachable) values(ConnectException(), HostUnreachable) values(SocketTimeoutException(), OperationTimeout) values(NoRouteToHostException(), HostUnreachable) values(IOException("Canceled"), ConnectionSpike) } thenWith { incoming, expected !" val execution = Observable.error<Any>(incoming) assertHandling(execution, expected) } } } -
@Test fun `should handle error when caught from proper networking
exception`() { using<Throwable, NetworkingIssue> { burst { values(UnknownHostException("No Internet"), HostUnreachable) values(ConnectException(), HostUnreachable) values(SocketTimeoutException(), OperationTimeout) values(NoRouteToHostException(), HostUnreachable) values(IOException("Canceled"), ConnectionSpike) } thenWith { incoming, expected !" val execution = Observable.error<Any>(incoming) assertHandling(execution, expected) } } } -
val words = Observable.just("Adenor", "Leonardo", "Bacchi") words.test() .assertComplete() .assertTerminated() .assertNoErrors()
.assertValueSequence(listOf("Adenor", "Leonardo", "Bacchi")) #$ %&' more verifications -
val words = Observable.just("Adenor", "Leonardo", "Bacchi") words.test() .assertComplete() .assertTerminated() .assertNoErrors()
.assertValueSequence(listOf("Adenor", "Leonardo", "Bacchi")) #$ %&' more verifications given(words) { assertThatSequence { should be completed should be terminated should notBe broken } verifyForEmissions { items match sequenceOf("Adenor", "Leonardo", "Bacchi") firstItem shouldBe "Adenor" never emmits "Parreira" } } -
val words = Observable.just("Adenor", "Leonardo", "Bacchi") words.test() .assertComplete() .assertTerminated() .assertNoErrors()
.assertValueSequence(listOf("Adenor", "Leonardo", "Bacchi")) #$ %&' more verifications given(words) { assertThatSequence { should be completed should be terminated should notBe broken } verifyForEmissions { items match sequenceOf("Adenor", "Leonardo", "Bacchi") firstItem shouldBe "Adenor" never emmits "Parreira" } } -
@Test fun `should fetch from local cache, with cache hit`()
{ `cache has previous data`() val execution = fetcher.execute( SupportedStatistic.AverageMarketPrice, FetchStrategy.FromPrevious ) val mapped = BitcoinInfoMapper(PREVIOUSLY_CACHED) given(execution) { assertThatSequence { should be completed } verifyForEmissions { firstItem shouldBe mapped } } } -
@Test fun `should fetch from local cache, with cache hit`()
{ `cache has previous data`() val execution = fetcher.execute( SupportedStatistic.AverageMarketPrice, FetchStrategy.FromPrevious ) val mapped = BitcoinInfoMapper(PREVIOUSLY_CACHED) given(execution) { assertThatSequence { should be completed } verifyForEmissions { firstItem shouldBe mapped } } } -
Domain Service(indirection) Concrete Derivative (low level detail) Use case ViewModel
UI Delivery (Activity) -
Domain Service (indirection) Concrete Derivative (low level detail) Use case
ViewModel UI Delivery (Activity) -
Domain Service (indirection) Concrete Derivative (low level detail) ViewModel UI
Delivery (Activity) -
"In the long term duplication is by far cheaper than
the wrong abstraction” -
Concrete Derivative (conforms to Domain Service) ViewModel Activity External World
Bridge Observable<D> Observable<V> Observable<P> Disposable D != P (preferred) D != V (eventually) -
Domain Service ViewModel Activity External World Bridge Observable<D1> Observable<V> Observable<P1>
Disposable Domain Service Observable<D2> External World Bridge Observable<P2> -
Domain Service ViewModel External World Bridge Observable<D1> Observable<V> Observable<P1> Domain
Service Observable<D2> External World Bridge Observable<P2> Use-case Observable<D1+D2> Disposable Activity -
Domain Service ViewModel External World Bridge Observable<D1> Observable<V> Observable<P1> Domain
Service Observable<D2> External World Bridge Observable<P2> Use-case Observable<D1+D2> Disposable Activity -
Data structures (“models") Services (indirections) Combinators (services + formatters +
entities) Formatters Standalone Entities (Behaviours) ETC Application Domain -
"In the application domain, the programming language should be the
ultimate level of abstraction” -
class FetcherStrategist( private val remote: BlockchainInfoService, private val local: CacheService
) : FetchBitcoinStatistic { override fun execute(target: SupportedStatistic, strategy: FetchStrategy) = when (strategy) { is ForceUpdate !" remoteThenCache(target) is FromPrevious !" fromCache(target) } private fun fromCache(target: SupportedStatistic) = local.retrieveOrNull(target) ()let { Observable.just(BitcoinInfoMapper(it)) } *+ Observable.empty() private fun remoteThenCache(statistic: SupportedStatistic) = remote .fetchStatistics(statistic) .doOnNext { local.save(statistic, it) } .map { BitcoinInfoMapper(it) } } -
class FetcherStrategist( private val remote: BlockchainInfoService, private val local: CacheService
) : FetchBitcoinStatistic { override fun execute(target: SupportedStatistic, strategy: FetchStrategy) = when (strategy) { is ForceUpdate !" remoteThenCache(target) is FromPrevious !" fromCache(target) } private fun fromCache(target: SupportedStatistic) = local.retrieveOrNull(target) ()let { Observable.just(BitcoinInfoMapper(it)) } *+ Observable.empty() private fun remoteThenCache(statistic: SupportedStatistic) = remote .fetchStatistics(statistic) .doOnNext { local.save(statistic, it) } .map { BitcoinInfoMapper(it) } } -
class FetcherStrategist( private val remote: BlockchainInfoService, private val local: CacheService
) : FetchBitcoinStatistic { override fun execute(target: SupportedStatistic, strategy: FetchStrategy) = when (strategy) { is ForceUpdate !" remoteThenCache(target) is FromPrevious !" fromCache(target) } private fun fromCache(target: SupportedStatistic) = local.retrieveOrNull(target) ()let { Observable.just(BitcoinInfoMapper(it)) } *+ Observable.empty() private fun remoteThenCache(statistic: SupportedStatistic) = remote .fetchStatistics(statistic) .doOnNext { local.save(statistic, it) } .map { BitcoinInfoMapper(it) } } -
class FetcherStrategist( private val remote: BlockchainInfoService, private val local: CacheService
) : FetchBitcoinStatistic { override fun execute(target: SupportedStatistic, strategy: FetchStrategy) = when (strategy) { is ForceUpdate !" remoteThenCache(target) is FromPrevious !" fromCache(target) } private fun fromCache(target: SupportedStatistic) = local.retrieveOrNull(target) ()let { Observable.just(BitcoinInfoMapper(it)) } *+ Observable.empty() private fun remoteThenCache(statistic: SupportedStatistic) = remote .fetchStatistics(statistic) .doOnNext { local.save(statistic, it) } .map { BitcoinInfoMapper(it) } } -
A Senior Engineer knows that composition should be preferred over
inheritance Therefore, you should EVER avoid inherit from a given use-case base class -
class RetrieveStatistics(private val fetcher: FetchBitcoinStatistic) { private val cached by
lazy { retrieveAll(strategy = FetchStrategy.FromPrevious) } private val updated by lazy { retrieveAll(strategy = FetchStrategy.ForceUpdate) } fun execute() = cached.concatWith(updated) private fun retrieveAll(strategy: FetchStrategy) = Observable .fromIterable(SupportedStatistic.ALL) .flatMap { Observable.just(fetcher.execute(it, strategy)) } .let { Observable.zip(it, Zipper) } private companion object Zipper : Function<Array<Any>, List<BitcoinStatistic,- { override fun apply(raw: Array<Any>) = raw.map { it as BitcoinStatistic } } } -
class RetrieveStatistics(private val fetcher: FetchBitcoinStatistic) { private val cached by
lazy { retrieveAll(strategy = FetchStrategy.FromPrevious) } private val updated by lazy { retrieveAll(strategy = FetchStrategy.ForceUpdate) } fun execute() = cached.concatWith(updated) private fun retrieveAll(strategy: FetchStrategy) = Observable .fromIterable(SupportedStatistic.ALL) .flatMap { Observable.just(fetcher.execute(it, strategy)) } .let { Observable.zip(it, Zipper) } private companion object Zipper : Function<Array<Any>, List<BitcoinStatistic,- { override fun apply(raw: Array<Any>) = raw.map { it as BitcoinStatistic } } } -
class RetrieveStatistics(private val fetcher: FetchBitcoinStatistic) { private val cached by
lazy { retrieveAll(strategy = FetchStrategy.FromPrevious) } private val updated by lazy { retrieveAll(strategy = FetchStrategy.ForceUpdate) } fun execute() = cached.concatWith(updated) private fun retrieveAll(strategy: FetchStrategy) = Observable .fromIterable(SupportedStatistic.ALL) .flatMap { Observable.just(fetcher.execute(it, strategy)) } .let { Observable.zip(it, Zipper) } private companion object Zipper : Function<Array<Any>, List<BitcoinStatistic,- { override fun apply(raw: Array<Any>) = raw.map { it as BitcoinStatistic } } } -
class SomeBehaviour<T> : ObservableTransformer<T, T> { override fun apply(upstream: Observable<T>)=
TODO() } class SomePipeline<T> { override fun someWork(): Observable<T> { return someStream.compose(SomeBehaviour()) } } -
object HandleErrorByHttpStatus<T> : ObservableTransformer<T, T> { override fun apply(upstream: Observable<T>):
ObservableSource<T> { return upstream.onErrorResumeNext(this./handleIfRestError) } private fun handleIfRestError(incoming: Throwable): Observable<T> = if (incoming is HttpException) toInfrastructureError(incoming) else Observable.error(incoming) private fun toInfrastructureError(restError: HttpException): Observable<T> { val infraError = mapErrorWith(restError.code()) return Observable.error(infraError) } private fun mapErrorWith(code: Int) = when (code) { in 40001499 !" RemoteIntegrationIssue.ClientOrigin else !" RemoteIntegrationIssue.RemoteSystem } } -
object HandleErrorByHttpStatus<T> : ObservableTransformer<T, T> { override fun apply(upstream: Observable<T>):
ObservableSource<T> { return upstream.onErrorResumeNext(this::handleIfRestError) } private fun handleIfRestError(incoming: Throwable): Observable<T> = if (incoming is HttpException) toInfrastructureError(incoming) else Observable.error(incoming) private fun toInfrastructureError(restError: HttpException): Observable<T> { val infraError = mapErrorWith(restError.code()) return Observable.error(infraError) } private fun mapErrorWith(code: Int) = when (code) { in 400..499 !" RemoteIntegrationIssue.ClientOrigin else !" RemoteIntegrationIssue.RemoteSystem } } -
object HandleConnectivityIssue<T> : ObservableTransformer<T, T> { override fun apply(upstream: Observable<T>):
ObservableSource<T> = upstream.onErrorResumeNext(this./handleIfNetworkingError) #$ Implementation } object HandleSerializationError<T> : ObservableTransformer<T, T> { override fun apply(upstream: Observable<T>): Observable<T> { return upstream.onErrorResumeNext(this./handleSerializationError) } #$ Implementation } -
object HandleConnectivityIssue<T> : ObservableTransformer<T, T> { override fun apply(upstream: Observable<T>):
ObservableSource<T> = upstream.onErrorResumeNext(this::handleIfNetworkingError) #$ Implementation } object HandleSerializationError<T> : ObservableTransformer<T, T> { override fun apply(upstream: Observable<T>): Observable<T> { return upstream.onErrorResumeNext(this::handleSerializationError) } #$ Implementation } -
object ExecutionErrorHandler<T>() : ObservableTransformer<T, T> { override fun apply(upstream: Observable<T>)
= upstream .compose(HandleErrorByHttpStatus) .compose(HandleConnectivityIssue) .compose(HandleSerializationError) } -
internal class BrokerInfrastructure( private val service: BlockchainInfo, private val targetScheduler:
Scheduler = Schedulers.trampoline() ) : BlockchainInfoService { override fun fetchStatistics(statistic: SupportedStatistic)= service .fetchWith(statistic.toString(), ARGS) .subscribeOn(targetScheduler) .compose(ExecutionErrorHandler) private companion object { val ARGS = mapOf( "timespan" to "4weeks", "format" to "json" ) } } interface BlockchainInfoService { fun fetchStatistics(statistic : SupportedStatistic) : Observable<BitcoinStatsResponse> } -
internal class BrokerInfrastructure( private val service: BlockchainInfo, private val targetScheduler:
Scheduler = Schedulers.trampoline() ) : BlockchainInfoService { override fun fetchStatistics(statistic: SupportedStatistic)= service .fetchWith(statistic.toString(), ARGS) .subscribeOn(targetScheduler) .compose(ExecutionErrorHandler) private companion object { val ARGS = mapOf( "timespan" to "4weeks", "format" to "json" ) } } -
internal class BlockchainInfoInfrastructureTests { @get:Rule val rule = InfrastructureRule() lateinit
var infrastructure: BrokerInfrastructure @Before fun `before each test`() { infrastructure = BrokerInfrastructure( service = rule.api, ) } -
rule.defineScenario( status = 200, response = loadFile("200OK-market-price.json") ) @Test fun
`should retrieve Bitcoin market price with success`() { -
val expected = BitcoinStatsResponse( name = "Market Price (USD)", description
= "Average USD market value across exchanges.", unit = "USD", values = listOf( StatisticPoint( timestamp = 1540166400, value = 6498f ), StatisticPoint( timestamp = 1540252800, value = 6481f ) ) ) @Test fun `should retrieve Bitcoin market price with success`() { -
val execution = infrastructure.fetchStatistics(AverageMarketPrice) given(execution) { assertThatSequence { should be
completed should emit something } verifyForEmissions { firstItem shouldBe expected } } @Test fun `should retrieve Bitcoin market price with success`() { Tested in a integrated fashion -
ViewModel Observable<Execution> Disposable AndroidSchedulers Activity class SomeViewModel { fun someExecution()
: Observable<Execution> { #$ %&' } } Lifecycle Control Threading Control -
sealed class UIEvent<out T> object Launched : UIEvent<Nothing>() data class
Failed(val reason: Throwable) : UIEvent<Nothing>() data class Result<out T>(val value: T) : UIEvent<T>() object Done : UIEvent<Nothing>() -
class StateMachine<T>( private val uiScheduler: Scheduler = Schedulers.trampoline() ) :
ObservableTransformer<T, UIEvent<T,- { override fun apply(upstream: Observable<T>): Observable<UIEvent<T,- { val beginning = Launched val end = Observable.just(Done) return upstream .map { value: T !" Result(value) as UIEvent<T> } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } } -
class StateMachine<T>( private val uiScheduler: Scheduler = Schedulers.trampoline() ) :
ObservableTransformer<T, UIEvent<T,- { override fun apply(upstream: Observable<T>): Observable<UIEvent<T,- { val beginning = Launched val end = Observable.just(Done) return upstream .map { value: T !" Result(value) as UIEvent<T> } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } } -
class StateMachine<T>( private val uiScheduler: Scheduler = Schedulers.trampoline() ) :
ObservableTransformer<T, UIEvent<T,- { override fun apply(upstream: Observable<T>): Observable<UIEvent<T,- { val beginning = Launched val end = Observable.just(Done) return upstream .map { value: T !" Result(value) as UIEvent<T> } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } } -
class StateMachine<T>( private val uiScheduler: Scheduler = Schedulers.trampoline() ) :
ObservableTransformer<T, UIEvent<T,- { override fun apply(upstream: Observable<T>): Observable<UIEvent<T>> { val beginning = Launched val end = Observable.just(Done) return upstream .map { value: T !" Result(value) as UIEvent<T> } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } } -
class StateMachine<T>( private val uiScheduler: Scheduler = Schedulers.trampoline() ) :
ObservableTransformer<T, UIEvent<T,- { override fun apply(upstream: Observable<T>): Observable<UIEvent<T>> { val beginning = Launched val end = Observable.just(Done) return upstream .map { value: T !" Result(value) as UIEvent<T> } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } } -
class DashboardViewModel( private val machine: StateMachine<List<DashboardPresentation,-, private val usecase: RetrieveStatistics)
{ fun retrieveDashboard() = usecase .execute() .map { BuildDashboardPresentation(it) } .compose(machine) } -
class DashboardViewModel( private val machine: StateMachine<List<DashboardPresentation>>, private val usecase: RetrieveStatistics)
{ fun retrieveDashboard() = usecase .execute() .map { BuildDashboardPresentation(it) } .compose(machine) } -
class DashboardViewModel( private val machine: StateMachine<List<DashboardPresentation>>, private val usecase: RetrieveStatistics)
{ fun retrieveDashboard() = usecase .execute() .map { BuildDashboardPresentation(it) } .compose(machine) } -
class DashboardViewModel( private val machine: StateMachine<List<DashboardPresentation,-, private val usecase: RetrieveStatistics)
{ fun retrieveDashboard() = usecase .execute() .map { BuildDashboardPresentation(it) } .compose(machine) } Mapping function runs in the Scheduler defined by the upstream (IO or Computation) -
private fun loadDashboard() = viewModel .retrieveDashboard() .subscribeBy( onNext = {
changeState(it) }, onError = { logger.e("Error !" $it") } ) private fun changeState(event: UIEvent<List<DashboardPresentation,-) { when (event) { is Launched !" startExecution() is Result !" presentDashboard(event.value) is Failed !" reportError(event.reason) is Done !" finishExecution() } } -
private fun loadDashboard() = viewModel .retrieveDashboard() .subscribeBy( onNext = {
changeState(it) }, onError = { logger.e("Error !" $it") } ) private fun changeState(event: UIEvent<List<DashboardPresentation,-) { when (event) { is Launched !" startExecution() is Result !" presentDashboard(event.value) is Failed !" reportError(event.reason) is Done !" finishExecution() } } Threading already handled -
private fun loadDashboard() = viewModel .retrieveDashboard() .subscribeBy( onNext = {
changeState(it) }, onError = { logger.e("Error !" $it") } ) private fun changeState(event: UIEvent<List<DashboardPresentation,-) { when (event) { is Launched -> startExecution() is Result -> presentDashboard(event.value) is Failed -> reportError(event.reason) is Done -> finishExecution() } } -
class DashboardActivity : AppCompatActivity(), KodeinAware { private val disposer by
instance<AutoDisposer>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dashboard) setupViews() disposer += loadDashboard() } #$ %&' } -
app module (plus variants) package package package package package package
package package package package package package package package package package package package -
Why multi-module builds ? Better files-per-feature co-location Better isolation of
legacy code Better visibility for internal-libs candidates Faster builds with parallel tasks execution Faster builds with more cacheable tasks Dynamic features ready !!! ETC -
app module (plus variants) Library Library Library Library Library Library
Library Library Library Library Feature Feature Feature Feature Feature Feature Feature Feature Feature Feature Feature -
Multi-module design "Should this new module be Kotlin-only or Android-library?”
Can we maximize the number of Kotlin-only modules? How do you handle circular dependencies? How do you share assets between feature modules? How do you handle DI between modules? How do you share configuration logic between Gradle files? Does this design scale? -
app module (plus variants) Feature Flow Screen Behavior Feature Domain
Models Domain Services Combinators Analytics Navigator Feature Flow Infrastructure Infrastructure Infrastructure Networking Database Dependency Injection Logger Formatters Infrastructure Infra ETC Ktx extensions (aka new utils 2.0) Circular dependency hack Shared mess between related features -
Eventually, let the composition of your modules to be “inspired”
by the design your architectural layers specially when extracting modules from an existing codebase -
app module (plus variants) Feature Flow Screen Dynamic Feature Domain
Models Domain Services Combinators Analytics Navigator Feature Flow Infrastructure Infrastructure Infrastructure Networking Database Dependency Injection Logger Formatters Infrastructure Infra ETC Shared extensions Circular dependency hack Shared utilities between Related Features -
Instant App Feature Flow Screen Behaviour Feature Domain Models Domain
Services Combinators Analytics Navigator Feature Flow Infrastructure Infrastructure Infrastructure Networking Database Dependency Injection Logger Formatters Infrastructure Infra ETC Shared extensions Circular dependency hack Shared utilities between Related Features -
Going annotation-processors free No to AA libs for each micro-issue
No to compiler-generated Moshi adapters No to Dagger2 No to kapt No to Room (?) -
Going annotation-processors free No to AA libs for each micro-issue
No to compiler-generated Moshi adapters No to Dagger2 No to kapt No to Room (?) -
Build speed + multi-module projects Kotlinx.Serialization for JSON D8 for
AAC Lifecycle or Java8 desugaring Isolate modules that require kapt Minimize the # of modules relying on kapt If doomed by Dagger2: consider dagger-reflect https://github.com/JakeWharton/dagger-reflect -
UBIRATAN SOARES Computer Scientist by ICMC/USP Software Engineer, curious guy
Google Developer Expert for Android / Kotlin Teacher, speaker, etc, etc