简体   繁体   中英

interface is implemented by thousands of classes so if changes occurs in interface then how to reduce it

There is scenario where I have Interface X, which has been implemented with my thousands of classes. Now I want to add new method in that Interface X. So how to make the changes in minimal way to solve the problem of overridden of methods in all my classes

If the method implementation is common to all classes, maybe an abstract class is better then interface for it.

If it isn't - you are going to write these methods anyway.


(*)It was initially a comment, but I was requested to put it as an answer.

  1. If your new method doesn't make sense for all implementations of that interface, don't add it there - make a new interface that extends your original one
  2. If there should be a default implementation for all your thousand classes - change your interface to an abstract clas

Apart from the other suggestions (make it abstract or extend the interface ) there is one further option:

Make all implementers of the interface extend a base class. This way, when you add methods to the interface you merely need to add default behaviour to the base class and class-specific behaviour to (hopefully) just a few implementers.

If you don't mind having no-op implementation of this method in all your classes and have control over all implementing classes, here is a very hacky way to do it with IntelliJ in 3 steps without going to each and every class:

  1. Add your method to an interface
  2. Select a method and invoke Refactor->Push Down... - your method declaration will appear in all the classes that implement this interface, but at least in my version of IntelliJ IDEA (11.0.2) they will have no implementation, eg void doSomething(); , so select this definition and do a full-project Find & Replace to replace this string with your default implementation, for example,

    @Override void doSomething() {}

  3. Add your method to interface again.

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