简体   繁体   中英

How to refactor the return of a generic method to an interface and all its implementations

I would change the return type declared in an interface, which is implemented in 10 other about class method . I'm using eclipse as IDE , the signature of the current method is:

public List<T> findById(int id);

and what I need

public T findById(int id);

Regards, Santiago

As @ Andy Turner states in the comments you can't automatically refactor returning a list to returning one of the lists elements. However there are steps to take to do the interface refactoring safely.

  1. Rename the list returning method in the interface.

  2. For the most common solution, returning the first element for instance, use TDD to write the new object returning method in one of your implementations. The new method should call the old method, and return the new return type. Don't use the example below it is clearly unsafe and will lead to a stack dump at some point.

     @Override public T findById(int id){ List<T> res = findById(id); return res.get(1); } 
  3. Update the interface to include the new method signature.

  4. For each class that uses the same solution already implemented, copy and paste the new method written in step 2.

  5. For any other desired implementations repeat steps 2 and 4.

If the method was an abstract method on a baseclass the initial method in step 2 would be written on the base class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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