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

Viewed 89

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);
1 Answers

Which option is better from a coding perspective??

My short answer to this question would be - Whatever you like the most. Because you call one more function, even though you won't (always) have a big impact on performance, there is some impact.

Mostly compiler will just inline your second function but if this doesn't happen then you are losing some performance. But I need to say that this is not that much and you won't even notice it if your code is nicely written.

What you want is to write code that is understandable and clean for everyone using it later and there is one other question here. Are there possibilities that your database query would need changes in keywords like 'Books'? It is always easier to change this in one place (1st option) than going through code and changing it more than once (search and replace - yes but still takes more time).

It is really up to you, both codes are nice. The second one is cleaner and easier to edit but the first one is more optimized (not that much).

More about calling functions from functions you can read here in this answer: https://stackoverflow.com/a/27875180/14759470

Related