Dynamic comparator or 2 separate comparators?

Advertisements

I’m working on a solution including 2 types of sorting based on a property. What do you think which one is a better approach?

public class ABComparator implements Comparator<O> {
    
    private final Property property;
    
    public ABComparator(Request request) {
        property = getProperty();
    }

    @Override
    public int compare(O o1, O o2) {
    if (property.someLogic()) {
        // 1 first type of sorting
    } else. {
        // another type of sorting
    }        
    }
}

or is better having 2 classes with their own logic and choosing one in the class where the sort is actually happening?

Thanks

>Solution :

Problems are exponential as you incorporate more mutations and more "choices" in your algorithms.

You can check what Sonarcloud thinks about cognitivity complexity and cyclomatic complexity. https://www.sonarsource.com/resources/cognitive-complexity/

To put it simply less choices, less state to manage will create more robust code and less bugs. Bringing 2 classes is low on complexity, especially if they don’t depend on anything else. Code volume added should be low. I personally would use 2 classes with 2 implementations that don’t share anything between themselves if possible so there is no if condition in your implementation of your compare function.

Leave a ReplyCancel reply