r/androiddev • • Nov 26 '16

Effective Java for Android (cheatsheet)

https://medium.com/rocknnull/effective-java-for-android-cheatsheet-bf4e3433889a
223 Upvotes

49 comments sorted by

9

u/McDaddyWithFries Nov 26 '16

"because not all Java features are ported and used in Android (e.g. enums, serialization, etc) or due to the limitations that a mobile device has (e.g. Dalvik/ART behaves differently than a desktop JVM"

Dear writer, do you mind sharing what those are? Specifically about enums and serialization?

You can use serialization and enums, so what is not ported exactly?

7

u/netcyrax Nov 26 '16

Good catch, thanks for pointing out. What i meant is that neither of the two features are widely used in Android. Enums (@IntDef are preferred) and serialization (parcelables are preferred) have Android-specific alternatives.

13

u/Saketme Nov 27 '16

Enums are pretty widely used in android apps. Unless you're referring to AOSP by "Android", I'd disagree with you.

0

u/[deleted] Nov 27 '16

[deleted]

7

u/Saketme Nov 27 '16

That's a different discussion :)

2

u/eMperror_ Nov 28 '16

Meh, they take more space but it's not really that much of an issue with modern devices.

1

u/ene__im https://github.com/eneim Nov 27 '16

just FYI, i think some stuff from javax is not ported (not the java GUI stuff)

4

u/prlmike Friendly Mike Nov 26 '16

Nice article. I'm believe I read somewhere that string concatenation gets translated to a string builder when compiling.

2

u/Zhuinden Nov 26 '16 edited Nov 26 '16

Nice article. I'm believe I read somewhere that string concatenation gets translated to a string builder when compiling.

If I remember right, that's only true for static things that don't change during runtime.

String hello = "Hello" + " " + "World";

The for loop cannot be compiled to a StringBuilder just like that, you end up creating a bunch of intermediate strings.

2

u/netcyrax Nov 26 '16

Thanks, didn't know that.

According to the docs [1] "The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method."

[1] https://developer.android.com/reference/java/lang/String.html

32

u/Plastix Nov 26 '16 edited Nov 26 '16

Static factory methods are really good for creating intents as well:

public class MyActivity {

	private static final String EXTRA_ARG = "SomeArg";
	
	public static Intent newIntent(Context context, String someArg){
		Intent intent = new Intent(context, MyActivity.class);
		intent.putString(EXTRA_ARG, someArg);

		return intent;
	}
}

Great writeup! Thanks for sharing.

10

u/ditn Google Developer Expert Nov 26 '16

There's a shortcut/postfix completion thing in Android Studio to do this for you. Type 'start' on a new line.

2

u/Plastix Nov 26 '16

Woah I didn't know this live template existed. Thanks!

4

u/ditn Google Developer Expert Nov 27 '16

Nor did I until a week ago! Turns out hitting CMD+J (iirc) lets you browse the templates in context, it's worth having a dig around for half an hour and seeing what's useful to you.

1

u/aselims Jan 26 '17

'starter' is the right one at AS2.2.3

16

u/Zhuinden Nov 26 '16

It's great when the static factory method is actually static

3

u/Plastix Nov 26 '16

Haha nice catch. I was typing a little too fast.

4

u/[deleted] Nov 26 '16

There is a lib called Henson that generates intent builders for activities from fields you have annotated. These fields can be automatically injected on the activity instance as well (works similarly to ButterKnife). You can make fields optional or required. It's pretty nice.

1

u/eMperror_ Nov 28 '16

Henson/Dart is very good! We use it on a fairly big project and it's been very good to us so far.

1

u/[deleted] Nov 26 '16

[removed] — view removed comment

4

u/chickennoodlegoop Nov 26 '16

This works fine when you can make assumptions about the arguments/extras that you need the intent to have, but gets a little tricky to abstract away otherwise.

4

u/cesarpim Nov 26 '16

A good review of best-practices for Java, thank for your post. My issue is only with your title... this isn't something specific for Android, it's for Java in general.

3

u/zunjae Nov 26 '16

Do you really need to use StringBuilder? I thought your compiler automatically converted it for you.

2

u/pgetsos Nov 27 '16

ESPECIALLY in loops it is quite faster

5

u/Paradiesstaub Nov 26 '16

How about making everything possible final (class, method, variables).

14

u/shadowdude777 Nov 26 '16

I make everything final and annotate every return type and parameter as either @NotNull or @Nullable. Some people say it's too verbose, but it has cut down the amount of mistakes I make by probably an order of magnitude.

Or I just use Kotlin and get all of this and more for free. :)

11

u/drabred Nov 26 '16

I've been doing this. Now (in Java) I assume not-nullability and only use @Nullable where needed. It's not that tedious this way.

4

u/shadowdude777 Nov 26 '16

That's not a bad idea. I find myself using @NotNull WAY more often than @Nullable so maybe only annotating the latter is a good way to cut down on verbosity while also getting the same linter warnings.

Though I think it still might be worth annotating parameters as @NotNull because I believe you can still pass @Nullable values to non-annotated params without triggering the lint warning, right?

2

u/TheRealKidkudi Nov 26 '16

How does that work in Kotlin? I've heard about it a lot, but to be honest I've never really made the time to look into it at all.

13

u/shadowdude777 Nov 26 '16

Java non-final declaration:

String foo = "";

Java final declaration:

final String foo = "";

Kotlin non-final declaration:

var foo = ""

Kotlin final declaration

val foo = ""

Since final isn't an extra keyword in Kotlin, but a choice between val/var, you're forced to make the decision every time you make a variable whether it should be final or not. It seems like a trivial distinction, but tell me when the last time you made a local variable final in Java was. For most people, that's not a thing you usually do, because it's verbose.


As for nullity, in Java, this is legal:

String foo = null;

In Kotlin, this is not:

val foo: String = null

You must change the type to String? (with a question mark at the end). And if you want to pass a String? to a parameter marked only as String, you have to null-check first. Similarly, if you want to take a return-type of String?, you can't put it into a variable of type String without doing a null-check.

For all intents and purposes, String is a subclass of String?, and all regular polymorphism rules apply here.


Since Kotlin makes you actively choose whether something should be final or not, or null or not, every time you declare it, it means most variables and return types end up being non-nullable and final, which is great.

2

u/TheRealKidkudi Nov 26 '16

Interesting, thanks for the explanation! If you don't mind another question, what about the worst of Kotlin? What makes you not like it?

9

u/shadowdude777 Nov 26 '16

The worst parts to me are as follows:

  1. You have to add a new dependency to your build.gradle. This is kind of annoying for Android developers. Fortunately, it's surprisingly small, at 4813 methods. This sounds like a lot, but it's a whole language, with a staggering amount of functionality (pretty much anything you could want from Guava, for example, is in Kotlin), and most of us already use RxJava, which has 800 more methods than Kotlin!

  2. public is the default modifier. This is certainly better than the infrequently-used package-protected modifier in Java (which has been replaced with something called internal in Kotlin, which is WAY more useful than package-protected), but private really should be the default in my opinion.

  3. When interoping with Java code, you get back objects that are typed as String!. This basically means "we can't tell if this is null because the Java compiler doesn't tell us that information." The sane thing to do, in my opinion, would be to treat them all as nullable. However, for "convenience's sake", Kotlin chose to treat them all as non-null! This means that you can still get NPEs in Kotlin if you're calling Java code. This is, in my opinion, the worst part of the language, as it kind of subverts all of the null-safety the devs worked so hard to establish.

Aside from that, fantastic language, and easily my favorite language that I've ever worked in (with a close second being Rust, which has completely different design goals but is still incredibly elegant).

1

u/MrBIMC Nov 28 '16

Both(#2 & #3) of your points are not really bad parts of kotlin though, you know the reasoning behind these decisions:

2) Yes, from puritan point of view, private-as-default would be better for OOP languages, but kotlin is pragmatic language, not puritan one and statistics show that public modifier is used in much more cases than private one. So using public as default saves a lot on keystrokes in a long run. Can't link that, but there's some JetBrains post about decision behind "public-as-default modifier".

3) String! will not appear if java code is marked by @Nullable or @NotNull annotations. Instead kotlin will fallback to corresponding type. Also, Platform types (String!, Type!) are just another pragmatic decision. Otherways, if everything cast to optionals, developers would be annoyed by explicitly unwrapping every variable they interact with. Redundant safety is also bad.

P.S. #1) point is also meh, as 5k methods is literally nothing thesedays.

1

u/shadowdude777 Nov 28 '16

Point 1 is very important. Methods count means a lot to a lot of developers, who are trying to avoid Proguard and multidex.

2) I understand why they chose public-as-default but it's still not a good idea. The language is all about safety, and adding one more word in a few places is no big deal. You shouldn't be using public that often that it gets annoying.

3) This is absolutely an indefensible decision. By that logic, we shouldn't have String? as a type at all, because unwrapping it is annoying. We should just get rid of null-safety altogether. Most NPEs in Kotlin come from Java interop. The fact that platform types exist is a HUGE source of bugs. Doing ?. instead of . is not inconvenient. Being forced to check to avoid crashing your app is not an inconvenience, it's a feature.

0

u/[deleted] Nov 26 '16

[deleted]

1

u/shadowdude777 Nov 26 '16

Exactly. A Lint warning is not as good as a compiler error like you get with Kotlin, but it's the best thing that we'll get in Java, and if you're paying attention, you still have almost no excuse for NPEs. The only exception I can really think of is if you call a library function that either isn't annotated, or that your IDE can't infer the nullity for. Those are always a huge bummer. :(

7

u/Phreakhead Nov 26 '16

Please don't make classes final. I hate when I just want to extend some class to have an extra tiny bit of functionality, but I can't because the author either made it final or made some members private when they could have been protected. Android is the worst at this. So many useful widgets and gesture detectors and what not, all having to be copy/pasted if you want to improve them at all.

12

u/nhaarman Nov 26 '16

Instead, prefer composition over inheritance.

3

u/Zhuinden Nov 26 '16

There are times when you can't just wrap the code with some decorator to fix internal behavior.

So you have to go and copy the whole library into your project and make the tiny bits of changes that 'd be easily done if they were at least package-visible or protected, or the class weren't final.

Flow was the most annoying at this, I had to copy both Flow 0.12 back in the day, and also Flow 1.0-alpha into my project initially to fix its bugs, because most of its stuff just can't be fixed from the outside. Well, technically copying it and then putting it in a forked Github repository was the easiest solution, so there's that.

2

u/Phreakhead Nov 27 '16

Heck even just ListView has scrolling animators, gesture detectors, etc. that would be so nice if you could just override them. But no, you have to hack your way around it with Compat everything or just writing it over again.

1

u/nhaarman Nov 27 '16 edited Nov 27 '16

A library developer, especially the folks over at Square, chooses their public api very carefully. Anything that is not private or final becomes a point some developer will rely on. The moment you change that, you will break their code.

When you expose that your internal data structure is a LinkedList instead of a List, you cannot change that anymore, because somewhere, someone will use that. You decide to rename your internal state variable i to counter? Someone is accessing i.

Suppose you wrote some internal function that does some nasty stuff using private fields and setting some state. One moment between library versions you decide to clean that up and remove the fields, or even just rename them. If you did not declare them as private or final, you're probably gonna break someone's code. And that may cause a developer like you to spend a whole day figuring out why your beautiful changes won't work anymore.

About classes being final, there is an item in EJ that you should design your classes for inheritance, or else prohibit it. There's ton of stuff potentially breaking when you change your 'base' class.

Heck, there's even a commit in AOSP where the fact that Samsung used reflection to access a private field caused the refactoring of some private stuff to be partially undone.

1

u/Zhuinden Nov 28 '16

Heck, there's even a commit in AOSP where the fact that Samsung used reflection to access a private field caused the refactoring of some private stuff to be partially undone.

I'd just keep it package-local as of late so that reflection can be avoided if someone wants to tinker with it. Package visibility is a lesser evil compared to reflection.


Otherwise, I guess that makes sense, although our code wasn't bad enough for this to come up as an issue, or maybe just wasn't complex enough. Not sure.

1

u/philipwhiuk K-9 Mail Developer (GH: philipwhiuk) Nov 29 '16

Heck, there's even a commit in AOSP where the fact that Samsung used reflection to access a private field caused the refactoring of some private stuff to be partially undone.

There's always this: https://www.facebook.com/notes/facebook-engineering/under-the-hood-dalvik-patch-for-facebook-for-android/10151345597798920/

1

u/s73v3r Nov 28 '16

If the thing is fixing internal bugs, then that's how you should be doing it. Then send the fix to the maintainer. Don't subclass to fix behavior, as someone new to the project won't have any idea that you're using MyBaseClass instead of the one the library provides.

1

u/Zhuinden Nov 28 '16

Well I did file issues but I needed the fix sooner than 9+ months later

0

u/[deleted] Nov 26 '16

[deleted]

3

u/Fiskepudding Nov 27 '16

Put it in the build method (if you are reusing the builder and can't use the constructor), or throw if it's not set.

1

u/Pidggit Nov 27 '16

I've seen this been said before ("use the builder pattern for constructors that have more than x args").

I like that it looks nicer and automatically gets documented what the values are for, but I still can't bring myself to use it since you can't ensure at compile time that all required properties have been set.

Does anyone have any solutions to this concern?

1

u/VeyndanStuart github.com/veyndan Nov 27 '16

Another option is to put the required fields as the constructor parameters of the Builder.

0

u/[deleted] Nov 27 '16

[deleted]

1

u/VeyndanStuart github.com/veyndan Nov 27 '16

Ah sorry must have missed that. I probably shouldn't go on Reddit just before I'm about to sleep haha