Reputation: 12627
I want to reuse code as often as possible. Let's say I create a library called JavaBase and I nest it in an aar-package for Android. Is this a decent solution?
And lets say JavaBase contains the following coding:
public class BooleanUtils {
private static final String TAG = "BooleanUtils";
public static boolean stringEquals(String arg, String... params) {
for (String s : params) if (s.equals(arg)) return true;
return false;
}
...
Now I want to provide the same code in Android, too. Would it be a recommended way to use the following coding for the aar-package (aka 'the Android library')
public class BooleanUtils {
private static final String TAG = "BooleanUtils";
public static boolean stringEquals(String arg, String... params) {
return JavaBase.stringEquals(arg, params);
}
Thanks in advance
EDIT
After some testing I see that both packages can be imported to it will be unnecessary to recall the method in the Base-Library
Upvotes: 2
Views: 108
Reputation: 718788
Yea, it is fine to share a Java codebase between the Java(TM) and Android. Compile the code, put it in a JAR file, and share it.
However, you need to watch out for accidental dependencies on the respective platforms in your shared codebase; i.e. dependencies on classes / methods in Java SE methods that are not present on Android or vices versa. To guard against this, it is advisable to compile (and unit test) the shared codebase on both platforms.
Having said that, here's some free advice.
While it is a cool idea to reuse your own code, it is often more efficient to reuse other peoples' code. Especially code written by the Guava and Apache Commons folks. The problem with rolling your own libraries is that you may end up reinventing the wheel, and you can end up having to maintain a bunch more code than you really want / need to. Furthermore, while you might think that your libraries are better than the alternatives, other people who may have to maintain your codebase may have different opinions. That can lead to problems if other people need to work on your codebase at some time in the future.
Upvotes: 1
Reputation: 1763
For making a library in android studio, just right click on your app folder -> New->module.
Click on module and then select android library as your module. Give it whatever name you want.
In your module:app gradle add compile project(':yourlibrary') as a dependency.
That's it, now you can access the functionality of your library in your main project. For eg: you can use BooleanUtils.stringEquals() directly in your main project java class.
Upvotes: 0