jeudi 3 décembre 2020

Multiple specific public methods calling a private method or a single generic public method?

I'm not sure how to name this question but I tried my best. We have a table in the database with rows representing mappings, each row has a string column that specify what object corresponds to. For example some rows have 'Books' in that column, others have 'CDs', other have 'Paintings' etc.

We want to retrieve all rows associated to a specific kind of object, for example all rows associated with 'Books'. We have a class that serves that table.

We have two ways to write that class. Which option is better? (some Option 3 maybe? There is no preferred way? It doesn't matter? Genuinely curious.)

Option 1

public TableClass {
    public List<Field> getBooksFields() {
         return getFields('Books');
    } 
    
    public List<Field> getCDsFields() {
         return getFields('CDs');
    } 
    
    ...etc...
    
    private List<Field> getFields(String name_of_field) {
         return tableRepository.getRowsWithType(name_of_field);
    } 
}

And then everywhere in the code where we want to get the fields associated to books, we can just do:

List<Field> bookFields = tableClass.getBooksFields();

Option 2

public TableClass {
    public List<Field> getFieldsWithType(String name_of_field) {
         return tableRepository.getRowsWithType(name_of_field);
    } 
    
    ...
}

And then hardcode in a Constants static class, the name associated to each field in the database. So we would do:

import Constants.BOOKS_FIELD_NAME;

...

List<Field> bookFields = tableClass.getFields(BOOKS_FIELD_NAME);

Aucun commentaire:

Enregistrer un commentaire