вівторок, 20 грудня 2011 р.

Using ORMLite in Android projects

Preamble:
(If you just want to start hacking right away please skip this philosophical piece and go straight to the Tutorial)
There are a lot of cases when it makes sense to store data in a mobile app. In iOS you have several ways to do it, including a powerful CoreData framework which allows persisting object graphs of a significant complexity.
In Android there are also several ways to do it, however the most advanced (in terms of flexibility and convenience) way to store structured data in Android is to use an SQLite relational database.

Probably everyone knows this, but still:
SQLite is basically a special file format and a set of APIs implemented in a library that ships with Android OS.  Like most relational databases management systems SQLite API allows to manipulate data with SQL queries.

The programming model in which one has to manipulate data with plain SQL queries inside the application business logic is tedious, inconvenient and outdated.  It should be forbidden to write spaghetti like code filled with SQL-queries in XXI century.  Even if you are completely forced to write SQL queries in code and if you are a good programmer - you will find yourself writing some sort of framework that encapsulates common query routines and allows you to easier do similar operations on different data entities.  What is more tedious, time-consuming and inconvenient - is dealing with SQLite API (anyone ever worked with SQLite C API ?).

The convenient programming model for me is:
- to be able to create/update objects in code and persist them by calling a method on a certain DB-manager object,
- to be able to fetch a set of objects with a certain predicate defined for one/several of the object's fields

This programming model is generally achieved with the help of any persistance/ORM framework such as Hibernate, however the latter is pretty heavy to be used in Android.  There is an excellent alternative called ORMLite.  As the name implies - it is a lightweight ORM framework, and it turns out to be well suited for Android.


Tutorial:
Let's do a simple tutorial that will help you get started with using ORMLite in your own project.
The full source code is hosted on GitHub: https://github.com/justadreamer/WishListManager.  I strongly encourage you to download the source code, import it to your Eclipse workspace and play with the ready-made app.  After this I advice to start the project from scratch in another IDE instance and use the source code only in case of uncertainty/confusion, otherwise following the tutorial steps.

вівторок, 4 жовтня 2011 р.

Logging in iOS projects

A standard NSLog function is a quite inconvenient way of doing logging - mainly for these reasons:

a) we are not able to easily turn it off in Release builds
b) NSLog does not show the function name / line number information before the output log message.

A good drop in replacement, which solves these problems is this set of macros, which were stolen by someone, who then shared it with me.  Original author of the macros I don't know, but I guess the link to this post removes some guilt from me.  And also the credit should probably go to this SO answer

So here is the (extended compared to original) set of macros we use in our projects:


#ifdef DEBUG  
 #     define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);  
 #else  
 #     define DLog(...)  
 #endif  
 // ALog always displays output regardless of the DEBUG setting  
 #define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);  
 //Convenience macros, to output just one value of certain type:  
 #define VLog(v) DLog(@#v @"=%@",v)  
 #define fLog(v) DLog(@#v @"=%f",v)  
 #define dLog(v) DLog(@#v @"=%d",v)  
 //Convenience macro to output CGRect value in a human readable format:  
 #define CGRectLog(v) DLog(@#v @"=(%f,%f,%f,%f)",v.origin.x,v.origin.y,v.size.width,v.size.height)  
 #define CGSizeLog(v) DLog(@#v @"=(%f,%f)",v.width,v.height)  
 #define CGPointLog(v) DLog(@#v @"=(%f,%f)",v.x,v.y)  

вівторок, 27 вересня 2011 р.

Keep the code clean (continued 1)

Continuing "keep the code clean" theme.  Here are tips on how to do automatic code cleanups in eclipse when doing Java development.  I started to use it on my current Android project recently.

субота, 17 вересня 2011 р.

Why is there no x86 native emulator for Android?

This is more of a complaint than a blog article. Nor it is a positive answer to the question stated in the title.
If you've developed apps for Android you probably faced the issue.  The Android emulators (especially Honeycomb 3.0 and post-Honeycomb 3.0+) run terribly slow.  The app is not testable in the emulator.  You are not able to develop it using emulator besides very basic functions.  What's the reason for this?
Turns out that this is because emulator takes a naive approach to emulating the device.  Naive meaning - it emulates the device using a virtual machine that translates ARM opcodes into x86 opcodes. It uses QEMU as a VM layer, which to make it even worst is single-threaded, so it runs all code on one core at the most.

Now if you have ever developed apps for Apple iOS - you know that your app usually runs 1000 times (the number is not precise of course) faster on the emulator on your x86-64, or PPC or whatever platform than on an actual device.  What's the reason?  Right, this is because the build in XCode is set up in such a way that it builds the same native app either for x86 or for ARM architecture - depending on whether you are building for iOS simulator or for the device.  iOS simulator is just a thin window-environment around the actual running app, which runs as a separate process natively on your CPU and can use as much resources of your machine as the machine can give it. For example there are no RAM constraints for an app running in the iOS Simulator - as opposed to the one running on the actual device - where it gets kicked for using too much RAM.  But the main idea as you can get - is to enable fast compile-test-edit-compile cycle.

For Android the architecture of the platform itself asks for an x86 native emulator.  This is because Android app is actually a bytecode which runs on a Dalvik VM - which is sort of a JVM.  So the app itself will not even need to be recompiled to be run on a Dalvik VM built for x86 architecture.  So my question and complaint to Google is stated in the title: "Why is there no x86 native emulator for Android?".  Why Google makes us suffer and struggle with an emulator slower than any box out there?  Are there any obvious reasons why they can not dump the stupid QEMU?  I understand QEMU was a quick and dirty approach at first stages, but right now as the platform has grown and they so want to beat iOS on the market - they could at least help the developers in a great way by creating a fast emulator.

And I am not alone - in this stackoverflow post a person struggles with the same thing and likes to be able to use an Android x86 port from www.android-x86.org to speed up things somewhat. So come on Google, help your devoted developers to live happier lives.

четвер, 14 липня 2011 р.

Keep the code clean

Dealing with a lot of projects that were developed in different times in my company by my former and current colleagues I usually come across a lot of code-garbage.  So far I've been able to identify and differentiate at least 7 types of code garbage (if you know more, please add in the comments).

1. Unneeded commented out pieces of code, or irrelevant textual comments.
2. Unneeded logging that was used for debugging of some issue at some point, and was not removed after the issue has been fixed.
3. Stale code which is not called from anywhere, left as a legacy after some refactoring.  Or some empty methods not actually doing any job.
4. Compiler warnings.  Not a really code pollution - but still pollutes the compiler output and you might miss some important warning.
5. Spelling/grammar errors in symbol names.
6. Methods or member functions with trivial implementation, which just calls super class implementation.
7. More than one class definition in a class file.

I have a strong opinion, that there is no legitimate reason why any of these types of code garbage should be kept in your code.  Even if you have a reason - this is just an excuse for not maintaining a good enough and consistent codebase.  Typically I hear these kinds of excuses:

1. "A commented out piece of code might be used sometime in the future, I commented it out, so that if I need it - I don't forget how I implemented something previously"
An answer to this is - in 99% of cases the commented out piece of code is just dangling there and is never used again.  Also there are version control systems - if you removed some code that you will really really need in the future - you will dig it out from history.  So really as I said - there is no reason to keep commented out code in the project.  This also has to deal with some autogenerated code (by your IDE for example) that you never use, but for some reason it is kept commented out and polluting the code.

2. "I fixed the issue, but left the debug logging in place so that I am able to see if something goes wrong" - in reality if something often goes wrong - you haven't really fixed the issue.  You can leave logging of exceptions or errors, but not additional logging of some regular control flow of the program which was used to help diagnose the issue.  So what I am saying here - when you start debugging a new issue - you spend more time reading irrelevant log messages instead of the ones dealing with the currently debugged issue.

3. For keeping the stale code in the project I can't even think of a typical excuse, so just simply don't do it.  Just delete the stale pieces of code.

4. There is no excuse for having warnings either.  Warnings - are errors.  Your code should compile clean and silently.  If anything is wrong it should stick out like a sore thumb - so you notice the warning and fix it right away.

5. When the variable or function name is spelled incorrectly - you spend some time on thinking why is it so.  What is worse - if you are a perfectionist like I am - you will have to correct the spelling error so it does not bother you again.  This will involve some refactoring or plain group replacement - and this where you lose your precious time.  So really when your mate does not care to spell the names correctly - he/she wastes your time.

6. Methods that just call super - are unneeded in most cases. If you have a correct inheritance implementation in your language - the superclass method will be called automatically - no need to override the implementation in order to just pass the execution to the same superclass method.

7. Some languages do not allow defining more than one class in a single source code file (like Java) - and for a good reason.  Are you saving the space in your FAT?  I don't see any other reasons why you should keep several class declarations/definitions in a single file.  The class is a granular entity - it should be in a different file (different compile module for such languages like C#/Java/C++/ObjC).  It also means that probably your classes are so coupled that should be used only together, then why are they separate classes?  Or if I want to use always both of them, why one of them is not aggregating another one and presenting interface to its services?  This might go deeper into semantics and not just the layout of your code.

Code pollution harms readability, maintainability and the beauty (if any) of your code.
I tend to be violent about any code-garbage I encounter.  Whether it is my own left-over or somebody else's.  In somebody else's codebase (actually if you started working on it - it is already yours as well) you tend to try being more gentle and careful.  You start to think: maybe this commented out piece of code - was meant for something, or maybe the original author wanted at some point reuse it or anything, or maybe this logging was important to the original author.  Don't even spend time on thinking that.  Don't hesitate.  Just kill that piece of garbage and that's it.  You'll do good to everyone - to yourself and your successors who will inherit this code from you.

So what I really would like to see - is the clean code.  Every unneeded piece of junk pollutes the code and makes it harder to read and modify.
The best is when you take the codebase and it
a) builds without warnings, silently
b) produces no (or very small) debug output - and if any - only in case of errors or exceptions
c) has no commented out pieces of code, and all the comments it has are relevant textual comments
d) has no stale pieces of code - if the code is there - it should be called at some point of execution
e) the function/variable names are spelled correctly not destructing your clear mind
f) contains no trivial methods that only call super
g) each class declaration/definition is in a separate file