Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic comparator or 2 separate comparators?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading