enum vs android #Intdef - which one is better optimized - android

I know that when comparing constants to enums constants take up less space and can be primitive. I am researching #Intdef annotation in android and can someone tell me if its better storage to use #Intdef vs a enum. Is it recommended now in android to put enum aside and use #intdef moving forward when possible ? can #Intdef do polymorphism, i doubt?
from the android docs regarding memory overhead:
Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

#Intdef is clearly more efficient, it carries zero weight over just having static final ints, it's all compile time instructions. enums are classes and as mentioned in your link have a foot print. #Intdef gets you the most basic functionality of enums namely value validation and none of the other features of enums such as automatic String conversions.
Much of the android docs is stale, this could very well be one of them. Back in the early days of android every bit counted but now devices are much more capable. Personally I would choose between those two options depending on what's called for by design and not get too caught up with being efficient. Also the syntax for some of these more advanced annotations doesn't make for clean easy to read code, so not a fan there. However if the situation calls for good old static ints the #Intdef will buy you some protection at the expense of visual clutter.

In addition to previous answers, I would add that if you are using Proguard (and you should definitely do it to reduce size and obfuscate your code), then your Enums will be automatically converted to #IntDef wherever it is possible:
https://www.guardsquare.com/manual/configuration/optimizations
class/unboxing/enum
Simplifies enum types to integer constants, whenever possible.
Therefore, if you have some discrete values and some method should allow to take only this values and not others of the same type, then I would use Enum, because Proguard will make this manual work of optimizing code for me.
And here is a good post about using enums from Jake Wharton, take a look at it.
As a library developer, I recognize these small optimizations that should be done as we want to have as little impact on the consuming app's size, memory, and performance as possible. But it's important to realize that throwing away an Iterator allocation vs. an indexed loop, using a HashMap vs. a binary-searched collection like SparseArray, and putting an enum in your public API vs. integer values where appropriate is perfectly fine. Knowing the difference to make informed decisions is what's important and the video nearly nails that except for this one stupid stat.

Related

What does obfuscating an API mean?

I am currently reading a research paper on obfuscation. Here's the portion of the paper that relates to my question.
"while current obfuscation schemes elevate some islets of static analysis, such as changing layout of the source code, changing control flow, and modifying data, they are easily exposed to reverse engineering analysis due to a lack of API concealment. Therefore, a quantitative evaluation scheme is needed to ensure that obfuscation is applied to an appropriate API with an adequate degree of resistance to reverse engineering."
"Obfuscating the API" probably means changing the names of identifiers, like class names, method names, field names, etc, to very un-descriptive names. so that readers of your code wouldn't know what your code is doing.
Proguard is such a tool. Here is a post I found, involving using Proguard to obfuscate private methods in a simple class. You can see how privateStaticMethod turned into a, and how the parameter names turned into paramString1 and paramString2.
By doing so, readers won't know what a does just by looking, because a tells them literally nothing about what the method actually does. The methods that a calls might also be obfuscated as b or c, which makes it even harder to know what your code is doing.
Reverse-engineering here refers to trying to figure out how obfuscated code looked originally. Obviously, changing the names of methods and parameters makes it harder to reverse-engineer than just changing control flow and code layout.

What are the pros and cons of android data-binding?

Both of my colleague and I have experience in MVVM of Web App, while we are new to native android development. Now we have contrary opinions about android data-binding -- I'm a fan of it while he is not.
My Arguments:
Reduces boilerplate code which in turns brings
Less coupling
Stronger readability
Powerful, easy to implement custom attribute and custom view
Even faster than findViewById (details)
His Arguments:
The auto-generated .class increases app size.
Harder to debug
I've made some investigation but there are not many discussions about it. Now I want to collect the pros and cons of android data-binding.
Aspects of discussion include but are not limited to:
unit test
app size
performance
learning curve
readability
coupling
I will comment on your arguments first then I will state my opinion:
1.Remove boilerplate code - it will remove some it will just move some in the xml or it will require additional classes. So you have to be careful and balance the use of data binding.
2.Stronger readability - depends if you are a new developer then you may find it easy to learn it but if you previously worked on android you will need extra time to learn it.
3.Powerful - the code has more power, you can implement whatever you like in code. Think about it like this, everything you implement using data binding has a code equivalent (it might be longer and more code to write), but the revers is not valid.
4.Even faster than findViewById - comparing the speed between these two, in my opinion is useless, you will never notice the difference, if you see some difference, then one of the implementation is wrong.
5.Auto generated class - it's true it will increase the app size, but again only if you have tons of it it will matter. It's true that on the android dev web site they state that it's kind of bad to use libraries that create autogenerated code or annotations that will generate extra code.
6.Hard to debug - depends, like readability, of what you are used to, heck debugging is hard either way for some problems, and you will get better by debugging not by using a different library.
So this is pure my opinion, I've developed many apps using different libraries and different approaches, and they all had pros and cons, but what I've learn: balance everything, don't use tons of libraries, don't waste time implementing things that are implemented already and work well, don't "decouple everything", don't "couple" everything, don't use code only, don't try to "generate" everything.
I think it's quite wrong, and you can get a wrong idea, if you ask for 'pros & cons' about some library/implementation, because usually it won't be impartial, you will get a lot of pros from somebody who used the library in a specific way and it worked and others will give you cons because they used different and it didn't work.
So in conclusion, I think you should check what the library can do for you and what can't do for you and decide if it's good for your setup. In other words, you should decide if a library is good for you not other people ;).
Update - 8 August 2018
First of all I still stand with my initial conclusion, balance is the key in these kind of situations, but in my case, data-binding speed-up a little bit the development process and also improved it. Here are a few new points that you should all think about.
Testing the UI -- with data-binding it's much more easy to test the UI, but data-binding it's not enough for that, you also need a good architecture and using the Google suggested architecture will show the actual power of data-binding.
The most visible changes were provided for points 2 & 5 from my original answer. It kind of was easier to read the code after we decided to use data-binding, and the most important thing here is: we as a team decided that we will use data-binding and after that, we kind of expected to have most of the trivial and basic UI setup in the XML file.
For the debugging part, here's a little bit tricky, Android Studio has a lot to improve on the errors and autocomplete for the data-binding but the most common errors you'll get them after the first 2-3 occurrences. Also I've learned that a "clean project" form time to time, helps A LOT.
Another point that you'll have to take in consideration is the project configuration to use data-binding, right now AS (3.1) supports by default data-binding (just set a flag in graddle) for Java, but I had some issues with Kotlin, after a bit of search here on SO, I managed to fix everything.
As a second conclusion (from my original post), if you can and the project deadline/requirements/etc allows you to try data-binding, go for it it will worth (unless you do some really stupid stuff :)) ).
I am working on a huge Android project and the team has decided to phase out Data Binding library. Why? The primary reason is that it is exacerbating build time(10+ mins), by generating a lot of classes in the build process.
Even if i like danypata's answer i would like to add/edit some of his statements to android databinding.
1.Remove boilerplate code - As written in danypatas answer it removes some code and adds some code somewhere else like in layouts. That doesnt mean that the boilercode isnt reduced because usually it is reduced.
For example you may want to create a bindingadapter, which handles several custom arrayadapters for your spinner/recyclerview/listview/.. but requires only one simple adapter. You may want to use the adapter in your layout by using e.g.
app:myCoolAdaptersData="#{model.mydata}"
Now you can create your generic adapter and (re)use your bindingadapter in all your layouts instead of using for example:
ListView lv = findViewById(...);
CoolGenericAdapter<MyModel> coolAdapter = new CoolGenericAdapter<>(...);
lv.setAdapter(coolAdapter);
This is just one simple example which recudes the code alot in larger projects. Another sample to recude code is, that you bind your model to your layout. Updating field-values of your model usually updates your model aswell (if its at least a BaseObservable/ObservableField).
That means that you dont need to find all your views, update your views, update your models, ...
2.Stronger readability - The extra time spent for learning databinding doesnt really matter. Since the layouts are not really different except that you wrap them into a layout tag and put your namespaces there, it doesnt really differs from "regular" layouts. Using bindingadapters and accessing the model in the layout may take some time, but usually you can start beginning with the basics which are easy and beautiful to use aswell. Learning new stuff always takes time, but you will easy overhaul the time when using databinding after a while.
3.Powerful - Yes, its very powerful. Its easier to reuse existing code, reuse existing bindingadapters and may lead to more generated code but thats not always true. For example you may create multiple adapters within several classes instead of creating one bindingadapter, it may be hard to "optimize" it later. Optimizing the Bindingadapter means that it gets updated everywhere. Optimizing may decrease the "lines of code" since the boilerplace is reduced anyway.
I agree to 4. and 5.
6. Hard to Debug Since AS 3.0+ outputs useful hints like syntax issues in your layout (line number and file) its easy to debug databinding generated code. If you have problems finding the issue you may also want to check for errors in the generated code. Some librarys like dagger 2 or android architecture library may confuse you because the error lines doesnt match with the real "error". This is due generated code by other annotation processors. If you know that those annotation processors may get in trouble with databindings error outputs, you can easy fix that.
7. Unit Testing Its possible like if you dont use databinding by using executePendingBindings.
8. Readability Readability may be better without databinding. Since you put some business logic into your layout, some into your real code, it may lead to spaghetti-code. Another problem is that using lambdas in your layout may be very confused if the "layout-designer" doesnt know which param may be used.
Another very big problem is that bindingadapter can be everywhere. Using BindingAdapter annotation generates the code. That means that using this in your layout may lead to problems to find the proper code. If you want to update a bindingadapter you need to "find" it.
When should you use what? For larger projects it is a really good idea to use databinding together with the mvvm or mvp pattern. This is a really clean solution and very easy to extend. If you just want to create a small simple application you'r fine using MVC Pattern without databinding. If you have existing generic bindingadapters which can be used from other projects you may want to use databinding, because its easy to reuse this code.
Data binding, concept wise looks promising to me, but I do not like the implementation part.
I would appreciate a bit more simpler and direct approach to it.
Thus I feel lot more comfortable in keeping it old school.
Model classes, mutable objects, observers feel like too much to me, if some how the data variables used for binding are received as Objects that are mutable and observable directly in a class , then that would make the process lot more cleaner, simpler and concise.

Protection from reflection - android

Even a private member/function of my class can be accessed by reflection by using setAccessible(true). Is there a way to prevent this kind of access from outside code?
I read something, here on stack-overflow, that I can use SecurityManager for prevention of reflection in applets(not sure how it works, though), but is there a similar mechanism for Android as well? Maybe an annotation or clever-programming?
Taking a step back, what you're observing is a difference in security philosophy, between the Java execution model as originally embodied in JVMs at Sun and the execution model of Android.
The original Java VM design was intended for a system wherein multiple, mutually-suspicious applications (or "applets" in the Java parlance) would simultaneously inhabit a single address space, running in a single VM. Because the designers didn't want one app to be able to mess with another, they went through great pains to define an intra-VM security model that would disallow things such as one object touching the private fields of another object of a different class.
That said, the Java library ended up having various "escape hatches" out of the security model. One of those is setAccessible() on reflection objects, as you note.
Android's model is different: Android uses processes as the security boundary and unit of application isolation, instead of trying to insinuate it into the process as was done with traditional JVMs. This renders moot the entirety of the Java security model, except in that it helps an application "save it from itself." That is, it's good design to not have an object poke into another object's private parts, and the default Java security model provides just that.
Leaving aside the question of people modifying your code, with Android, as an application author, you control all the code that ends up running inside the process of your app. If you choose to include code that calls setAccessible() that's your business. You might be shooting yourself in the foot, but you certainly won't be shooting any other apps' feet, since the Android security model, running as it as at the layer of processes, inherently doesn't let that happen. Likewise, using native code will totally break you out of the Java object model, which allows for the possibility of things going totally higgledy-piggledy in the process but also allows you to express some things in a more productive manner than you could in Java. It's a trade-off, but it's a per-application-developer tradeoff and not one that particularly impacts anything else that's happening on your phone / device.
I know this doesn't directly answer your question, but I hope it provided some useful context.
Is there a way to prevent this kind of access from outside code?
Not really.
is there a similar mechanism for Android as well?
Even if there is (and I am not aware that such a thing exists), anyone can remove it, by decompiling your code (assuming they do not have your source already), getting rid of the protection, and recompiling the code.
Bear in mind that ProGuard, when used properly, will obfuscate your private classes and methods for your production APK builds. That, plus a lack of documentation, will make it tedious for anyone to gain access to those private classes and methods.
I don't believe that you can ever really 100% protect from users using reflection on your project with malicious intent. You can make it more difficult for users to do it by doing things like obfuscating your code, but it is still possible to reflect on the obfuscated code.
I don't believe SecurityManager can be used for the purpose that you are suggesting, though I could be wrong.

Benifits of implementing MVC in Android

I want to implement MVC in my Android application for reasons I have heard but not realized. Can anyone lead me to implement MVC in my application? Kindly mention the benefits for using the same.
Thanks
The key benefit of MVC (and its variations) in general and not only for Android is separation of concerns. This means you keep business logic isolated in the Model instead of mingled with the presentation logic. In turn the Model becomes easier to unit test, modify, and reuse (when reuse is a concern at least).
I'm not sure if there is much sense in testing the View or Controller parts of MVC. The View for one thing is supposed to be as much 'dumb' as possible, to the point of lacking even presentation logic.
MVC apparently has trouble telling where the presentation logic belongs to -- this seems to be the reason why MVP has been created, so all this logic goes to the Presenter. So by using MVP instead of MVC you would also have the benefit of easily testable presentation logic.
MVC also allows (in theory at least) to change the user interface adopted by the application, though I'm not sure how this applies to Android (maybe for games?).
Needless to say, Android apps DO NOT implement MVC by design. Otherwise those benefits would be available to Android apps by design, which is not true.
It's already implemented as per this post here: MVC pattern on Android
For one thing, it allows you to plug in a different algorithms or data store/source into your app with a single line of code. So in my sample Android app, I can switch from DES, to AES to TDES encryption in one line of code. It allows you to port your algorithm to another app with a completely different user interface and architecture. So in .NET I can write a Windows Form app and then port it to a Web Form app without re writing the core algorithm code. If you are looking for an example in Android I have a complete example here. If you can read C# code I have an example here.
Have fun.
JAL
Java has very powerful features behind it. The word MVC means at the bottom line, basically, componentization. Components are a very important definition in a OOP language like Java, and even more important to languages that implement memory allocation and handling like Java with the GC (Garbage Collector).
There's lots of GC algorithms & types implemented out there, each JVM has it's own number of sets, Oracle has it's own, IBM, Apache's OpenJDK, and so on and on. But the concept is almost every time the same: reference counting. Let's picture an example where you have an object A, that define a property of type B, and this class B has also a property to another class called C, and they are all in the same processing scope (e.g. a method). Analysing this example, the runtime (JVM) could only release "B" after "C" is out of scope (out scoped), and also "A" could not be liberated because of "B" being used by the same scope. Putting this in perspective, the scope modifiers, methods, classes, static methods and classes, final declarations, everything needs to be carefuly chosen.
Summing all together, that means not only you get a more well organised code using patterns like MVC, but also more performance in the JVM runtime, because depending on the size of your program, your GC pool can really be a bottom-neck, and fine grained java code, with methods with a just few lines divided by a few number of classes, will always perform better. Huge classes, with just a few methods with a lot of lines of code within, tend to perform poorly.
... and that's the beauty of things. MVC not only gives a more well organised code, but also, more performance. Hope it helps!

Android private fields naming guidelines are ok?

Here http://source.android.com/source/code-style.html#follow-field-naming-conventions it is stated that :
Field Names
Non-public, non-static field names start with m.
Static field names start with s.
Other fields start with a lower case letter.
Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.
It also states that :
The rules below are not guidelines or recommendations, but strict rules. You may not disregard the rules we list below except as approved on a need-to-use basis.
I don't like the "m" convention before private or package fields in a class. I really find this uninspired... I mean, if we try to apply good designs, the low coupling of the classes implies having few public fields. actually, in my programs I usually have no public fields, even when I need some I use getters and setters...
So, why should I be forced to have almost all my fields in the program with an "m" in front of them? wouldn't be easier to have the few public fields, if there are any, with some "g" in front or something? or just use setters and getters as beans suggest?
this really makes my code harder to read....
Also, following these guidelines, local temp variables used in the methods have no restriction so they could easily be mistaken for public global fields (also without restriction)... this also I find to be wrong, as it is a probable source of mistakes...
I understand to have a way of differentiating from fields, but private/protected member fields are the most used in an application, they shouldn't be less "readable".
What do you think? Should I follow the guidelines?
Those coding guidelines are for the Android Open Source Project which is the core Android Platform. You have to follow these guidelines if you want any of your code to be accepted into the core platform. You can do what ever you want in your own applications.
With regards to the guidelines themselves I think they are very reasonable and similar to many standards used in commercial applications. Generally you want to use getters and setters for public field access and you don't want to have global public variables. Only global public constants are ok.
So the short answer is follow them for the Open Source project, decide to follow them in you app.
In regards to getters\setters, it is actually recommended to not use them in Android.
I found this on the "Designing for Performance" page (section: Avoid Internal Getters/Setters): http://developer.android.com/guide/practices/design/performance.html
Bottom line, they infer that instance field lookups are more efficient than Virtual method calls (due to optimizations in the JIT).
I think I will continue to use getters\setters in my code, but this might be an easy way to improve performance (especially for apps that do a lot of data manipulation).

Categories

Resources