A Question about Good Practices in Android and Java Development
Good Morning (Afternoon, evening, i dunno what time it is when ur reading this .. lol but its 8:30 AM here :) )
I was yesterday in a Meetup about android programming and The presenter had a sample code about how to create an app with database access in android..
We talked about various classes, methods and so on.
Lets assume we have a table in the database called MyItem .. We create a class called MyItem.java that has the same fields (similar to object relational mapping concept).
Now the presenter created a class called MyItemList.java that goes like this
package androidenthusiasts.androiddbproject;
import java.util.ArrayList;
// The MyList class is used to store MyItem objects in an ArrayList
pu开发者_C百科blic class MyList {
public ArrayList<MyItem> mylist;
// NonParameterized Constructor - Called when class is created
public MyList()
{
mylist = new ArrayList<MyItem>();
}
// AddItem method
public boolean AddItem(MyItem item)
{
mylist.add(item);
return true;
}
// GetCount method
public int GetCount()
{
return mylist.size();
}
// getItem method
public MyItem getItem(int index)
{
MyItem item = null;
if (index < GetCount())
{
item = mylist.get(index);
}
return item;
}
}
This is an object that only has a list.. and all the methods implemented are in the ArrayList .. Is it a good practice to create a new object for this list? Is it better to define the ArrayList wherever you want to use it as an ArrayList? Or even more, should we create a class for MyItem that extends the ArrayList?
What do the masses of StackOVerFlow Think?
Thanks
I recommend against extending ArrayList to create MyList. It is better to prefer composition over inheritance. Especially built-in classes shouldn't be extended.
Defining a separate class instead of using an ArrayList has some advantages:
- You could easily add new methods to your class
- You can make your class implement an interface
In general it will be easier to add new functionality and maintain the code. Also the MyList class doesn't throw IndexOutOfBoundsException exceptions, but silently returns null instead.
No, this is not a good practice. If you want a list of MyItems, you just create an ArrayList
, or better yet, ArrayList<MyItem>
.
You could extend ArrayList if you wanted to add some functionality to it (for example, validate the fields in a MyItem before adding it, and throw an exception if it contains bad data). But most of the time, you can do what you want with the classes already provided in java.util.
Another thing - in the Java naming convention, you start method names in lower case.
精彩评论