Slide 1

Slide 1 text

Ubiratan Soares April / 2019 Reviewing opinionated architectural decisions applied to Android codebases and products BLOCKKED, DISTILLED

Slide 2

Slide 2 text

https://github.com/ubiratansoares/blockked Blockked A blockchain.info companion (and educational) app for Android

Slide 3

Slide 3 text

DSL❤

Slide 4

Slide 4 text

Extensions Functions Lambda Extensions Operators Overload Extension Properties Infix Notation Trailing Notation ETC Invoking Instances DSL Markers

Slide 5

Slide 5 text

https://github.com/ubiratansoares/burster

Slide 6

Slide 6 text

@Test fun `should handle error when caught from proper networking exception`() { using { 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(incoming) assertHandling(execution, expected) } } }

Slide 7

Slide 7 text

@Test fun `should handle error when caught from proper networking exception`() { using { 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(incoming) assertHandling(execution, expected) } } }

Slide 8

Slide 8 text

https://github.com/ubiratansoares/tite

Slide 9

Slide 9 text

val words = Observable.just("Adenor", "Leonardo", "Bacchi") words.test() .assertComplete() .assertTerminated() .assertNoErrors() .assertValueSequence(listOf("Adenor", "Leonardo", "Bacchi")) #$ %&' more verifications

Slide 10

Slide 10 text

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" } }

Slide 11

Slide 11 text

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" } }

Slide 12

Slide 12 text

@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 } } }

Slide 13

Slide 13 text

@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 } } }

Slide 14

Slide 14 text

https://youtu.be/Qaqr3h8RUn8

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

"Sandwich by Convention?” 1

Slide 17

Slide 17 text

Domain Service(indirection) Concrete Derivative (low level detail) Use case ViewModel UI Delivery (Activity)

Slide 18

Slide 18 text

Domain Service (indirection) Concrete Derivative (low level detail) Use case ViewModel UI Delivery (Activity)

Slide 19

Slide 19 text

Domain Service (indirection) Concrete Derivative (low level detail) ViewModel UI Delivery (Activity)

Slide 20

Slide 20 text

Repository Implementation ViewModel Activity Retrofit Observable Observable Observable Disposable

Slide 21

Slide 21 text

"In the long term duplication is by far cheaper than the wrong abstraction”

Slide 22

Slide 22 text

Concrete Derivative (conforms to Domain Service) ViewModel Activity External World Bridge Observable Observable Observable

Disposable D != P (preferred) D != V (eventually)

Slide 23

Slide 23 text

Domain Service ViewModel Activity External World Bridge Observable Observable Observable Disposable Domain Service Observable External World Bridge Observable

Slide 24

Slide 24 text

Domain Service ViewModel External World Bridge Observable Observable Observable Domain Service Observable External World Bridge Observable Use-case Observable Disposable Activity

Slide 25

Slide 25 text

Domain Service ViewModel External World Bridge Observable Observable Observable Domain Service Observable External World Bridge Observable Use-case Observable Disposable Activity

Slide 26

Slide 26 text

Data structures (“models") Services (indirections) Combinators (services + formatters + entities) Formatters Standalone Entities (Behaviours) ETC Application Domain

Slide 27

Slide 27 text

"In the application domain, the programming language should be the ultimate level of abstraction”

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

Idealism Idealism Language + frameworks

Slide 30

Slide 30 text

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) } }

Slide 31

Slide 31 text

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) } }

Slide 32

Slide 32 text

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) } }

Slide 33

Slide 33 text

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) } }

Slide 34

Slide 34 text

A Senior Engineer knows that composition should be preferred over inheritance Therefore, you should EVER avoid inherit from a given use-case base class

Slide 35

Slide 35 text

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, List) = raw.map { it as BitcoinStatistic } } }

Slide 36

Slide 36 text

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, List) = raw.map { it as BitcoinStatistic } } }

Slide 37

Slide 37 text

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, List) = raw.map { it as BitcoinStatistic } } }

Slide 38

Slide 38 text

Rx Transformers : the abstraction everyone should know about 2

Slide 39

Slide 39 text

class SomeBehaviour : ObservableTransformer { override fun apply(upstream: Observable)= TODO() }

Slide 40

Slide 40 text

class SomeBehaviour : ObservableTransformer { override fun apply(upstream: Observable)= TODO() } class SomePipeline { override fun someWork(): Observable { return someStream.compose(SomeBehaviour()) } }

Slide 41

Slide 41 text

object HandleErrorByHttpStatus : ObservableTransformer { override fun apply(upstream: Observable): ObservableSource { return upstream.onErrorResumeNext(this./handleIfRestError) } private fun handleIfRestError(incoming: Throwable): Observable = if (incoming is HttpException) toInfrastructureError(incoming) else Observable.error(incoming) private fun toInfrastructureError(restError: HttpException): Observable { val infraError = mapErrorWith(restError.code()) return Observable.error(infraError) } private fun mapErrorWith(code: Int) = when (code) { in 40001499 !" RemoteIntegrationIssue.ClientOrigin else !" RemoteIntegrationIssue.RemoteSystem } }

Slide 42

Slide 42 text

object HandleErrorByHttpStatus : ObservableTransformer { override fun apply(upstream: Observable): ObservableSource { return upstream.onErrorResumeNext(this::handleIfRestError) } private fun handleIfRestError(incoming: Throwable): Observable = if (incoming is HttpException) toInfrastructureError(incoming) else Observable.error(incoming) private fun toInfrastructureError(restError: HttpException): Observable { val infraError = mapErrorWith(restError.code()) return Observable.error(infraError) } private fun mapErrorWith(code: Int) = when (code) { in 400..499 !" RemoteIntegrationIssue.ClientOrigin else !" RemoteIntegrationIssue.RemoteSystem } }

Slide 43

Slide 43 text

object HandleConnectivityIssue : ObservableTransformer { override fun apply(upstream: Observable): ObservableSource = upstream.onErrorResumeNext(this./handleIfNetworkingError) #$ Implementation } object HandleSerializationError : ObservableTransformer { override fun apply(upstream: Observable): Observable { return upstream.onErrorResumeNext(this./handleSerializationError) } #$ Implementation }

Slide 44

Slide 44 text

object HandleConnectivityIssue : ObservableTransformer { override fun apply(upstream: Observable): ObservableSource = upstream.onErrorResumeNext(this::handleIfNetworkingError) #$ Implementation } object HandleSerializationError : ObservableTransformer { override fun apply(upstream: Observable): Observable { return upstream.onErrorResumeNext(this::handleSerializationError) } #$ Implementation }

Slide 45

Slide 45 text

object ExecutionErrorHandler() : ObservableTransformer { override fun apply(upstream: Observable) = upstream .compose(HandleErrorByHttpStatus) .compose(HandleConnectivityIssue) .compose(HandleSerializationError) }

Slide 46

Slide 46 text

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 }

Slide 47

Slide 47 text

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" ) } }

Slide 48

Slide 48 text

internal class BlockchainInfoInfrastructureTests { @get:Rule val rule = InfrastructureRule() lateinit var infrastructure: BrokerInfrastructure @Before fun `before each test`() { infrastructure = BrokerInfrastructure( service = rule.api, ) }

Slide 49

Slide 49 text

rule.defineScenario( status = 200, response = loadFile("200OK-market-price.json") ) @Test fun `should retrieve Bitcoin market price with success`() {

Slide 50

Slide 50 text

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`() {

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

The UI State Machine 3

Slide 53

Slide 53 text

ViewModel Observable Disposable AndroidSchedulers Activity class SomeViewModel { fun someExecution() : Observable { #$ %&' } } Lifecycle Control Threading Control

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

Launched Result (remote) Done

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

Launched Result (remote) Done Result (local)

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

Launched Failed (remote) Done

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

Launched Failed (remote) Done Result (local)

Slide 62

Slide 62 text

Launched Failed (reason) Done Result (value)

Slide 63

Slide 63 text

sealed class UIEvent object Launched : UIEvent() data class Failed(val reason: Throwable) : UIEvent() data class Result(val value: T) : UIEvent() object Done : UIEvent()

Slide 64

Slide 64 text

class StateMachine( private val uiScheduler: Scheduler = Schedulers.trampoline() ) : ObservableTransformer): Observable } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } }

Slide 65

Slide 65 text

class StateMachine( private val uiScheduler: Scheduler = Schedulers.trampoline() ) : ObservableTransformer): Observable } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } }

Slide 66

Slide 66 text

class StateMachine( private val uiScheduler: Scheduler = Schedulers.trampoline() ) : ObservableTransformer): Observable } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } }

Slide 67

Slide 67 text

class StateMachine( private val uiScheduler: Scheduler = Schedulers.trampoline() ) : ObservableTransformer): Observable> { val beginning = Launched val end = Observable.just(Done) return upstream .map { value: T !" Result(value) as UIEvent } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } }

Slide 68

Slide 68 text

class StateMachine( private val uiScheduler: Scheduler = Schedulers.trampoline() ) : ObservableTransformer): Observable> { val beginning = Launched val end = Observable.just(Done) return upstream .map { value: T !" Result(value) as UIEvent } .onErrorReturn { error: Throwable !" Failed(error) } .startWith(beginning) .concatWith(end) .observeOn(uiScheduler) } }

Slide 69

Slide 69 text

class DashboardViewModel( private val machine: StateMachine

Slide 70

Slide 70 text

class DashboardViewModel( private val machine: StateMachine>, private val usecase: RetrieveStatistics) { fun retrieveDashboard() = usecase .execute() .map { BuildDashboardPresentation(it) } .compose(machine) }

Slide 71

Slide 71 text

class DashboardViewModel( private val machine: StateMachine>, private val usecase: RetrieveStatistics) { fun retrieveDashboard() = usecase .execute() .map { BuildDashboardPresentation(it) } .compose(machine) }

Slide 72

Slide 72 text

class DashboardViewModel( private val machine: StateMachine

Slide 73

Slide 73 text

private fun loadDashboard() = viewModel .retrieveDashboard() .subscribeBy( onNext = { changeState(it) }, onError = { logger.e("Error !" $it") } ) private fun changeState(event: UIEvent

Slide 74

Slide 74 text

private fun loadDashboard() = viewModel .retrieveDashboard() .subscribeBy( onNext = { changeState(it) }, onError = { logger.e("Error !" $it") } ) private fun changeState(event: UIEvent

Slide 75

Slide 75 text

private fun loadDashboard() = viewModel .retrieveDashboard() .subscribeBy( onNext = { changeState(it) }, onError = { logger.e("Error !" $it") } ) private fun changeState(event: UIEvent startExecution() is Result -> presentDashboard(event.value) is Failed -> reportError(event.reason) is Done -> finishExecution() } }

Slide 76

Slide 76 text

class DashboardActivity : AppCompatActivity(), KodeinAware { private val disposer by instance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dashboard) setupViews() disposer += loadDashboard() } #$ %&' }

Slide 77

Slide 77 text

No content

Slide 78

Slide 78 text

app module (plus variants) package package package package package package package package package package package package package package package package package package

Slide 79

Slide 79 text

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

Slide 80

Slide 80 text

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

Slide 81

Slide 81 text

Life is harder than this …

Slide 82

Slide 82 text

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?

Slide 83

Slide 83 text

Learnings from the battlefield …

Slide 84

Slide 84 text

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

Slide 85

Slide 85 text

Eventually, let the composition of your modules to be “inspired” by the design your architectural layers specially when extracting modules from an existing codebase

Slide 86

Slide 86 text

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

Slide 87

Slide 87 text

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

Slide 88

Slide 88 text

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 (?)

Slide 89

Slide 89 text

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 (?)

Slide 90

Slide 90 text

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

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

https://speakerdeck.com/ubiratansoares

Slide 93

Slide 93 text

UBIRATAN SOARES Computer Scientist by ICMC/USP Software Engineer, curious guy Google Developer Expert for Android / Kotlin Teacher, speaker, etc, etc

Slide 94

Slide 94 text

THANK YOU @ubiratanfsoares ubiratansoares.dev https://br.linkedin.com/in/ubiratanfsoares