Smell Detail

Alternative Classes with Different Interfaces

异曲同工的类

Object-Orientation Abusers

Two classes have similar functionality but different interfaces.

Define

Introduction

When two classes do the same thing but have different method names, this smell occurs. It increases learning costs and maintenance difficulty, and violates the principle of consistency.

Key Identifiers

  • Two classes provide similar functionality
  • Method names differ but functionality is the same
  • Parameter types or order are inconsistent
  • Increases learning costs for users

Refactoring Suggestions

  1. Unify Interfaces: Ensure similar classes implement the same interface
  2. Rename Methods: Use consistent naming conventions
  3. Extract Superclass: Create a base class for shared behavior
  4. Merge Classes: If functionality is identical, consider merging them

Explanation

These two classes do the same thing but with different interfaces. The interfaces should be unified or the classes merged. This reduces learning costs and improves code consistency.

Code Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.*;
import java.nio.file.*;
class FileReader {
public String readFile(String filename) throws IOException {
return new String(Files.readAllBytes(Paths.get(filename)));
}
public boolean fileExists(String filename) {
return Files.exists(Paths.get(filename));
}
public long getFileSize(String filename) throws IOException {
return Files.size(Paths.get(filename));
}
}
class DocumentLoader {
// Same functionality but different method names
public String loadDocument(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)));
}
public boolean documentExists(String path) {
return Files.exists(Paths.get(path));
}
// Different parameter order and return type
public int getDocumentSize(String path) throws IOException {
return (int) Files.size(Paths.get(path));
}
}