0
\$\begingroup\$

I find myself using this bit of code very often when I am retrieving the results from a Cursor

SearchItem searchItem = new SearchItem();
searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));
searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));
searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));
searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));

Specifically this could be when I am using a CursorAdapter for a ListView and in a DAO object.

What would be a useful design pattern to use in this case?

My first instinct is to have a singleton class which does this. Are there any problems in taking this route?

\$\endgroup\$
5
  • \$\begingroup\$ I see I was voted down. I am always open to hear why this is a bad question \$\endgroup\$ – jiduvah Oct 3 '13 at 2:41
  • \$\begingroup\$ Not sure, but perhaps the voter believed that this type of question leads to discussions of "equally-right" answers, which is discouraged by SO (see stackoverflow.com/help/dont-ask). \$\endgroup\$ – Paul Burke Oct 3 '13 at 3:46
  • 1
    \$\begingroup\$ I didn't realise it was one of those questions. Maybe I should try something and post on codereview \$\endgroup\$ – jiduvah Oct 3 '13 at 3:55
  • \$\begingroup\$ Is those five lines exactly the same when you write them? \$\endgroup\$ – Simon Forsberg Nov 22 '13 at 1:07
  • \$\begingroup\$ yes exactly the same \$\endgroup\$ – jiduvah Nov 25 '13 at 3:09
2
\$\begingroup\$

I am not completely sure if your question is as easy as it sounds (or if I am missing something), but here's my thought on things.

Using a singleton class for this does not make much sense in my opinion. There's no state to be stored, and therefore there's no need for an object at all. Instead, it sounds like you could put it in an utility method.

public static SearchItem createSearchItem(Cursor cursor) {
    SearchItem searchItem = new SearchItem();
    searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));
    searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));
    searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));
    searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));
    return searchItem:
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.