You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何传递类对象复用通用方法?消除重复if-else代码求助

Solution: Use a Common Interface + Polymorphism

Absolutely, you can fix this messy if-else duplication with polymorphism and interfaces—this is exactly the kind of problem OOP was designed to solve. Let me walk you through how to refactor this step by step.

Step 1: Define a Common Interface

First, create an interface that declares all the methods and properties (exposed via getters) your repeated code uses. This acts as a shared contract for all your lookup classes:

public interface Lookupable {
    // Methods your code calls directly
    void loadClass(String fileToLookup);
    String[] getClassData();
    
    // Getters for member variables your code accesses
    int[] getPositionIds();
    String[] getPositionNames();
    boolean[] getPositionExpandableToMultipleBoolean();
    String expandablePositionIdToName(int index, String data);
}

Step 2: Make Your Classes Implement the Interface

Update CustomerClass and AddressClass (and any similar future classes) to implement this interface. For existing member variables, just add getter methods that return them:

public class CustomerClass implements Lookupable {
    // Your existing member variables
    int[] positionIds;
    String[] positionNames;
    boolean[] positionExpandableToMultipleBoolean;

    // Implement all interface methods
    @Override
    public void loadClass(String fileToLookup) {
        // Keep your original loadClass logic here
    }

    @Override
    public String[] getClassData() {
        // Keep your original getClassData logic here
        return ...;
    }

    @Override
    public int[] getPositionIds() {
        return positionIds;
    }

    @Override
    public String[] getPositionNames() {
        return positionNames;
    }

    @Override
    public boolean[] getPositionExpandableToMultipleBoolean() {
        return positionExpandableToMultipleBoolean;
    }

    @Override
    public String expandablePositionIdToName(int index, String data) {
        // Keep your original logic here
        return ...;
    }
}

Repeat this for AddressClass—it will follow the same structure with its own internal logic.

Step 3: Create a Factory Method to Get the Right Instance

Instead of creating class instances inside if-else blocks, use a factory method to return the correct Lookupable implementation based on the folder:

private Lookupable getLookupInstance(String databaseFolder) {
    if (databaseFolder.equals(CustomerFolder)) {
        return new CustomerClass();
    } else if (databaseFolder.equals(AddressFolder)) {
        return new AddressClass();
    }
    // Handle unknown folders (throw an exception or return a default)
    throw new IllegalArgumentException("Unsupported folder: " + databaseFolder);
}

Step 4: Extract Repeated Logic to a Single Method

Now you can move all that duplicated code into one method that accepts a Lookupable instance. Since Lookupable defines all the methods/properties we need, the compiler will recognize them without issue:

private void processLookupData(Lookupable lookup, String fileToLookup) {
    lookup.loadClass(fileToLookup);
    
    String[] tempString = new String[lookup.getPositionIds().length * 2];
    String[] tempExpandString = new String[lookup.getPositionIds().length];
    String[] classData = lookup.getClassData();
    String[] positionNames = lookup.getPositionNames();
    boolean[] expandableFlags = lookup.getPositionExpandableToMultipleBoolean();

    for (int i = 0; i < lookup.getPositionIds().length; i++) {
        tempString[i * 2] = positionNames[i];
        
        if (expandableFlags[i] && classData[i] != null && classData[i].contains(",")) {
            tempString[i * 2 + 1] = "Multiple- Click to Expand";
            tempExpandString[i] = classData[i];
        } else if (expandableFlags[i]) {
            tempString[i * 2 + 1] = lookup.expandablePositionIdToName(i, classData[i]);
            tempExpandString[i] = classData[i];
        } else if (classData[i] == null) {
            tempString[i * 2 + 1] = " ";
        } else {
            tempString[i * 2 + 1] = classData[i];
        }
    }
    
    list = tempString;
    filesToExpand = tempExpandString;
}

Step 5: Replace If-Else Blocks with Clean Calls

Finally, replace all your messy if-else code with two simple lines:

Lookupable lookup = getLookupInstance(databaseFolder);
processLookupData(lookup, fileToLookup);

Why Your Original Approach Failed

When you passed an Object to your lookupclass method, the compiler only knew it was an Object—which doesn't have methods like loadClass or fields like positionIds. By using the Lookupable interface, you're telling the compiler "this object has all the methods we need", so it can resolve the calls correctly.

Bonus Benefits

  • Less duplication: You only maintain the processing logic once.
  • Easier to extend: Add a new lookup class? Just implement Lookupable and add a case to the factory method—no need to copy-paste processing code.
  • Cleaner code: Your main logic focuses on what you want to do, not checking which class to use.

内容的提问来源于stack exchange,提问作者Rich Fedor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:55:19