Skip to content

Reduce code duplication across modules (8.83% / 8,239 lines) #3274

Closed

Description

@dbwiddis

Code Duplication Analysis

Tool used: jscpd (min-lines: 10, min-tokens: 50)
Scope: oshi-common/src/main/java, oshi-core/src/main/java, oshi-core-ffm/src/main/java
Results: 430 clones totaling 8,239 duplicated lines out of 93,352 (8.83%)

Duplication Breakdown by Category

Category Clones Duplicated Lines Priority
Cross-module (oshi-core ↔ oshi-core-ffm) 201 4,093 HIGH
Within oshi-core (Unix platforms) 112 2,359 MEDIUM
oshi-common ↔ oshi-core-ffm 31 759 HIGH
oshi-common ↔ oshi-core 22 457 LOW
Within oshi-common 19 379 LOW

Issue 1: JNA ↔ FFM Parallel Implementations (4,093 lines)

The largest source of duplication. JNA and FFM implementations share identical business logic (parsing, data transformation, getters) but differ only in how native functions are invoked.

Top Offending File Pairs

Dup Lines JNA File FFM File
295 oshi-core/.../mac/MacOSProcessJNA.java oshi-core-ffm/.../mac/MacOSProcessFFM.java
222 oshi-core/.../windows/WindowsGpuStatsJNA.java oshi-core-ffm/.../windows/WindowsGpuStatsFFM.java
189 oshi-core/.../windows/WindowsSensorsJNA.java oshi-core-ffm/.../windows/WindowsSensorsFFM.java
158 oshi-core/.../mac/MacGpuStatsJNA.java oshi-core-ffm/.../mac/MacGpuStatsFFM.java
123 oshi-core/.../WmiUtil.java oshi-core-ffm/.../WmiUtilFFM.java
106 oshi-core/.../windows/WindowsNetworkIfJNA.java oshi-core-ffm/.../windows/WindowsNetworkIfFFM.java
96 oshi-core/.../windows/WindowsCentralProcessorJNA.java oshi-core-ffm/.../windows/WindowsCentralProcessorFFM.java
90 oshi-core/.../mac/MacPowerSourceJNA.java oshi-core-ffm/.../mac/MacPowerSourceFFM.java
71 oshi-core/.../windows/WindowsGraphicsCardJNA.java oshi-core-ffm/.../windows/WindowsGraphicsCardFFM.java
68 oshi-core/.../windows/WindowsPowerSourceJNA.java oshi-core-ffm/.../windows/WindowsPowerSourceFFM.java
67 oshi-core/.../mac/MacFileSystemJNA.java oshi-core-ffm/.../mac/MacFileSystemFFM.java
62 oshi-core/.../windows/WindowsFileSystemJNA.java oshi-core-ffm/.../windows/WindowsFileSystemFFM.java
60 oshi-core/.../windows/WindowsFirmwareJNA.java oshi-core-ffm/.../windows/WindowsFirmwareFFM.java

Existing Good Pattern to Follow

The WMI drivers already solve this correctly. For example, Win32BaseBoardJNA.java and Win32BaseBoardFFM.java each differ by only ~5 lines because shared logic lives in a common Win32BaseBoard base class:

// Win32BaseBoardJNA.java (entire meaningful diff from FFM version):
import oshi.util.platform.windows.WmiQueryExecutorJNA;
public final class Win32BaseBoardJNA extends Win32BaseBoard {
    return Win32BaseBoard.queryBaseboardInfo(Objects.requireNonNull(WmiQueryExecutorJNA.createInstance()));
}

Fix Strategy for Issue 1

For each JNA/FFM pair listed above:

  1. Identify the shared business logic (parsing results, building data structures, getter methods)
  2. Extract that logic into a new abstract base class or shared utility in oshi-common
  3. Leave only the native call dispatch (JNA Native.load / FFM Arena + Linker) in the platform-specific subclass
  4. Both JNA and FFM classes should extend the new common base

Example for MacOSProcessJNA/MacOSProcessFFM: The 117-line block at JNA:243-359 / FFM:287-403 is identical except for 2 lines (Native.getLastError() vs omitted, and new Resource.Rlimit() vs Arena.ofConfined()). Extract the surrounding process-attribute-parsing logic into a shared method that accepts the native results as parameters.


Issue 2: Getter Boilerplate Not in Abstract Base Classes (~1,500 lines)

Multiple platform implementations repeat identical @Override getter methods that should live in abstract base classes.

OSFileStore (7 implementations × ~57 lines each)

Files affected:

  • oshi-core/.../unix/aix/AixOSFileStore.java:27-83
  • oshi-core/.../unix/freebsd/FreeBsdOSFileStore.java:27-83
  • oshi-core/.../unix/openbsd/OpenBsdOSFileStore.java:27-83
  • oshi-core/.../unix/solaris/SolarisOSFileStore.java:27-83
  • oshi-core-ffm/.../windows/WindowsOSFileStoreFFM.java:26-83
  • oshi-core/.../mac/MacOSFileStoreJNA.java
  • oshi-common/.../os/linux/LinuxOSFileStore.java
  • oshi-common/.../os/mac/MacOSFileStore.java
  • oshi-common/.../os/windows/WindowsOSFileStore.java

Duplicated getters: getLogicalVolume(), getDescription(), getType(), getFreeSpace(), getUsableSpace(), getTotalSpace(), getFreeInodes(), getTotalInodes()

NetworkIF (6+ implementations × ~61 lines each)

Files affected:

  • oshi-core/.../unix/aix/AixNetworkIF.java:66-126
  • oshi-core/.../unix/solaris/SolarisNetworkIF.java:58-118
  • oshi-core/.../unix/BsdNetworkIF.java
  • oshi-common/.../platform/linux/LinuxNetworkIF.java:75-145
  • oshi-common/.../platform/mac/MacNetworkIF.java:44-101
  • oshi-core-ffm/.../windows/WindowsNetworkIfFFM.java:58-143
  • oshi-core/.../windows/WindowsNetworkIfJNA.java:67-152

Duplicated getters: getBytesRecv(), getBytesSent(), getPacketsRecv(), getPacketsSent(), getInErrors(), getOutErrors(), getInDrops(), getCollisions(), getSpeed(), getTimeStamp()

HWDiskStore (5+ implementations × ~55 lines each)

Files affected:

  • oshi-common/.../platform/linux/LinuxHWDiskStore.java:119-173
  • oshi-common/.../platform/windows/WindowsHWDiskStore.java:70-90
  • oshi-common/.../platform/mac/MacHWDiskStore.java:51-105
  • oshi-core/.../unix/openbsd/OpenBsdHWDiskStore.java:106-172
  • oshi-core/.../unix/solaris/SolarisHWDiskStore.java:47-92
  • oshi-core/.../unix/freebsd/FreeBsdHWDiskStore.java

Duplicated getters: getReads(), getReadBytes(), getWrites(), getWriteBytes(), getCurrentQueueLength(), getTransferTime(), getTimeStamp()

Fix Strategy for Issue 2

For each interface (OSFileStore, NetworkIF, HWDiskStore):

  1. Add the duplicated fields to the existing abstract base class (AbstractOSFileStore, AbstractNetworkIF, AbstractHWDiskStore)
  2. Move the getter implementations into the abstract class
  3. Add a constructor or setter in the abstract class to initialize these fields
  4. Remove the duplicate fields and getters from all platform subclasses
  5. Subclasses only need to implement updateAttributes() and platform-specific factory methods

Issue 3: Unix Platform Duplication (FreeBSD≈OpenBSD, AIX≈Solaris) (~500 lines)

FreeBSD ↔ OpenBSD (nearly identical)

Dup Lines File A File B
86 FreeBsdOSProcess.java:188-273 OpenBsdOSProcess.java:225-397
69 FreeBsdOSThread.java:49-117 OpenBsdOSThread.java:49-109
38+35 FreeBsdOSProcess.java (2 more blocks) OpenBsdOSProcess.java
33 FreeBsdOperatingSystem.java OpenBsdOperatingSystem.java

Differences are minor: column names (LWP vs TID, TDNAME vs ARGS, ETIMES vs ETIME), command flags (-awwxo vs -aHwwxo), and a few platform-specific fields.

AIX ↔ Solaris (nearly identical)

Dup Lines File A File B
104 AixOSProcess.java:102-205 SolarisOSProcess.java:104-362
61 AixNetworkIF.java:66-126 SolarisNetworkIF.java:58-118
57 PsInfo.java (aix):171-227 PsInfo.java (solaris):184-240
51 AixOSThread.java SolarisOSThread.java

Fix Strategy for Issue 3

  1. Create BsdOSProcess abstract base in oshi-core/.../unix/ that holds the shared ps-parsing logic, with abstract methods for platform-specific column names and command flags
  2. FreeBsdOSProcess and OpenBsdOSProcess extend it, overriding only the platform-specific constants
  3. Same pattern for BsdOSThread
  4. Create SysVOSProcess or PosixOSProcess base for AIX+Solaris shared logic
  5. Extract common PsInfo logic into a shared base with type parameters for the platform-specific struct types (AixPsInfo/SolarisPsInfo)

Issue 4: FileUtil Internal Duplication (minor)

oshi-common/src/main/java/oshi/util/FileUtil.java has two readLines methods (lines 76-98 and 128-149) with identical file-existence-check and error-handling patterns.

Fix Strategy

Extract a private helper:

private static <T> T readFileWithErrorHandling(String filename, boolean reportError, 
        FileReader<T> reader, T defaultValue) {
    Path file = Paths.get(filename);
    if (Files.isReadable(file)) {
        LOG.debug(READING_LOG, filename);
        try { return reader.read(file); }
        catch (IOException e) {
            if (reportError) LOG.error("Error reading file {}. {}", filename, e.getMessage());
            else LOG.debug("Error reading file {}. {}", filename, e.getMessage());
        }
    } else if (reportError) {
        LOG.warn("File not found or not readable: {}", filename);
    }
    return defaultValue;
}

Implementation Notes

  • All changes should maintain backward API compatibility (public method signatures unchanged)
  • Run existing tests after each refactoring step: mvn test -pl oshi-common,oshi-core,oshi-core-ffm
  • The @ThreadSafe annotation pattern should be preserved on refactored classes
  • New abstract base classes should go in oshi-common so both oshi-core and oshi-core-ffm can depend on them
  • Consider tackling this in phases: Issue 2 (getters) first as lowest risk, then Issue 1 (JNA/FFM), then Issue 3 (Unix platforms)

Activity

  1. dbwiddis commented on May 20, 2026

    @dbwiddis
    MemberAuthor

    Progress Update

    Issue 2 (Getter Boilerplate) — Complete ✅

    PR #3275 pulled duplicated fields/getters into abstract base classes for:

    • OSFileStore (7 subclasses simplified)
    • NetworkIF (7 subclasses simplified)
    • HWDiskStore (6 subclasses simplified)

    Net reduction: ~1,188 lines of duplicated getter boilerplate.

    Issue 1 (JNA ↔ FFM Parallel Implementations) — High-value work complete ✅

    Remaining Issue 1 classes are all "hard" — native API calls deeply interleaved with business logic (WindowsSensors, MacGpuStats, MacOSProcess, WindowsGraphicsCard, PowerSource classes, WindowsCentralProcessor). These would require either new abstraction layers for native APIs or awkward parameter-passing patterns. The ROI is low relative to the complexity.

    Issue 3 (Unix Platform Duplication) — Deferred

    The FreeBSD ≈ OpenBSD and AIX ≈ Solaris duplication is stable and not growing. The shared code is primarily ps output parsing with slightly different flags/column names and sysctl queries.

    Recommendation: Defer Issue 3 until NetBSD/DragonflyBSD support is added. At that point, the right abstractions (e.g., BsdOSProcess base class) can be extracted with full knowledge of what's actually shared across all 4 BSDs.

    Issue 4 (FileUtil Internal Duplication) — Minor

    Left as-is; trivial internal duplication that doesn't affect maintainability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions