0

My question is not really technical, so there will be no definite right or wrong. For extension functions, I have a package containing a file for every type: Context.kt contains all extension functions for Context, Uri.kt contains all extension functions for Uri and so on.

While refactoring my project, I came across these two functions:

fun Context.getImageSize(uri: Uri): Size? = try {
    val bitmapOptions = BitmapFactory.Options()
    bitmapOptions.inJustDecodeBounds = true

    val inputStream = contentResolver.openInputStream(uri)
    BitmapFactory.decodeStream(inputStream, null, bitmapOptions)
    Size(bitmapOptions.outWidth, bitmapOptions.outHeight)
} catch (e: ErrnoException) {
    null
}
fun Uri.getImageSize(context: Context): Size? = try {
    val bitmapOptions = BitmapFactory.Options()
    bitmapOptions.inJustDecodeBounds = true

    val inputStream = context.contentResolver.openInputStream(this)
    BitmapFactory.decodeStream(inputStream, null, bitmapOptions)
    Size(bitmapOptions.outWidth, bitmapOptions.outHeight)
} catch (e: ErrnoException) {
    null
}

The exact same function, extending a different type. Are there any conventions if a function depends on multiple variables, which type to extend?

Michiel
  • 767
  • 4
  • 19
  • I think the main purpose of extension methods, is to improve the readability of the calling code, so that will drive what you choose. Although Context.getImageSize reads a bit weirdly - why does a Context have an image size? – matt freake May 20 '20 at 13:42
  • 1
    Depends how you're using it. The first one will be more readable when you're using it from within an Activity, but less readable when used from within a Fragment. – Tenfour04 May 20 '20 at 13:47
  • Like matt said, Context does not have a size. I'll go for `Uri.getImageSize()` in the future, since it's the size of the uri. Thanks! – Michiel May 20 '20 at 15:15

0 Answers0