Coverity Issues – Java – SIC_INNER_SHOULD_BE_STATIC

TLDR: What is rationale behind SIC_INNER_SHOULD_BE_STATIC ?

First of all, I am curious of how coverity finds a fault in code, by doing static analysis.
But in this article, I wish to cover
1) The variety of issues found by Coverity,
2) How to address each of them,
3) What is the rationale behind each of the issue?

1. Relating to Static Inner Classes:
SIC: Should be a static inner class (SIC_INNER_SHOULD_BE_STATIC)
For example, it flags that inner class should be made static.

package com.question.inner.stat;

public class ExperimentStatic {

 /**
  * @param args
  */
 public static void main(String[] args) {
  ExperimentStatic.NestedClass expVar =
  new ExperimentStatic.NestedClass(3, "dfdpstr");
 }
 
 class NestedClass{  
  private int i;
  private String str;  
  NestedClass(int id, String pstr)
  {
   i = id;
   str = pstr;
  }
 }
}

Here, how do we address this issue?
Ans: By just marking it as static.


static class NestedClass{}

What is the rationale behind this coverity issue?
It says that the inner class should be declared as static.
So, what is the harm in keeping an inner class as non-static?
One thing we can see is that if a inner class is non-static, then it can access the members of the enclosing class. If a inner class is made static, then it does not have access to
non-static members of the enclosing class. A static inner class can have access to static members of enclosing class.

So, ultimately it boils down to the design, whether we want to access static members of the enclosing class or not. A static inner class also means that we are going to have one
instance of this inner class in the context of enclosing class.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s