Sugar : Android database made easy.

UPDATE : Some of the code snippets in the below post are outdated. Please visit http://satyan.github.com/sugar/ for latest updates to the library.

This post is an introduction to Sugar library for android. The aim of the project is to simplify database access in Android.

The project draws inspiration from GORM for grails or Active Record for Rails. These patterns have been hugely successful in the web world, and have set a benchmark for libraries for database access.

The basic objectives of the library  are:

1. Creation and management of database and connection.

2. Simple and Intuitive API for database querying.

3. Simple CRUD operations.

Source Code

Source code is present at https://github.com/satyan/sugar

You can clone it and start hacking. There’s a build script along with it to compile and generate the binary.

An example project using the library is present at https://github.com/satyan/SugarExample

Usage

Android Manifest file: 

Include the android:name attribute in the application tag. SugarApp extends android’s Application and initiates the database creation for the project. By including the attribute, you’re basically starting with SugarApp instead of android’s Application class. If you intend to write your own Application class, you can extend SugarApp.

<?xml version="1.0" encoding="utf-8"?>
<manifest..>
<application.. android:name="com.orm.SugarApp">
.....
</application>
</manifest>

Entities
The entities need to inherit from SugarRecord including a typed parameter. SugarRecord provides for all the CRUD methods that will be available to the entity classes.

public class Note extends SugarRecord<Note>{
private String title;
private String description;
public Note(Context context){
super(context);
}
...
}

Thats about it. Configuration is done. You’re ready to dive into the sweetness of Sugar. (OK.. I couldn’t stop myself from saying this.)

# inserting values

Note note = new Note(context, "Note 1");
note.save();

# query

Note.findById(context, Note.class, 1);
Note.find(context, Note.class, "title=?", new String[]{"Note 1"});

# delete
Note note = Note.findById(context, Note.class, 1);
note.delete();

# few more..

Note.listAll(context, Note.class);
Note.deleteAll(context, Note.class);

Nice.. All done. Happy Android hacking.

Protect your dear ones

Many times you encounter code that reads as follows:


public class OuterClass{

private ContainedClass containedClass;

public ContainedClass getContained(){

return containedClass;

}

}

public class ContainedClass{

public void someMethod(){

// Do something

}

}

Typical usage:


// Usage of the class

OuterClass outerObj = new OuterClass();

ContainedClass containedObj = outerObj.getContained();

containedObj.someMethod();

This is a very common pattern and you’d have surely witnessed it in some form or another. There is something essentially wrong with it. Before I begin, Let me tell you a real life instance first:

Imagine you have a girlfriend. Hmm.. for most of us this is easy. We’ve always only imagined a girlfriend 🙂

Back to the point. Lets say you have a girlfriend. A buddy of your calls one day and asks you for her details.

Your obvious response would be “What do you need to do with her?”

He says he has nothing wrong in mind, he just needs to check on something.

Your response “Tell me what you want checked.. I’ll check and let you know”.

This would be a very typical case of how you’d react on that kind of a request. What are you doing here? You’re trying to protect her from exposing it outside, fearing it may harm her or cause her some trouble. You abstract her out from your friend and act as her messenger at times.

Now lets look back at our piece of code above.

1. The OuterClass contains an instance of ContainedClass.

2. It exposes it completely through the method getContained()

But thats not the kind of thing you did in real life.. didn’t you. You abstracted out the details from the friend who called you up.

You need to follow a similar approach here. Lets have a look at this piece of code. (With the ContainedClass remaining same)


public class OuterClass{

private ContainedClass containedClass;

public void someMethod(){

return containedClass.someMethod();

}

}

Typical usage:


// Usage of the class

OuterClass outerObj = new OuterClass();

outerObject.someMethod();

Here you have abstracted out ContainedClass from rest of the world. It can only be accessed through the OuterClass.

It is also referred to as ‘Law of Demeter”

It has many advantages:

1. It helps build more cohesive units and loosely coupled components.

2. The implementation details are hidden from outer world and can be easily modified if needed.

3. The dependencies on the calling objects are limited. It only depends on OuterClass now.

4. Testing is far easier, since you have less dependencies to satisfy.

Hope you found it useful. Do share if you have any thoughts on the above.

Object Builder alternative

Its a fairly common discussion and usually solved by

1. Constructors

MyObject(String name, String blog){
   this.name = name;
   this.blog = blog;
}

Usage:

new MyObject("Satya", "onSoftwareAndStuff");

There is a small issue with it. During creation of the object, the parameters “Satya” and “onSoftwareAndStuff” do not say what they are.  One of the alternatives with dynamic languages is (with Groovy)

 new MyObject(name : "Satya", blog : "onSoftwareAndStuff");

This is much more readable as it says.. name is Satya and blog is onSoftwareAndStuff.

2. Setters

MyObject(){
}
public void setName(String name){
     this.name = name;
}
public void setBlog(String blog){
     this.blog = blog;
}

Usage:

MyObject obj = new MyObject();
obj.setName("Satya");
obj.setBlog("onSoftwareAndStuff");

This is more readable but spreads into multiple lines and repetition of variable “obj” and method ‘set*’ is uncomfortable.

3. Alternatives

To achieve the readability equivalent to the groovy construction, lets try the following alternative:

MyObject(){
}
public MyObject name(String name){
     this.name = name;
     return this;
}
public MyObject blog(String blog){
     this.blog = blog;
     return this;
}

Usage:

MyObject obj = new MyObject().name("Satya").blog("onSoftwareAndStuff");

Probably for a 2 parameter constructor this is an overkill.. but if there are more parameters, this looks a fairly feasible solution.

Any thoughts?

Inherit or compose.. Hmm..

When designing your domain/classes, this is one decision that always results in conflicts within teams. Whether to inherit from a class or to compose that class. This is fairly subjective but here are few pointers for discussion..

Lets take this code for example:

public class GiftCollection extends HashSet {

    public Gift getRandomGift(){
        List giftList = new ArrayList(this);
        Collections.shuffle(giftList);
        return giftList.get(0);
    }
}

It is a collection of gifts that is represented as a set. The additional behavior from a set is that it can give you a random gift. It looks fairly straight-forward and would work in a even more straight-forward manner. Lets look at a usage of this..

public class GiftSelector {

    GiftCollection giftCollection;

    public GiftSelector(GiftCollection giftCollection) {
        this.giftCollection = giftCollection;
    }

    public Gift selectRandomGift(){
          return giftCollection.getRandomGift();
    }

}

This is a basic usage of the GiftCollection provided earlier. If one looks closely, though the two classes look very similar and doing similar things, there are basic differences between the two.

GiftCollection inherits a HashSet and extends to the behaviour by adding another method getRandomGift to it. However GiftSelector decided to contain a GiftCollection and delegate few calls to it.

I’ve always preferred the latter approach for following reasons:

1. The classes (both superclass and subclass) are much more flexible to change.

In this case, if GiftCollection decides to change the signature of the method getRandomGift(), it would not have an effect on the callers of GiftSelector, since it wraps the method call.

But any change to the Set implementation would affect the api of the GiftCollection class, without its knowledge. The users of GiftCollection have to change their code, though there has been no apparent change to the class. This is not an ideal scenario.

2. Easier to test.

It clearly shows that GiftSelector is much easier to test than GiftCollection. One can easily mock the dependency of the class and unit test the code. Whereas, in the case of inheritance, most mocking libraries do not provide a way to mock super classes. So its difficult to test in isolation.

3. Polymorphism through Interfaces is more flexible

One of the reasons for inheritance has been to reduce code and take advantage of polymorphic behaviour. Interfaces provide a more flexible way to achieve the same result. Composition coupled with Interfaces present a better alternative to achieve polymorphism.

This is not to say that one should not use Inheritance.

When modeling your domain, Inheritance should be used in case of a direct ‘is-a’ relationship. It should not be used only to achieve code-reuse or polymorphism.

Prefer composition over inheritance, unless you have good reasons to not do so..

Would love to hear your thoughts on this..

GWT architecture best-practices

Its an excellent video that lists down many interesting things: A must watch for UI archs.

Just to summarize few of the architecture points discussed in this (and my comments)
1. MVP pattern usage in GWT. (using gwt-presenter library probably) http://martinfowler.com/eaaDev/uiArchs.html
2. Dependency injection on client side (Google-gin (client-side) and Google-Guice(server side))
3. Event Bus (following event collaboration by martin fowler http://martinfowler.com/eaaDev/EventCollaboration.html)
4. Command Pattern (probably using gwt-dispatch)

Hope it helps.. Please share your understandings as well.