mercredi 1 mars 2017

SQL specification in repository pattern

I just read this article http://ift.tt/2mcMHzu he only few methods in his repository and one method query(SqlSpecification $specification). He creates object for each Query he needs. here is the codes:

the repository class ( i only mention the query method):

@Override
public List<News> query(Specification specification) {
    final SqlSpecification sqlSpecification = (SqlSpecification) specification;

    final SQLiteDatabase database = openHelper.getReadableDatabase();
    final List<News> newses = new ArrayList<>();

    try {
        final Cursor cursor = database.rawQuery(sqlSpecification.toSqlQuery(), new String[]{});

        for (int i = 0, size = cursor.getCount(); i < size; i++) {
            cursor.moveToPosition(i);

            newses.add(toNewsMapper.map(cursor));
        }

        cursor.close();

        return newses;
    } finally {
        database.close();
    }
}

the SQL specification:

public class NewestNewsesSpecification implements SqlSpecification {

@Override
public String toSqlQuery() {
    return String.format(
            "SELECT * FROM %1$s ORDER BY `%2$s` DESC;", 
            NewsTable.TABLE_NAME, 
            NewsTable.Fields.DATE
    );
}
}

and he create object for every new sql he needs, such as newsById($id) and so on....

in the newbie's sight like me, it seems interesting but I am afraid this is not a good practice to follow.

my question is simple, is this good practice and worth to follow?

Aucun commentaire:

Enregistrer un commentaire