简体   繁体   English

Java-重构类似方法的代码

[英]Java - Refactoring the code of similar methods

I have a following problem: 我有以下问题:

I had a few methods that are basically used to get something from Salesforce. 我有几种方法基本上是用来从Salesforce那里获取东西的。

Here is an example: 这是一个例子:

 public Map<String, Customer> findSomethingByIds(String[] somethingIds) throws... {
     return binding.findSomethingByIds(somethingIds);
 }

For a number of reasons I needed to retry the execution of this method in a very rare cases (fe session expires etc.), so I used this . 由于多种原因,在极少数情况下(fe会话到期等),我需要重试此方法的执行,因此我使用了this

So now I have something like this: 所以现在我有这样的事情:

 public Map<String, Something> findSomethingByIds(final String[] somethingIds) throws ... {       
    Map<String, Something> myList = null;                
    Callable<Map<String, Something>> task = new Callable<Map<String, Something>>() {
        @Override
        public Map<String, Something> call() throws Exception {
            return binding.findSomethingByIds(somethingIds);
        }
    };

    RetriableTask<Map<String, Something>> r = new RetriableTask<>(2, 1000, task);
    try {
        myList = r.call();
    } catch (Exception e) {
        // Ex. handling
    }
    return myList;
}

Now, there are a lot of such methods in my code, so if I want to use the RetriableTask interface I have to add a lot of code to those methods, similar to the one above, which I want to avoid at all costs. 现在,我的代码中有很多这样的方法,因此,如果我想使用RetriableTask接口,我必须向这些方法中添加很多代码,类似于上面的方法,我想不惜一切代价避免这样做。 All those methods pretty much return something different, so I can't use a Factory here (or I don't know how). 所有这些方法几乎都返回不同的东西,所以我不能在这里使用Factory(或者我不知道如何)。 Does anyone know any solution for this? 有谁知道任何解决方案吗? Any help would be appreciated. 任何帮助,将不胜感激。

If you have a method doing something similar and the only difference is the return type, try using generics : 如果您有执行类似操作的方法,唯一的区别是返回类型,请尝试使用泛型

public Map<String, T> findSomethingByIds(final String[] somethingIds) throws ... {       

}

This will allow you to perform equivalent processing on different object types without copying and pasting code everywhere. 这将使您可以对不同的对象类型执行等效的处理,而无需在各处复制和粘贴代码。

Responding to the comments, if they take different parameter types, you can still use generics in the parameters. 响应注释时,如果它们采用不同的参数类型,则仍可以在参数中使用泛型。 If you mean they have a different number of parameters (ie, have a completely different signature), then you can create wrapper methods which perform the processing which is unique to that object type, and after that you can pass control to the generic method for the processing which is common to all object types. 如果您表示它们具有不同数量的参数(即,具有完全不同的签名),则可以创建包装器方法,该方法执行对该对象类型唯一的处理,然后可以将控制权传递给用于所有对象类型共有的处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM