简体   繁体   中英

What code design should I use in this case?

Let's suppose I have following code (two almostly similar methods is the API requirement):

method1() {
  ...
  internalMethod();
  ...
}

method2() {
  ...
  internalMethod();
  ...
}

internalMethod() {
  ...
  internalMethodHelper();
  ...
}

internalMethodHelper() { ... }

And suppose I need to add new one method3() , which implementation requires another signature for internalMethod() and internalMethodHelper() .

So, as I think, there is only one way to resolve this situation:

method1() {
  ...
  internalMethod(sign1);
  ...
}

method2() {
  ...
  internalMethod(sign1);
  ...
}

method3() {
  ...
  internalMethod(sign2);
  ...
}

internalMethod(sign1) {
  ...
  internalMethodHelper(sign1);
  ...
}

internalMethod(sign2) {
  ...
  internalMethodHelper(sign2);
  ...
}

internalMethodHelper(sign1) { ... }

internalMethodHelper(sign2) { ... }

Am I right ? Or it's a very bad code design to overload methods in this case?

Thanks for all of your answers!

In this case Strategy pattern might help you.

It's better explained by Strategy Design Pattern - GOF that states:

The strategy pattern is a design pattern that allows a set of similar algorithms to be defined and encapsulated in their own classes. The algorithm to be used for a particular purpose may then be selected at run-time according to your requirements.

The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time .

This allows the behaviour of a program to change dynamically according to configuration details or user preferences.

It also increases flexibility by allowing new algorithms to be easily incorporated in the future.

在此处输入图片说明

IMHO Method Overloading is not Code Smell . If your need is to overload method in this context then do it. Design Patterns are tools not rules. They should be used wisely & must not be forced.

Also, if you write new class & put that method in it then ask these questions to yourself.

  • Does the new class does what it says?

  • Does the method written in it do what it says?

If yes, then can extract method & put in other Type. Otherwise stick with overloading, there is nothing like bad design here.

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