Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
337 changes: 337 additions & 0 deletions spml/src/main/resources/123-java-general-guidelines.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,337 @@
<?xml version="1.0" encoding="UTF-8"?>
<system-prompt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="system-prompt.xsd"
id="123-java-general-guidelines" version="1.0">
<metadata>
<description>Java General Guidelines</description>
<globs>*.java</globs>
<always-apply>false</always-apply>
<tags>
<tag>java</tag>
<tag>guidelines</tag>
<tag>naming</tag>
<tag>formatting</tag>
<tag>documentation</tag>
<tag>exceptions</tag>
<tag>best-practices</tag>
</tags>
<version>1.0.0</version>
</metadata>

<header>
<title>Java General Guidelines</title>
</header>

<system-characterization>
<role-definition>You are a Senior software engineer with extensive experience in Java software development</role-definition>
</system-characterization>

<description>
This document outlines general Java coding guidelines covering fundamental aspects such as naming conventions for packages, classes, methods, variables, and constants; code formatting rules including indentation, line length, brace style, and whitespace usage; standards for organizing import statements; best practices for Javadoc documentation; and comprehensive error and exception handling with a strong focus on security, including avoiding sensitive information exposure, catching specific exceptions, and secure resource management.
</description>

<toc auto-generate="true"/>

<content-sections>
<rule-section number="1" id="naming-conventions">
<rule-header>
<rule-title>Naming Conventions</rule-title>
<rule-subtitle>Follow Standard Java Naming Patterns</rule-subtitle>
</rule-header>
<rule-description>
Adhere to standard Java naming conventions for all code elements to promote intuitive, predictable, and easier to understand code navigation.
</rule-description>
<code-examples>
<good-example>
<code-block language="java"><![CDATA[// GOOD: Proper naming conventions
package com.example.project.module; // Lowercase, reverse domain notation

public class UserProfileService { // PascalCase for classes
public static final int MAX_LOGIN_ATTEMPTS = 3; // ALL_CAPS_SNAKE_CASE for constants

private final UserRepository userRepository; // camelCase for variables

public UserDTO getUserByUsername(String username) { // camelCase for methods
// ... implementation
}

private boolean isValid(String input) { // Boolean methods with 'is', 'has', 'can' prefix
return input != null && !input.trim().isEmpty();
}
}

// Generic type parameters
public class Repository<T extends Entity> { // Single uppercase letter
// ... implementation
}]]></code-block>
</good-example>
<bad-example>
<code-block language="java"><![CDATA[// AVOID: Poor naming conventions
package My_App_Services; // Uses underscores and wrong case

public class userprofilesvc { // Not PascalCase
public static final int defaultpagesize = 20; // Not ALL_CAPS_SNAKE_CASE

private UserRepository mUserRepository; // Hungarian notation (avoid)

public UserDTO GetUser(String Username) { // Wrong case for method and parameter
// ... implementation
}
}]]></code-block>
</bad-example>
</code-examples>
</rule-section>

<rule-section number="2" id="formatting">
<rule-header>
<rule-title>Formatting</rule-title>
<rule-subtitle>Apply Consistent Code Formatting</rule-subtitle>
</rule-header>
<rule-description>
Consistently apply formatting rules for indentation, line length, brace style, and whitespace to improve code readability and maintainability.
</rule-description>
<code-examples>
<good-example>
<code-block language="java"><![CDATA[// GOOD: Proper formatting
public class FormattingExample {
private static final int MAX_RETRY_COUNT = 3; // Proper spacing around operators

public void processData(String input) {
if (input == null || input.isEmpty()) { // K&R brace style
logger.warn("Input is null or empty");
return;
}

for (int i = 0; i < MAX_RETRY_COUNT; i++) { // Spaces after keywords and around operators
try {
performOperation(input);
break;
} catch (TemporaryException e) {
logger.debug("Retry attempt {}: {}", i + 1, e.getMessage());
}
}
}
}]]></code-block>
</good-example>
<bad-example>
<code-block language="java"><![CDATA[// AVOID: Poor formatting
public class BadFormattingExample{
private static final int MAX_RETRY_COUNT=3;// No spaces

public void processData(String input){
if(input==null||input.isEmpty())// No spaces, missing braces
logger.warn("Input is null or empty");

for(int i=0;i<MAX_RETRY_COUNT;i++){
try{
performOperation(input);
break;
}catch(TemporaryException e){// catch on same line
logger.debug("Retry attempt "+i+": "+e.getMessage());
}
}
}
}]]></code-block>
</bad-example>
</code-examples>
</rule-section>

<rule-section number="3" id="import-statements">
<rule-header>
<rule-title>Import Statements</rule-title>
<rule-subtitle>Organize Imports Systematically</rule-subtitle>
</rule-header>
<rule-description>
Structure import statements logically by grouping related packages and alphabetizing within groups. Avoid wildcard imports to ensure clarity about class origins.
</rule-description>
<code-examples>
<good-example>
<code-block language="java"><![CDATA[// GOOD: Organized imports
package com.example.myapp.services;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

import org.springframework.stereotype.Service;

import static com.example.myapp.utils.ValidationConstants.MAX_NAME_LENGTH;

import com.example.myapp.dto.UserDTO;
import com.example.myapp.exceptions.InvalidUserDataException;

@Service
public class UserService {
// ... implementation
}]]></code-block>
</good-example>
<bad-example>
<code-block language="java"><![CDATA[// AVOID: Disorganized imports
package com.example.myapp.services;

import java.util.*; // Wildcard import
import com.example.myapp.dto.UserDTO;
import java.util.Objects; // Mixed order
import com.example.myapp.exceptions.InvalidUserDataException;
import static com.example.myapp.utils.ValidationConstants.MAX_NAME_LENGTH; // Static import not grouped
import org.springframework.stereotype.Service;

@Service
public class UserService {
// ... implementation
}]]></code-block>
</bad-example>
</code-examples>
</rule-section>

<rule-section number="4" id="documentation-standards">
<rule-header>
<rule-title>Documentation Standards</rule-title>
<rule-subtitle>Maintain Clear Documentation</rule-subtitle>
</rule-header>
<rule-description>
Write self-documenting code and provide comprehensive Javadoc for public APIs, complex algorithms, and non-obvious business logic with required elements like @param, @return, @throws.
</rule-description>
<code-examples>
<good-example>
<code-block language="java"><![CDATA[// GOOD: Comprehensive documentation
/**
* Utility class for string manipulations and validation.
*
* @since 1.0
*/
public class StringUtil {

/**
* Checks if a string is null or empty.
*
* @param str The string to check, may be null
* @return {@code true} if the string is null or empty, {@code false} otherwise
* @throws IllegalArgumentException if the input string is "error" (for demo purposes)
*/
public static boolean isNullOrEmpty(String str) throws IllegalArgumentException {
if ("error".equals(str)) {
throw new IllegalArgumentException("Input cannot be 'error'");
}
return str == null || str.isEmpty();
}

/**
* Validates and sanitizes user input for safe processing.
*
* @param input The raw user input to validate
* @return The sanitized input
* @throws ValidationException if input fails validation rules
*/
public static String sanitizeInput(String input) throws ValidationException {
// Implementation with clear business logic comments
if (input == null) {
throw new ValidationException("Input cannot be null");
}

// Remove potentially dangerous characters
String sanitized = input.replaceAll("[<>\"'&]", "");

return sanitized.trim();
}
}]]></code-block>
</good-example>
<bad-example>
<code-block language="java"><![CDATA[// AVOID: Poor or missing documentation
public class StringHelper {
// No explanation of what it does or parameters
public boolean check(String s) {
return s == null || s.length() == 0;
}

// Unclear method name and no documentation
public String fix(String s) {
return s.replaceAll("[<>]", "");
}
}]]></code-block>
</bad-example>
</code-examples>
</rule-section>

<rule-section number="5" id="comprehensive-error-handling">
<rule-header>
<rule-title>Comprehensive Error and Exception Handling</rule-title>
<rule-subtitle>Implement Secure and Robust Error Management</rule-subtitle>
</rule-header>
<rule-description>
Implement robust error handling using specific exceptions, managing them at appropriate levels while preventing information leakage and ensuring proper resource cleanup.
</rule-description>
<code-examples>
<good-example>
<code-block language="java"><![CDATA[// GOOD: Comprehensive error handling
public class SecureFileProcessor {
private static final Logger logger = LoggerFactory.getLogger(SecureFileProcessor.class);

/**
* Reads file content safely with proper error handling.
*
* @param filePath The path to the file to read
* @return The file content
* @throws FileProcessingException if file cannot be processed
*/
public String readFile(Path filePath) throws FileProcessingException {
if (filePath == null) {
throw new IllegalArgumentException("File path cannot be null");
}

StringBuilder content = new StringBuilder();

// try-with-resources ensures proper resource cleanup
try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append(System.lineSeparator());
}
} catch (NoSuchFileException e) {
logger.warn("File not found: {}", filePath.getFileName());
throw new FileProcessingException("Requested file not found", e);
} catch (AccessDeniedException e) {
logger.error("Access denied reading file: {}", filePath.getFileName());
throw new FileProcessingException("Access denied", e);
} catch (IOException e) {
logger.error("IO error reading file: {}", filePath.getFileName(), e);
throw new FileProcessingException("Failed to read file", e);
}

return content.toString();
}
}]]></code-block>
</good-example>
<bad-example>
<code-block language="java"><![CDATA[// AVOID: Poor error handling
public class UnsafeFileProcessor {

public String readFile(String filePath) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
// ... reading logic
} catch (Exception e) {
// Swallowing exception - bad practice!
e.printStackTrace(); // Not using proper logging
return ""; // Hiding the problem
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Another swallowed exception
}
}
}
return null;
}
}]]></code-block>
</bad-example>
</code-examples>
</rule-section>
</content-sections>
</system-prompt>
Loading
Loading