Skip to content

Conversation

@uhm0311
Copy link
Collaborator

@uhm0311 uhm0311 commented Sep 2, 2025

🔗 Related Issue

https://rules.sonarsource.com/java/RSPEC-2386/

There is no good reason to have a mutable object as the public (by default), static member of an interface. Such variables should be moved into classes and their visibility lowered.

Similarly, mutable static members of classes and enumerations which are accessed directly, rather than through getters and setters, should be protected to the degree possible. That can be done by reducing visibility or making the field final if appropriate.

Note that making a mutable field, such as an array, final will keep the variable from being reassigned, but doing so has no effect on the mutability of the internal state of the array (i.e. it doesn’t accomplish the goal).

This rule raises issues for public static array, Collection, Date, and awt.Point members.

Noncompliant code example

public interface MyInterface {
  public static String [] strings; // Noncompliant
}

public class A {
  public static String [] strings1 = {"first","second"};  // Noncompliant
  public static String [] strings2 = {"first","second"};  // Noncompliant
  public static List<String> strings3 = new ArrayList<>();  // Noncompliant
  // ...
}

⌨️ What I did

  • static final 필드로 선언되어 있지만 실제로는 상수로 사용할 수 없는 필드 대신 사용할 메소드를 추가합니다.
  • 기존의 mutable static final 필드는 @Deprecated 처리합니다.

@uhm0311 uhm0311 requested a review from jhpark816 September 2, 2025 09:00
(byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255,
(byte) 255, (byte) 255, (byte) 255, (byte) 255
};
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@uhm0311 @oliviarla @brido4125
매번 객체를 생성하여 사용하고 GC 하는 것 보다, 기존 코드가 나아 보입니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

매번 객체를 생성하지 않는 점이 문제가 되는 코드입니다.

AS-IS

ByteArrayBKey.MIN[0] = 10;
System.out.println(ByteArrayBKey.MIN[0]); // 10

TO-BE

ByteArrayBKey.getMin()[0] = 10;
System.out.println(ByteArrayBKey.getMin()[0]); // 0

@jhpark816
Copy link
Collaborator

@oliviarla @brido4125 추가 리뷰어 지정하니, 리뷰 바랍니다.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants