0

In Typescript (or JavaScript) I always try to write in a way that if I (or another developer) has to touch my code in one year, it is really easy to understand what is happening. So I do not try to find the shortest code possible but the clearer one.

I do not worry about the size of the file because I know in production this function:

function myFunction(value: number) {
   if(otherFunction(number){
       return true;
   }

   if(yetAtherFunction(number){
       return true;
   }

   return false;
}

will be converted to this:

function myFunction(n){return!!otherFunction(n)||!!yetAtherFunction(n)}

Would something similar happens with kotlin?

I ask because I offen find this kind of code:

val myDrawable = item?.image?.let { Uri.parse(it.toString()) } ?: R.drawable.my_default_image

and to me it is not easy to do a fast parse to know what is happening why doing a PR or similar.

If I write that in a more verbose way, would it have an impact on the size of the final apk ?

Important:

To clarify, I am not asking is it better to write in this or that way? I am asking if the compiler tries to optimize the input like a typescript/javascript minifier does.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
distante
  • 6,438
  • 6
  • 48
  • 90
  • 1
    Honestly write what is correct and clear to you. Compilers have gotten pretty efficient and unless you've identified a performance issue there isn't a need to pre-optimize. What constitutes "clean code" or "understandable code" is a matter of opinion. – Morrison Chang Jun 27 '20 at 19:44
  • Perhaps you are asking about [app size](https://developer.android.com/studio/build/shrink-code)? Related: [How to use Kotlin with Proguard](https://stackoverflow.com/q/33547643/295004) – Morrison Chang Jun 27 '20 at 20:03
  • 1
    It’s compiled to lower level code (byte code) that is in a different language than what you wrote, so your question doesn’t really apply. – Tenfour04 Jun 27 '20 at 20:13

1 Answers1

3

In Kotlin / Java world, all code must get compiled into bytecode before it can run anywhere, and in general this is basically an incredibly optimized binary blob where whitespace doesn't exist.

In interpreted languages like JS, the client / browser downloads a copy of the source and runs the source directly. Minifying is super important in these cases because it reduces the size of the file clients need to download by removing logically redundant characters. In TS, most clients cannot run it directly, so it instead gets transpiled into JS, and that is what is typically served to browsers / clients. (Some exceptions like Deno exist for example, which has a native ts interpreter).

The reason you see inlined code stuffed into one line, is purely for cosmetic / code style purposes.

Additional whitespace and variable names generally have no impact on the size / performance of your compiled Android app, so you can simply write code in the way that seems most presentable to you.

dlam
  • 3,547
  • 17
  • 20