$30 off During Our Annual Pro Sale. View Details »

Android Worldwide: Everything is an API

Android Worldwide: Everything is an API

Just because we might not be exposing a module as a public or open-sourced library, doesn't mean we can't benefit from making good decisions towards an effective and sensible API. By taking the stance that every piece of code we write is an API we can build more versatile and scalable applications.

Ash Davies

July 27, 2021
Tweet

More Decks by Ash Davies

Other Decks in Education

Transcript

  1. Ash Davies
    Android & Kotlin GDE Berlin
    @askashdavies
    Everything is an API
    Android Worldwide - July 21’ 🌍

    View Slide

  2. What defines an API?

    View Slide

  3. Application Programming Interface
    noun
    A set of functions and procedures allowing the creation of applications
    that access the features or data of an operating system, application, or
    other service.

    View Slide

  4. View Slide

  5. /**
    * An utility class that provides {@code ViewModels} for a scope.
    *
    * Default {@code ViewModelProvider} for an {@code Activity} or a {@code Fragment} can be obtained
    * by passing it to {@link ViewModelProvider#ViewModelProvider(ViewModelStoreOwner)}.
    */
    @SuppressWarnings("WeakerAccess")
    public class ViewModelProvider {
    private static final String DEFAULT_KEY =
    "androidx.lifecycle.ViewModelProvider.DefaultKey";
    /**
    * Implementations of {@code Factory} interface are responsible to instantiate ViewModels.
    */
    public interface Factory {
    /**
    * Creates a new instance of the given {@code Class}.
    *
    *
    * @param modelClass a {@code Class} whose instance is requested
    * @param The type parameter for the ViewModel.
    * @return a newly created ViewModel
    */
    @NonNull
    T create(@NonNull Class modelClass);
    }
    }

    View Slide

  6. class ItemStateRepository internal constructor(/* ... */) {
    fun addToFavouritesAndMarkAsRead(itemId: String): Single = /* ... */
    fun markItemAsRead(itemId: String): Completable = /* ... */
    fun observable(): Observable = /* ... */
    fun observableFavouriteChange(): Observable = /* ... */
    fun observableHiddenChange(): Observable = /* ... */
    fun observableMarkAsReadChange(): Observable = /* ... */
    fun setItemState(itemId: String, isFavourite: Boolean): Completable = /* ... */
    fun setHiddenState(itemId: String, isHidden: Boolean): Completable = /* ... */
    fun stateFor(itemId: String): Observable = /* ... */
    fun states(): Observable = /* ... */
    fun readStateFor(itemId: String): Observable = /* ... */
    }

    View Slide

  7. ¯\_(ツ)_/¯

    View Slide

  8. ● Increased learning curve
    ● Longer to peer review
    ● Unpleasant to resolve
    ● Increased risk of bugs
    ● Slowed feature delivery
    API Decisions
    Cost of Technical Debt

    View Slide

  9. “Debugging is like being the detective in
    a crime movie where you are also the
    murderer”
    - Filipe Fortes

    View Slide

  10. ● Your code will always be consumed by other people
    ● Technical debt is not often resolved or paid back
    ● Have respect for your colleagues, make their lives easier
    ● Test code should also be considered production ready
    API Decisions
    Double standards

    View Slide

  11. “Always code as if the guy who ends up
    maintaining your code will be a violent
    psychopath who knows where you live”
    - John Woods

    View Slide

  12. Good Code? 🏆

    View Slide

  13. ● No such thing as perfect code
    ● Perfect is the enemy of good
    ● Perfect solution fallacy (Nirvana fallacy)
    ● Problem for API maintainers
    ● Done is ok, work on making it better
    Good Code?! 😭
    Not so easy...

    View Slide

  14. “Dans ses écrits, un sage Italien, dit
    que le mieux est l'ennemi du bien”
    - Voltaire (François-Marie Arouet)

    View Slide

  15. ● Keep your API surface as small as possible
    ● Allow yourself room for change
    ● Try not to expose behaviour
    Code Progressively
    Through abstraction...

    View Slide

  16. ● Prefer interface contracts
    ● Composition over inheritance
    ● Interface segregation principle
    ● Single responsibility principle
    Hiding Implementations...
    Through abstraction...

    View Slide

  17. ● Javadoc can sometimes be useful if maintained
    ● Code should always be self-documenting
    ● Name considerably and with purpose
    ● Consider sources of code smell
    Usefulness of Documentation
    “What’s a Javadoc?!”

    View Slide

  18. ● Conditional statements
    ● Iteration or recursion
    ● Significant indentation
    ● Polymorphism
    ● Mutability
    Code Smell 👃
    “My God! What is that smell?” - Veronica Corningstone

    View Slide

  19. “There are only two hard things in
    Computer Science: cache invalidation and
    naming things”
    - Phil Karlton

    View Slide

  20. Meaningful Names
    Naming is hard.

    View Slide

  21. Meaningful Naming
    for (i: Int in kS) {
    try {
    c.connect(i)
    } catch(e: Throwable) {
    // Meh 󰤇
    }
    }
    Unclear purpose or intention

    View Slide

  22. Meaningful Naming
    for (index: Int in keySet) {
    try {
    client.connect(index)
    } catch(ignored: Throwable) {
    }
    }
    Unclear purpose or intention

    View Slide

  23. Meaningful Naming
    internal suspend infix fun String.contains(value: String): Boolean
    Signatures

    View Slide

  24. Meaningful Naming
    internal suspend infix fun String.contains(value: String): Boolean
    Signatures
    Method is visible only to members in the same package (probably inaccessible)

    View Slide

  25. Meaningful Naming
    internal suspend infix fun String.contains(value: String): Boolean
    Signatures
    Method will return a result asynchronously, can only be accessed by coroutine or by another
    suspended method

    View Slide

  26. Meaningful Naming
    internal suspend infix fun String.contains(value: String): Boolean
    Signatures
    Method can be used with the Kotlin infix notation
    Eg. val result: Boolean = “12345” contains “234”

    View Slide

  27. Meaningful Naming
    internal suspend infix fun String.contains(value: String): Boolean
    Signatures
    Receiver indicates the scope of the function, must be called as an extension on this type

    View Slide

  28. Meaningful Naming
    internal suspend infix fun String.contains(value: String): Boolean
    Signatures

    View Slide

  29. Meaningful Naming
    internal suspend infix fun String.contains(value: String): Boolean
    Signatures
    Named parameters with type give us information about how to call the method

    View Slide

  30. Meaningful Naming
    internal suspend infix fun String.contains(value: String): Boolean
    Signatures
    Method return type tells us how to use the result

    View Slide

  31. Meaningful Naming
    fun updateClaimWithPolicyDetails(c: Claim, pc: PolicyCriteria, identifier: String)
    fun getIfNotSetWithDefault(value: Any): String
    fun compareAndSet(value: Any): Boolean
    fun isNullOrEmpty(value: String): Boolean
    Signatures

    View Slide

  32. Meaningful Naming
    public interface ViewStateFactory { /* ... */ }
    internal class ViewStateFactoryImpl { /* ... */ }
    Interfaces

    View Slide

  33. Impure Functions
    var values: MutableMap = mutableMapOf('a' to 1)
    fun modify(items: MutableMap): Int {
    val b: Int = 1;
    items['a'] = items['a'] * b + 2;
    return items['a'];
    }
    val c = modify(values);

    View Slide

  34. Interface Composition
    Prefer interface composition over inheritance
    ● Inheritance forces the consumer to use a base class
    ● Limitations on extending abstract classes
    ● Potentially exposes protected behaviour
    ● Prohibits Kotlin interface delegation

    View Slide

  35. Interface Abstraction
    public interface CoroutineScope {
    public val coroutineContext: CoroutineContext
    }
    internal class ContextScope(context: CoroutineContext) : CoroutineScope {
    override val coroutineContext: CoroutineContext = context
    }
    public fun CoroutineScope(context: CoroutineContext): CoroutineScope {
    return ContextScope(if (context[Job] != null) context else context + Job())
    }
    Obfuscate behaviour through interface abstraction

    View Slide

  36. ● Impact analysis, risk containment
    ● Peer review scrutiny
    ● Mob programming
    ● Android API council
    ● Guild meetings
    Democratise your API Decisions
    But not too much!

    View Slide

  37. The elephant in the room...

    View Slide

  38. Modularisation
    “Modularise all the things!”

    View Slide

  39. Modularisation
    Concurrency

    View Slide

  40. Modularisation
    Build Cache / Scan
    gradle.com

    View Slide

  41. Modularisation
    Pitfalls
    ● Misaligned product flavours
    ● Misbehaving dependencies
    ● Incorrect configurations

    View Slide

  42. View Slide

  43. ● Always a potential for risk
    ● Make use of annotations!
    ○ @Deprecated(message: String, replaceWith: ReplaceWith, level: DeprecationLevel)
    ○ @RequiresOptIn(message: String, level: Level)
    ○ @TechnicalDebt(issue: String, message: String)
    ○ @VisibleForModularisation(otherwise: ProductionVisibility)
    But,
    we’re all human… 󰤇

    View Slide

  44. @Deprecated(
    message = "CoroutineScope.rxCompletable is deprecated in favour of top-level rxCompletable",
    level = DeprecationLevel.ERROR,
    replaceWith = ReplaceWith("rxCompletable(context, block)")
    )
    public fun CoroutineScope.rxCompletable(
    context: CoroutineContext = EmptyCoroutineContext,
    block: suspend CoroutineScope.() -> Unit
    ): Completable = rxCompletableInternal(this, context, block)
    We’re all Human 󰤇
    Migration Tools

    View Slide

  45. Half screen photo slide if
    text is necessary
    We’re all Human 󰤇
    Decision Paralysis
    The worst decision is a decision
    not made in time.

    View Slide

  46. ● code that documents itself?
    ● code that can be changed easily?
    ● easily and readily maintainable?
    ● follows all the design principles?
    Conclusion
    Good code is...

    View Slide

  47. ● code that documents itself?
    ● code that can be changed easily?
    ● easily and readily maintainable?
    ● follows all the design principles?
    ● code that can be easily deleted.
    Conclusion
    Good code is...

    View Slide

  48. “Every line of code is written without
    reason, maintained out of weakness, and
    deleted by chance”
    - Jean-Paul Sartre

    View Slide

  49. ● Explicit mode for library authoring · Issue #45 · Kotlin/KEEP
    ● TwoHardThings
    ● The Annotated Programmer - Pointer IO
    ● Developers: Your Poorly Named Variables Are Hurting Your Team
    ● How modularization can speed up your Android app's built time
    ● Stefan Tilkov on Twitter: "Many enterprise IT departments have become big fans of an “API-first“ strategy"
    ● The Human Cost of Tech Debt
    ● Unreachable State
    Everything is an API
    Further Reading

    View Slide

  50. Ash Davies
    Android & Kotlin GDE Berlin
    @askashdavies
    Thanks!

    View Slide