Skip to main content

Clean Code Sonar Lint Java



Coding Guidelines


1. Sections of code should not be commented out (java:S125)

CODE_SMELLCode smellMAJORMajor


Programmers should not comment out code as it bloats programs and reduces readability.

Unused code should be deleted and can be retrieved from source control history if required.




2.
Standard outputs should not be used directly to log anything (java:S106)

CODE_SMELLCode smellMAJORMajor


When logging a message there are several important requirements which must be fulfilled:
• The user must be able to easily retrieve the logs
• The format of all logged message must be uniform to allow the user to easily read the log
• Logged data must actually be recorded
• Sensitive data must only be logged securely

If a program directly writes to the standard outputs, there is absolutely no way to comply with those requirements. That's why defining and using a dedicated logger is highly recommended.

Noncompliant Code Example
System.out.println("My Message");  // Noncompliant


Compliant Solution
logger.log("My Message");


See


3.

Classes should not be empty (java:S2094)

CODE_SMELLCode smellMINORMinor

There is no good excuse for an empty class. If it's being used simply as a common extension point, it should be replaced with an interface. If it was stubbed in as a placeholder for future development it should be fleshed-out. In any other case, it should be eliminated.

Noncompliant Code Example

public class Nothing {  // Noncompliant
}

Compliant Solution

public interface Nothing {
}

Exceptions

Empty classes can be used as marker types (for Spring for instance), therefore empty classes that are annotated will be ignored.

@Configuration
@EnableWebMvc
public final class ApplicationConfiguration {

}




4.

Unused assignments should be removed (java:S1854)

CODE_SMELLCode smellMAJORMajor

A dead store happens when a local variable is assigned a value that is not read by any subsequent instruction. Calculating or retrieving a value only to then overwrite it or throw it away, could indicate a serious error in the code. Even if it's not an error, it is at best a waste of resources. Therefore all calculated values should be used.

Noncompliant Code Example

i = a + b; // Noncompliant; calculation result not used before value is overwritten
i = compute();

Compliant Solution

i = a + b;
i += compute();

Exceptions

This rule ignores initializations to -1, 0, 1, null, true, false and "".


5.

Unnecessary imports should be removed (java:S1128)

CODE_SMELLCode smellMINORMinor

The imports part of a file should be handled by the Integrated Development Environment (IDE), not manually by the developer.

Unused and useless imports should not occur if that is the case.

Leaving them in reduces the code's readability, since their presence can be confusing.

Noncompliant Code Example

package my.company;

import java.lang.String;        // Noncompliant; java.lang classes are always implicitly imported
import my.company.SomeClass;    // Noncompliant; same-package files are always implicitly imported
import java.io.File;            // Noncompliant; File is not used

import my.company2.SomeType;
import my.company2.SomeType;    // Noncompliant; 'SomeType' is already imported

class ExampleClass {

  public String someString;
  public SomeType something;

}


5.

Local variables should not be declared and then immediately returned or thrown (java:S1488)

CODE_SMELLCode smellMINORMinor

Declaring a variable only to immediately return or throw it is a bad practice.

Some developers argue that the practice improves code readability, because it enables them to explicitly name what is being returned. However, this variable is an internal implementation detail that is not exposed to the callers of the method. The method name should be sufficient for callers to know exactly what will be returned.

Noncompliant Code Example

public long computeDurationInMilliseconds() {
  long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
  return duration;
}

public void doSomething() {
  RuntimeException myException = new RuntimeException();
  throw myException;
}

Compliant Solution

public long computeDurationInMilliseconds() {
  return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
}

public void doSomething() {
  throw new RuntimeException();
}



This error comes in my code when I am storing the result of the function in a fucntion
then returning the variale the good coding practice is just to return the values irrespective of
storing the values in a separate variables




"""

public static String getCurrentDate() {
LocalDate localdate=LocalDate.now();

String currentDate=localdate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));

return currentDate;
}


"""

How I improved my code

1.

""""
public static String getCurrentDate() {
LocalDate localdate = LocalDate.now();

return localdate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));

}

""""

































Comments

Popular posts from this blog

Xpath toughest

1. //span[contains(text(),'Please enter the comments!')]//following-sibling::div//input//following-sibling::textarea Some of the other Xpaths are 1. search RBGA //clicking on the new request //a[@title='Request a new workflow for RB General Approval Form']         @FindBy(xpath="//body[contains(@class,'ext-safari')]/form[contains(@name,'workOnIssueForm')]/table[contains(@class,'jiraform maxWidth')]/tbody/tr/td[contains(@class,'rb_formArea')]/fieldset[contains(@class,'rb_WorkON_FieldSet')]/table/tbody/tr/td/div[contains(@class,'rb_WorkON_FieldContainer')]/div[contains(@class,'rb_WorkON_FieldValueArea rb_WorkON_FieldValueArea_create rb_WorkON_ValueArea_Wide')]/table[contains(@class,'workonstdtable')]/tbody/tr/td/input[1]")     public WebElement tickMark;         @FindBy(xpath="//body[contains(@class,'ext-safari')]/form[contains(@name,'workOnIssueForm')]/table[contains(@class,...

Date Time API

Issues with the Existing   Date / Time   APIs 1. Thread Safefty:- develpoers have to deal with concurrency issues.new date and time api in java 8 are immutable and thread safe and thus taking concurrency headache away from developers. 2. API Design and Ease of Understanding: good utility methods in new API 3. Zoned Date and Time Functinality is added. 4. The format that I have used in my project is basically a user defined format String userdefinedDate=localdate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")); System.out.println(userdefinedDate); ==================================================================== Study Link https://www.baeldung.com/java-8-date-time-intro#:~:text=Java%208%20provides%20ZonedDateTime%20when,to%20represent%20them%20as%20follows. Working With   LocalDate LocalDate localDate = LocalDate.now(); LocalDate.of(2015, 02, 20); LocalDate tomorrow = LocalDate.now().plusDays( 1 ); DayOfWeek sunday = LocalDate.parse("2016-06-12").getDayOfWeek...