heihei blog

Blog icon by Unsplash https://unsplash.com/@virussinside

Notes - Android Jetpack: what’s new in Android Support Library (Google I/O 2018)

※Notes記事では、英語のセッション動画やポッドキャストの内容を(雑に)英語でメモに書き残すことを行っています。本記事は、あくまで動画を見ながら、参考程度に読んでいただくことを想定しています。Notes記事には雑メモ程度のものだったり、書き起こしのようなものもあります。これから実際の動画を見る際には、本記事の内容が少しでもお役に立てば幸いです。(内容において不備、誤字脱字等ありましたら気軽にご連絡いただけると嬉しいです!m(__)m)

本記事は、Android Jetpack: what’s new in Android Support Library (Google I/O 2018)の記事です。

f:id:shaunkawano:20180514095248p:plain

Packaging

Current Package Name

  • com.android.support
    • support-v4
    • support-v13
    • appcompat-v7
    • cardview-v7
    • gridlayout-v7
    • mediarouter-v7
    • palette-v7
    • preference-v7
    • preference-v14
    • recyclerview-v7

Packaging Versioning Releasing

  • Form of foundation to jetpack: Android Extension Libraries = AndroidX

Jetpack

  • Guidance
  • Recommended libraries and tools
  • Has a cute logo

AndroidX

  • Libraries itself
  • Technical guarantees
  • Does not have a cute logo

Finer-grained artifacts

  • Feature-based Maven groupId and artifactId
  • Scoped to individual widgets, use cases
  • Compatible with old artifacts
  • Binary compatible

Refined versioning

  • Reset from 28.0.0 to 1.0.0
  • Strict semantic versioning
    • Major - binary compatibility
    • Minor - feature release
    • Bug fix
  • Per-artifact versioning & release
  • Dependencies defined in POM

Updated packaging

  • Refactored to androidx java packages
    • 1androidx..ClassName`
  • Consistent Maven naming schemes
    • androidx.<feature>:<feature>-<sub-feature>
  • Removed -v7, -v4, etc. naming

Examples

Support Library 28.0.0-alpha1 => AndroidX 1.0.0-alpha1
com.android.support:multidex
=> androidx.multidex:multidex

com.android.databinding:adapters
=> androidx.databinding:databinding-adapters

android.arch.persistence.room:common
=> androidx.room:room-common

com.android.support:support-compat
=> androidx.core:core

com.android.support:cardview-v7
=> androidx.cardview:cardview

Migrating to AndroidX

  • Tooling for automatic source migration
    • Available in Android Studio 3.2 Canary 14+
    • Wait until Canary 15 to start using this
  • Jetifier tool for prebuilt JAR, AAR transformation
    • Available as standalone JAR or Gradle plugin
  • Use Automated refactoring(As of 05/12/18: Available now in Android Studio 3.2 Canary 14)

    • "Refactor to AndroidX…"
  • Support Library 28.0.x

    • Parity with AndroidX 1.0.x libraries
    • Same old android.support java package
    • Same old com.android.support Maven groupId
  • No feature releases after 28.0.0

What's New Features

RecyclerView Selection

  • Touch and mouse-driven
  • Preserves state between Activity lifecycle events
  • Finger-grained control
dependencies {
  implementation "androidx.recyclerview:recyclerview-selection:1.0.0-alpha1"
}
  • Band selection
  • Item selection area
  • Item rejection
  • State management
  • Much more

RecyclerView ListAdapter

  • Operates on immutable lists
  • Simplified way to use DiffUtil
  • Provides animated updates
  • Concurrency support
  • Efficiently animates changes
  • See also AsyncListDiffer

androidx.webkit

  • Provides access to latest WebView platform APIs(android.webkit.*)
  • Relies on updatable WebView APK
    • API 21+ devices only
dependencies {
  implementation "androidx.webkit:webkit:1.0.0-alpha1"
}

Browser library

  • android.support.customtabs -> androidx.browser
  • Custom tabs supported by major browsers
  • Browser actions
    • Allows apps to hook into browser context-click menu
    • Requires browser support: Chrome v66+

HeifWriter

Slices

Android's new approach for remote content

  • Templated
  • Interactive
  • Updatable

Backwards-compatible through API 19+(95% of devices)

Goal

  • One reusable API for presenting remote app content in Android
  • Templated and Interactive

Launching in Search

Enhance Suggestions with rich, live app content

  • App names
  • General terms

Reach hundreds of millions of users with Slices backwards-compatibility

dependencies {
  implementation "androidx:slice-builders:1.0.0-alpha1"
  implementation "androidx:slice-view:1.0.0-alpha1"
  implementation "androidx:slice-core:1.0.0-alpha1"
}

Slice Types

  • Shortcut slice
  • Small slice
  • Large slice

Material Components

  • Adding more customization for color, type, and shape
  • New components
  • Animations
  • Express your brand
dependencies {
  implementation "com.google.android.material:material:1.0.0-alpha1"
}

所感・まとめ・個人的に印象に残ったことなど

  • Automatic Source MigrationはCanary 15から
  • Jetifier名前良い..どういう仕組みとか知るためには紹介されていた動画を見る
  • What's new in Android Support Libraryが来年からWhat's new in AndroidXになる!
  • Androidアプリ開発を始めてから今まで、Androidのサポートライブラリ系のパッケージング周りよくわからなかったので、今回androidxに統一されて分かりやすくなるの最高そう!

以上です!

Notes - Android Jetpack sweetening Kotlin development with Android KTX (Google IO 18)

※Notes記事では、英語のセッション動画やポッドキャストの内容を(雑に)英語でメモに書き残すことを行っています。本記事は、あくまで動画を見ながら、参考程度に読んでいただくことを想定しています。Notes記事には雑メモ程度のものだったり、書き起こしのようなものもあります。これから実際の動画を見る際には、本記事の内容が少しでもお役に立てば幸いです。(内容において不備、誤字脱字等ありましたら気軽にご連絡いただけると嬉しいです。)

本記事は、Android Jetpack sweetening Kotlin development with Android KTX (Google IO 18)の記事です。

f:id:shaunkawano:20180514094438p:plain

Last Year at Google I/O

  • We are allowed to extend Android APIs to have new ways of writing Android types.
  • Create more concise version of what we intended to do
  • Intend is to feel semantically equivalent

Why can't we directly offer APIs for it? => Lambda matters

When we pass lambda in Java 8 or in Kotlin by default it has to create anonymous class which eats a method and causes a class loading.

inline

  • Language functionality which allows us to eliminate lambda's allocation
  • By marking a function with inline, the body of the function gets copied inside the caller side, so we have zero overhead.
inline fun ViewGroup.forEachIndexed(action: (Int, View) -> Unit) {
  for (index in 0 until childCount) {
    action(index, getChildAt(index))
  }
}

val userLayout: ViewGroup = findViewById(R.id.users)
userLayout.forEachIndexed ( index, view -> 
  // Do something
)

reified

  • Compiler trick
  • Forces the type information of the generic to be known at the compile time so that it can be made available at runtime
inline fun <reified T> Context: systemService(): = 
  ContextCompat.getSystemService(this, T::class.kava)

val notifications = systemService<NotificationManager>()
var onlyDigits = true
for (c in phoneNumber) {
  if (!c.isDigit()) {
    onlyDigits = false
    break
  }
}

Kotlin has a extension function isDigit() so we can use it with all {}:

val onlyDigits = phoneNumber.all { it.isDigit() }

But Android already has a built-in function:

val onlyDigits = TextUtils.isDigitsOnly(phoneNumber)

We can create a extension function for it:

inline fun CharSequence.isDigitsOnly() = TextUtils.isDigitsOnly(this)

But, is it worth it to extract it as extension? => YES - More natural - With extension, the IDE will show this with auto-complete so you can easily find this API and you can simply press it to use it.

Android KTX

core-ktx -> support-compat -> Android framework
↓
core-ktx -> core -> Android framework
fragment-ktx -> fragment
palette-ktx -> palette
collection-ktx -> collection
lifecycle-reactivestreams-ktx -> lifecycle-reactivestreams
sqlite-ktx -> sqlite
navigation-*-ktx -> navigation-*
work-runtime-ktx -> work-runtime

KTX Principles

  • Adapt existing functionality and redirect features upstream
    • The body of KTX can be just an alias of current Android APIs
    • The implementation of functions should be trivial
  • Default to inline unless code size or allocation is prohibitive
    • If you write Kotlin by your own making inline as default may not be the best way as it may lead to have more overhead
  • Leverage features unique to Kotlin

  • Code golf APIs to be as short as possible
    • KTX is not there to make the code shorter
  • Optimize for a single and/or specific use case

Reference

API reference  |  Android Developers

Android Developers Reference now contains some of the KTX extension functions

  • Extension Function Summary

Building Kotlin-friendly Libraries

Port public API or entire library to Kotlin

  • May not viable for Android Framework or androidx.* libraries
    • Maybe in the future, strongly possible

Ship sibling artifact with Kotlin extensions

KEEP-110

Kotlin Evolution Enhancement Process

@ExtensionFunction / @ExtensionProperty

  • Turn a static method with at least one argument into an extension function or an extension property
class TextUtils {
  @ExtensionFunction // Tell compiler to have an extension function for this method
  static boolean isDigitsOnly(CharSequence str) {
    int len = str.length();
    // …
  }
}

So in Kotlin side, you can use the extension function made by Kotlin compiler:

val onlyDigits = phoneNumber.isDigitsOnly()

// We no longer need this extension function
// inline fun CharSequence.isDigitsOnly() = TextUtils.isDigitsOnly(this)

// In byte code we get
val onlyDigits = TextUtils.isDigitsOnly(phoneNumber)

@KtName

  • An alternative name for methods, fields, and parameters for use by Kotlin code
  • Advantages
    • You can retain the single source of truth in Java APIs
      • You don't have to add Kotlin code
    • Even in pure Java libraries they can enhance their APIs for Kotlin users

@DefaultValue

Default parameter value

class View {
  void setPadding(
    @KtName("left") @DefaultValue("paddingLeft") int left,
    @KtName("top") @DefaultValue("paddingTop") int top,
    @KtName("right") @DefaultValue("paddingRight") int right,
    @KtName("bottom") @DefaultValue("paddingBottom") int bottom
  ) {
    …
  }
}
avatarView.setPadding(left = 10, right = 10)

// We no longer need this extension function
// inline fun View.updatePadding { … }

// in byte code we get
avatarView.setPadding(left = 10, top = avatarView.paddingTop, right = 10, bottom = avatarView.paddingBottom)

Note

  • Semantics may change
  • Naming may change
  • This proposal may not be accepted and added into Kotlin compiler
    • But some of the prototypes are already in Kotlin compiler

In Bug Tracker we have now new component: Android Public Tracker > App Development > Support Libraries > Android KTX

  • Still accepting PRs, but issues inside GitHub is no longer the single source of truth, Bug Tracker will be.

所感・まとめ・個人的に印象に残ったことなど

  • 具体的な原則をもとにどういう拡張関数を追加するかを吟味することは、Jakeとかしかできないよなぁ
  • Dead code elimination(Fragment Transactionに関する拡張関数)のくだりをみると、Kotlin Compilerがどれだけ賢いかが分かる..
  • KEEP-110がもし採択されたらktxいらなくなりそう、もしくはめちゃくちゃ軽量になりそう、けど、ツイッター上でどなたかおっしゃっていたとおもうけど、Javaのコード上にものすごい量のアノテーションつきそうでそれはそれでつらそう。どうなるのだろうか、どちらにしても楽しみ
    • とはいえ、Androidプラットフォームに適用することにおいてはものすごく恩恵が大きそうなので個人的には実現してほしいなあという印象です..!

以上です!

Notes - Android Jetpack how to smartly use Fragments in your UI (Google IO 18)

※Notes記事では、英語のセッション動画やポッドキャストの内容を(雑に)英語でメモに書き残すことを行っています。本記事は、あくまで動画を見ながら、参考程度に読んでいただくことを想定しています。Notes記事には雑メモ程度のものだったり、書き起こしのようなものもあります。これから実際の動画を見る際には、本記事の内容が少しでもお役に立てば幸いです。(内容において不備、誤字脱字等ありましたらご連絡いただければと思います。)

本記事は、Android Jetpack how to smartly use Fragments in your UI (Google IO 18)の記事です。

f:id:shaunkawano:20180512195201p:plain

The Story so far

Everybody started writing Activity

  • Entry point to your application system
  • main() with lifecycle
  • Creates views
  • Binds view

Enter tables

  • Phone UI + Phone UI = Tablet UI
  • How do I stick two phone UIs together?
  • Enter tables

Fragments of an Activity

  • Design goal of fragments allow splitting up huge Activity classes
  • Requirement: anything an Activity can do, a Fragment can do
    • Lifecycle events
    • Managing view hierarchies
    • Saved instance state
    • Non-configuration instance object passing
    • Back stacks

Can we fix some other APIs?

  • onRetainNonConfigurationInstance
  • Activity#showDialog
  • TabHost/LocalActivityManager

Factoring Activities

  • Recipe for breaking up monoliths:
    • Move loosely related code to separate fragments
    • Repeat

Factoring Activities Fragments

  • Recipe for breaking up monoliths:
  • Move loosely related code to separate fragments
  • Repeat

Things Fragments do

  • Lifecycle hooks
  • Back stack management
  • Retain objects across configuration changes
  • (Instance:)Stateful presence in the FragmentManager
  • Manage a View subtree
  • inflatable, reusable components

Architecture Components

Focuses on doing one thing well

LifecycleObservers

  • Strict ordering callback: Last in, first out
  • Created by you, not recreated via reflection
  • NO stateful restoration by the system
  • Isolated, minimal component, easy to test, easy to inject

ViewModel

  • Instances are created by factory you provide
  • LiveData allows easy (lifecycle aware!) reconnection
  • Replace retained instance Fragments
  • Your Activities or Fragments do not have to know where the data comes from; ViewModel is responsible for getting and passing data

Navigation

Fragments are good to be owner of Lifecycle, ViewModel, and views, so Google wants to make it easy for developers to use.

  • Focusing on making "How you move one screen to another screen" better
  • Works well with Fragments
  • Replaces back stack transactions

Why Fragments in 2018?

Android layering

Package Managing

android.widget vs. android.app
  • android.widget - Mechanism

    • Shows state to the user
    • Reports user interaction events
  • android.app - Policy

    • Defines state to bind to widgets
    • Responds to user interaction and issues changes to model

Inflatable Components

ViewGroups that got too smart

  • Composed high-level controls
  • Self-sufficient
  • Lifecycle aware
  • Inflated attributes can become Fragment arguments

=> Cross-cutting UI policy

  • Self sufficient components
  • Ads
  • Independent info cards
  • Parent doesn't need to be involved in data routing from repository

App Screens

Tastes great with Navigation!

Use Activity just as an entry point, and Fragments for showing actual contents

  • Single-Activity apps
  • Common app chrome, decoupled destinations
  • Transitions and animations managed by Navigation, not by hand
  • Can inflate sub-components to help

DialogFragment

Managing another interaction

  • Interaction with another..
    • Floating UI
    • System interaction
  • Leverage instance state restoration
  • Dialogs, bottom sheets
  • Transient UIs you don't want to lose

Options Menus

We still don't have a great answer for this

Merging menus for your Toolbar

  • Fragments support options menus
  • Common use case: setSupportActionBar
    • Useful for fixed common chrome
    • FragmentPagerAdapter
  • Alternative:
    • Directory manage menus as Toolbar View data

Testing Fragments

Diving Fragment Lifecycles

  • FragmentController drives lifecycle
  • Test your larger components in greater isolation
  • Possible, if not the best interface

Loaders

Now decoupled from Fragments!

  • Rebuild on top of LiveData and ViewModel
  • use Loaders from any LifecycleOwner+ViewModelStoreOwner

Where are we going?

  • Separate desired behavior from incidental behavior
  • Reimplementing existing APIs on top of new primitives
    • e.g. LoaderManager on LiveData
  • Make primitive signals and Activity callbacks available to any interested component
  • If you don't like Fragments, write your own!
    • No more magic
    • Use the same composable hooks
  • Fragments + your components working together
  • android.app.Fragment is now official deprecated

所感・まとめ・個人的に印象に残ったことなど

  • 1つのエントリーポイントに対して1つのActivityを、画面にコンテンツを表示するにはFragmentを利用していこう
    • その際のFragmentのBack Stack管理や画面遷移時のアニメーションなどは全てNavigationに任せようという流れ
  • 使いまわし可能なコンポーネントとして、コンテンツを表示する役割をFragmentに完全に任せることで、再利用可能かつ"つらみ"のないアプリ開発ができるようになる => そのためのAAC、そして今回特にFragmentのために用意されたNavigation
  • Navigationを使うことでFragmentのつらみ、Animation周りボイラープレートコードを開発者が気にする必要がなくなる
  • 未だに"つらみ"のある既存のプラットフォームAPIやサポートライブラリのAPIはあるが、今後はAACなどの新しいAPIの上に乗せる形で作り直すような例も出てくる(LoaderManagerがLiveDataに依存する形で作りなおされたように)
  • 今後はAACを使ったアプリ開発は、より安全かつより早くアプリ開発をする上で必須になりそう

以上です!

Notes - Modern Android development: Android Jetpack, Kotlin, and more (Google I/O 2018)

※Notes記事では、英語のセッション動画やポッドキャストの内容を(雑に)英語でメモに書き残すことを行っています。本記事は、あくまで動画を見ながら、参考程度に読んでいただくことを想定しています。Notes記事には雑メモ程度のものだったり、書き起こしのようなものもあります。これから実際の動画を見る際には、本記事の内容が少しでもお役に立てば幸いです。(内容において不備、誤字脱字等ありましたら気軽にご連絡いただけると嬉しいです!m(__)m)

本記事は、Modern Android development: Android Jetpack, Kotlin, and more (Google I/O 2018)のNotes記事です。

f:id:shaunkawano:20181216214559p:plain

Android History

  • 2008 - Android 1.0
  • 2013 - Android Studio
  • 2014 - ART, RecyclerView
  • 2017 - ConstraintLayout, Kotlin, AAC, Studio Profilers
  • 2018 - ktx, Paging

Tools

  • Layout Inspector
  • Trace View -> Systrace
  • New Profiler Tab in Android Studio
  • Memory Tracking
  • Layout Design
    • ConstraintLayout

Runtime in Language

Dalvik

  • Optimized for Space
  • JIT optimizations not as powerful
  • Slow Allocation/collection
  • Heap fragmentation

So

  • Avoid allocations(e.g. Don't use Enums!)
  • Primitive types are cool

ART

  • Optimized for performance
  • JIT + AOT
  • Faster allocation/collection
  • Heap defragmentation
  • Large object heap

So

  • Allocate as necessary(Yes, even enums)
  • Use appropriate types

But

  • Phones are still constrained
  • Buttery is important

Java

  • Started with Java 1.5
  • Extremely popular
  • Available great tools
  • Slow adoption of newer versions

Kotlin

  • Official support in 2017
  • Close collaboration with Jetbrains
  • Many great features that make code more enjoyable to write & read
  • Android project can contain both Kotlin & Java
  • Lint checks in Android Studio
  • Java -> Kotlin conversion
  • Android Kotlin Extension
  • Kotlin Style Guide
  • Kotlin Interop Guide

Benefits of Kotlin

  • Extensions
  • Inline functions
  • Operators
  • De-structuring assignments
  • Data classes
  • Lambdas

Now, new Java APIs in the platform starting with Android P will follow the code convention of Kotlin that when there is a SAM interface as parameter, it goes at the end of the list of parameters.

APIs

  • AbsoluteLayout => Deprecated
  • LinearLayout => Okay for simple cases
  • FrameLayout => Okay
  • GridLayout => Don't use
  • RelativeLayout => Don't use
  • ConstraintLayout => Use it. 2.0 Soon!
  • AdapterViews

Fragments

  • Complicated
  • Core platform bugs+fixes => Core Platform API @deprecated
  • Use Support Library Fragments
    • Improvements ongoing, plans for more
    • New Navigation component simplifies fragment transactions

Activities

  • Android apps consist of many activities
  • Navigating launches an activity
  • Use single activities when possible
    • One per entry point
  • Richer, more continuous use experience
  • Fragments are not necessary, but can help
    • Navigation component, too

Architecture

  • No recommendation for architecture before

Lifecycle

  • AAC: Lifecyle
    • Fragment implements LifecycleOwner
    • AppCompatActivity implements LifecycleOwner
    • Activity and Lifecycle-Dependent-Thing now gets seprated

Views and Data

  • Activity had too much stuff
    • Views
    • Data for Views
    • Lifecycle tracking
    • Data change tracking

Live Data and ViewModel

  • Activity now only contains Views and reference for ViewModel
  • Activity observes LiveData

Data

  • Do it your own! => Room

Room

  • Local data persistence via SQLite
  • Compile-time validation
  • LiveData integration
Idea from Repository Pattern
Activity/Fragment
↓
ViewModel(contains LiveData)
↓
Repository
-> Model(Room) -> SQLite
-> Remote Data(Retrofit) -> WebService

Data Paging

  • Paging Library 1.0
    • Works with RecyclerView
    • Fine-grained item changes, bindings
    • Uses background threads
    • Flexible data fetching options
    • Integration with Room
    • Boring name

Graphics

  • OpenGL ES 1.0 => OpenGL ES 3.1/3.2, Vulkan
  • Software rendering => Hardware accelerated rendering
  • Nine patches => Vector Drawables
  • TextureView vs SurfaceView => Use SurfaceView, not TextureView
  • Managing bitmaps by hand => Recommended Libraries: Glide, Picasso, Lottie

Final Thoughts

  • Profile your code => Profile your code
  • Avoid work when possible
  • Minimize memory consumption
  • Devices are still resource-constrained
  • Battery life is critical
  • Bandwidth is precious
  • User experience matters

所感、個人的に特に印象に残ったことなど

  • 可能であれば1 Activityに極力しよう、というのを公式として今回方針を明言しているのは大きいなと感じました
  • Java APIの作りもKotlinを意識した形にする、というのは最高そうですね!
  • Navigation Component、AAC LifecycleによってFragmentも扱いやすくなった、というようなわりとFragmentが肯定される内容だったのかなと
  • サードーパーティー製のライブラリも良いものは使っていこう(Retrofit, Glide, Picassoなどが本動画には登場しています)という姿勢も、全て結果的には良いUXを提供しようというところにつながっていて、説得力というか納得感もあり実際それによって開発者も悩み少なく良いアプリを作れる、というWin-Winな形があるなぁと感じました

以上です!

2018年4月を振り返る

2018年も約35%が終わったようです。( ゚∀゚)・∵. グハッ!!(洒落にならない) ※5/3(木)時点

先月に引き続き、振り返ります。

4月やったこと

Google I/O 2018 Pre-Partyに参加した

昨年度参加した経験から絞り出したTipsを紹介しました。内容は下記です

  • Office Hourを有効活用してGooglerに質問したりニーズを伝えたりしよう
  • Sandboxでの展示などを見よう
  • 「お土産」があるかもしれないので荷物の空きスペースには余裕を持とう
  • パーカーなど会場でのお土産は早めに買おう

Tips for Google I/O 2018 - Speaker Deck

去年Twitter上でOffice HourにGooglerに質問する内容をください、という旨のツイートをしたら会社の後輩や同期からメンションいただけて少しだけでも役に立てたかなと感じたので今年も同じように質問を集めています。今のところ試しにGoogle SpreadSheetを使っています。どなたでもお気軽に記載していただいて構いません。質問はあるけどここに書くのは気が引ける、こんな質問していいのかな?と悩んでいる方はDMでもくださればと思います。

docs.google.com

初技術書典

技術書典にて、Coupling Union Android愛好会というサークル名で本を出しました。Coupling Unionについては下記を御覧ください。

CyberAgent COUPLING UNION - CAグループが運営するマッチングサービスの情報メディア

Google Tasks APIやAccount Hold, Okioについて3人でそれぞれ執筆しました。

初めての技術書典で反省ばかりでしたが、控えめの部数だったとはいえ完売できて嬉しかったのと、もっと早く、かつきれいで分かりやすい文章を書けるようになりたい、と改めて思いました。貴重な経験でした!仕事の時期などはもちろん見極める必要はありそうですが、ぜひまた参加したいです。完売後の日本酒は本当に最高だった。(飲みすぎました。)

その他

  • 新しいプロジェクト

今、新しいプロジェクトで数年運用されているAndroidアプリケーションの開発を担当しています。色々もっと良くしていきたいことがあるので、頑張るぞ!

  • Ready Player Oneを観た

4.6 / 5!面白かったです。2Dで観たので、3Dでもう一度観たい。

www.youtube.com

以上になります。4月もお疲れ様でした!

Android関連のユティリティークラスやヘルパークラスの命名などについてざっくり調べてみた

TL;DR

  • ユティリティーとヘルパーの違いは曖昧
  • ユティリティークラスはプライベートコンストラクタを持ちstaticメソッドを公開しているパターンが多そう
  • ユティリティーパッケージ、ユティリティークラスやヘルパークラスの命名には単数形(~Util / Helper)を用いるパターンと複数形(~Utils / ~Helpers)を用いるパターンがある
  • ヘルパークラスはutilパッケージ内部に定義されているパターンが多そう
  • とはいえ、ユティリティークラスやヘルパークラス、またはそのパッケージの命名に関してはチームの中で統一された考え方がありみんな納得感あればそれで良さそう
  • うちのチームだとこうしているよ、というような知見の共有などいただけると幸いですm(__)m

ユティリティークラスとヘルパークラスの違いって曖昧だな、と、最近モヤモヤと感じています。

よくよく考えてみると、「ユティリティークラスとはこういうクラス」、「ヘルパークラスとはこういうクラス」というふうに深く意識したことがあまりなかったです。それはそれでどうなのよ、という意見もあるかもしれません。なぜ意識しようと思ったかというと、最近担当しているプロジェクトのユティリティークラスのコードを読んでいた時に「この関数はユティリティークラスにあるべき関数なのかな?」とふと疑問に思っている自分がいたりしたからです。なのでまずは自分なりの考えをまとめてよう、と思った次第です。

先に書いておくと、言語、プラットフォーム、もしかしたら時代によってもユティリティークラスとヘルパークラスの違いや考え方が異なるかもしれないです。今回はAndroidアプリケーション開発にフォーカスしています。

  • 別に困らないからそこまで違いを意識する必要ないのでは?
  • ユティリティークラス、ヘルパークラスは悪だ!
  • 拡張関数でええやん
  • 不毛だな(゚∀゚)

という意見もあるかもしれませんが、ここではあまり意識していません。コメントでもTwitterにてメンションやDMでも良いので、勘違いやご意見、うちのチームだとこうしているよ、というような知見の共有などもしありましたらいただけると本当に嬉しいです!

そもそも

以前、一人で開発を担当していたプロジェクトでは、ユティリティークラスはアプリケーション独自の仕様への依存がなく、どのアプリケーションにも転用できるようなstaticなメソッド群を定義したクラス、ヘルパークラスはアプリケーション独自の仕様だったり特定のライブラリに依存したstaticなメソッド群を定義したクラスと定義していたつもりでした。改めて見返してみると、常にこの定義に沿っているわけではありませんでした。。

改めて、ユティリティークラス、ヘルパークラスとはなんだろう、ということで検索してみました。

まずはユティリティークラスから見ていきます。たくさんの記事がヒットしましたが、Quoraの記事の回答を引用します。

What is a utility class? - Quora

A utility class is one which:

  • Has no state (fields) of its own, so all the methods can be class methods (static) rather than object methods (requiring an instantiation of an object)
  • Provides methods for multiple other classes (shared code)

上記Quoraの回答によると、

ユティリティークラスは、下記に該当するクラスだそうです:

  • 独自のstateを管理せず全てのメソッドがクラスメソッド(static)にできるクラス
  • 他複数クラスへメソッドを提供するクラス(shared code)

ヘルパークラスのほうも検索してみます。

stackoverflow.com

上記stackoverflowの質問では、helper "objects"という単語が使われています。もしかしたらヘルパークラスはインスタンス化して利用するクラスという認識が、質問を記載した方にはあるのかもしれないです。

stackoverflowの回答の1つを引用します。

These are objects that "sit to the side" of the main body of code, and do some of the work for the object. They "help" the object to do it's job.

ヘルパーオブジェクトは中心となるコードの隣で特定のオブジェクトのために仕事を肩代わりするオブジェクト。特定のオブジェクトの仕事の"手助けをする"オブジェクトである

というようなことが書いてありそうです。ヘルパークラスがなぜ"ヘルパー"なのかはなんとなく理由がつきそうです。この記事ではヘルパークラスという呼び方をしていますが、もしかしたらヘルパーオブジェクトという呼び方がより一般的なのかもしれないです。

Androidフレームワークのコードを参考にしてみる

ここでAndroidフレームワークのユティリティークラス、ヘルパークラスをそれぞれ参考にしてみます。

Util / Utils

Search results for "util"   |   Android Developers

ユティリティークラスに関してAndroid Developerサイト上で検索してみると、java.utilパッケージ内のクラスがたくさんヒットします。代わりに、GitHub上のAOSP mirrorのほうを見てみます。utilパッケージを覗いてみます。

github.com

クラス群の命名に注目してみると、下記に気づきました。

  • Utils接尾語がついているクラスがちらほら
  • Helpersクラスも一つだけ(ContainerHelpers.java)
  • JsonWriter、Logなど、UtilsやHelpers接尾語がついていないクラスがほとんど
  • プライベートコンストラクタが定義されていてstaticクラスとして利用するものが多いですが、インスタンス化して利用するクラスも含まれている

次はSupportライブラリのcore-utilsを見てみます。

github.com

NavUtilsColorUtilsMathUtilsのようにUtils接尾語が付与されているクラス名もあれば、そうではないクラス名もあります。また、AOSP mirror同様、Helperクラス(PrintHelper)も内包されています。

Square社のOSSのコードを参考にしてみる

次はAndroid界隈では有名なSquare社のOSSのコードを参考にしてみます。(ここでは取り上げているライブラリについての説明などは記載していません。)

OkHttp 3

※2020/08/11 追記:こちらのクラスは追記時点で存在しなくなっておりました。

OkHttp 3にはinternalパッケージ配下にUtilという名前のクラスが存在します。

プライベートコンストラクタが定義されています。internalパッケージ配下に存在しますが、定数やメソッドはpublicスコープなのでアプリケーション側からも呼び出しができそうです。

/** Junk drawer of utility methods. */
public final class Util {
...

というコメントがあります。個人的にはユティリティーメソッド群を寄せ集めしただけのクラスなのかなという解釈をしています。

Picasso 3

Picasso 3にもユティリティークラスが存在します。こちらはUtilsという名前です。

github.com

Picasso 3のUtilsクラスにもプライベートコンストラクタが定義されているため、staticメソッド呼び出しのみの利用が想定されています。Picasso 3のUtilsクラスは、クラス自体やメソッドが全てパッケージスコープとなっているようです。余談ですが、もともと依存があったかどうかは調べきれていませんが、Picasso 3のUtilsクラス内部ではOkioのクラスが利用されていることがわかります

Okio

※2020/08/11 追記:こちらのクラスは追記時点で存在しなくなっておりました。

Okioにもユティリティークラスが存在します。Okio 2に向けてKotlin化作業が進み、UtilクラスはKotlinで書き直されています。OkioはOkHttpと同様、Utilというクラス名が採用されています。

 

まとめ

もうまとめなの!?ヘルパークラスはどうした!?と思われるかもしれませんが、体力が尽きそうなのでこのあたりで身勝手にもまとめさせていただきます。

Androidフレームワークや著名なOSSライブラリを複数開発するSquare社のソースコードを参考にと思い読んでみた結果、個人的には下記のことが分かりました

  • ユティリティーとヘルパーの違いは曖昧
  • ユティリティークラスやヘルパークラス、またはそのパッケージの命名に関してはチームごとに統一された考え方があれば良さそう
  • ユティリティークラスはプライベートコンストラクタを持ちstaticメソッドを公開しているパターンが多そう
  • ユティリティーパッケージ、ユティリティークラスやヘルパークラスの命名には単数形(~Util / Helper)を用いるパターンと複数形(~Utils / ~Helpers)を用いるパターンがある
  • ヘルパークラスはutilパッケージ内部に定義されているパターンが多そう

前プロジェクトではhelpersパッケージ内に~Helperクラスを定義していましたが、AOSPの場合、utilパッケージ内部にヘルパークラスを内包するパターンが多く見られたのが意外でした。きっとユティリティーという概念の中にヘルパーという概念が存在するのだろうな、というふんわりとした印象を覚えました。

とはいえ、調べてきた上で「けどやっぱりutilパッケージとhelperパッケージわけたほうがよくないか」という考えだったり「クラス名の単数形、複数形は統一したい」「パッケージ名に関しては複数形にしたい」というようないわゆるエゴのようなこだわりのようなものは消えていないので、これからもチームの他のメンバーさんたちと議論しながら納得感持って開発していきまっす。

改めて、うちのチームだとこうしているよ、というような知見の共有などもしありましたらいただけると嬉しいです。

以上です!

2018年3月を振り返る

2018年も約27%が終わったようです。( ゚∀゚)・∵. グハッ!!(洒落にならない) ※4/7(土)時点

先月に引き続き、振り返ります。

3月やったこと

Droidcon Bostonに登壇者として参加した

3月はこれが自分にとっては一番大きなイベントでした。海外で登壇することも初めてだし、Droidcon Bostonへの参加も初めてだったので不安もありましたが、カンファレンスの登壇者や参加者、ボランティアの方々がみんな優しく、カンファレンス自体に関しても、大規模というよりはどちらかというとアットホーム感が漂う感じでそれもまた良かったです。現地のエンジニアの話(技術・生活周りなど)の話もできたことも、改めて振り返ってみてとても良かったと思います。

肝心の発表に関しては振り返るともちろんあーもっとこうしておけばよかった、とか掘り出せばきりがないのですが、DroidKaigiのときよりも落ち着いて発表できたことと、しっかりと参加者の方々から質問をしていただけたことは振り返ってみても嬉しいです。とはいえ、もちろんもっとうまくプレゼンできるようになりたいのは変わりないので、こればっかりは引き続き色々な上手な方々のプレゼンを聞いたり見たり、アドバイス頂いたりして精進したい所存です。

Droidcon Boston参加に至るまでの経緯や細かい振り返り等に関しては下記記事に記載していますので興味ある方はどうぞ:

shoheikawano.com

技術書典

ウッ…だいぶ遅れ気味ではありますが、、CU Android愛好会、初めての技術書典、頑張るぞー!楽しむぞー!(オー!)(ユルイ)

その他

  • ゆるキャン△した

「手ぶら温泉キャンプ」ということで、埼玉県神川町にあるロハスガルデンキャンプ場にいってきました。会社の同期3人と自分の男4人でゆる〜く。カレー麺もちゃんと食べました(๑•̀ㅂ•́)و✧

埼玉県神川町の手ぶら温泉キャンプ・ロハスガルテンキャンプ場

  • 映画「さよならの朝に約束の花をかざろう」を観た

壮大なストーリーで、時間もわりと長かった気がする。いろいろな意味でリアルだな、と感じた。良かった。(雑)

sayoasa.jp

まとめ

その他、業務では新しいチャレンジをさせてもらえることになったり、いろいろな変化があった3月でした。

エンジニアとして技術力をもっと伸ばさねばとは常々思っていますが、改めてインプットを増やしていかないと、と感じました。4月も精進します。

以上です!3月もおつかれさまでした!