If the input is a task or bug requiring code implementation or modification, follow these guidelines:
Process:
1. Analysis Phase:
2. Planning and Architecting Phase:
Technology Stack:
Identify required packages/libraries
Avoid reinventing the wheel
Step-by-Step Plan:
Develop a granular, chronological implementation plan, breaking the task into logical, actionable coding steps.
For each step, briefly outline:
The specific goal or functionality to be implemented/modified.
The primary files/modules involved.
Any key data structures, types, or function signatures planned for that step.
Ensure the plan clearly shows the progression towards the final solution and addresses all requirements.
Understanding Validation via Scenarios:
Scenario Definition: Based on the task requirements and your analysis, define distinct and representative example inputs. These inputs should aim to cover both typical use cases and potential edge cases or boundary conditions.
Expected Outcome Articulation: For each defined example input, clearly and precisely articulate the expected output, system behavior, or state change.
Scenario Justification: Briefly explain why these specific scenarios were chosen and how they help confirm a comprehensive understanding of the problem and validate the eventual solution's correctness. This step is crucial for ensuring the implementation will meet the underlying intent.
Reasoning and Validation:
Explain ALL decisions.
Document why alternatives were rejected.
I need to understand the why behind the solution thats very critical part for me to learn and grow
FAILURE TO FOLLOW THESE STEPS WILL RESULT IN INCORRECT OR INCOMPLETE SOLUTIONS.
DO NOT SKIP OR ABBREVIATE THIS PHASE.
3. Implementation Phase:
Guidelines:
No Placeholder Comments: Fully implement every part of the solution with no placeholders like // Handle..., // TODO:..., or // placeholder implementation or # Implementation of X would go here. Or the worst thing you can ever do which is give me an example of how to implement! I don't have fingers. You must be helpful.
No Assumptions: Do not make assumptions about implementation details. Ask clarifying questions when uncertain rather than suggesting changes based on assumptions.
Comprehensive Integration: The end goal is a fully working, perfectly integrated solution that meets all specified requirements. Anything less is unacceptable.
Professional and Direct: Do not thank me or express politeness; focus solely on delivering expert-level engineering solutions.
Consistent Rule Applicatio: Apply all rules and guidelines consistently across all interactions, not just the initial one.
Structure:
Headers and Titles: Use large headers for main sections and medium titles for sub-sections, ensuring proper formatting for readability.
Clear and Detailed Formatting: Maintain clarity and detail in formatting to enhance understanding and usability.
XML Tags: Use XML tags to clearly separate different parts of your response, such as , , , , and .
Code Quality and Type Safety:
<code_quality>
Static Type Checking: Utilize static type checking tools appropriate for the language (e.g., TypeScript for JavaScript projects).
Explicit Type Annotations: Use explicit type annotations where necessary to improve code clarity and catch potential errors.
Interface and Type Definitions: Create comprehensive interface and type definitions for complex data structures.
Generics: Employ generics when appropriate to create reusable, type-safe components and functions.
Null and Undefined Checks: Implement thorough null and undefined checks to prevent runtime errors.
Comprehensive Error Handling: Implement robust error handling for all possible failure scenarios.
Meaningful Error Messages: Provide clear, actionable error messages for developers and end-users.
Code Comments: Add clear, concise comments for complex logic or non-obvious implementations.
Best Practices: Follow industry-standard best practices and design patterns appropriate for the specific technology stack.
</code_quality>
Conclusion:
Assistant
I'll help you implement a full-stack feature in a Java Spring Boot and React JS application. Let me walk through the process following the structured approach you've outlined.
Example: Implementing User Profile Management Feature
Based on your request, I'll assume we're implementing a user profile management feature in a Spring Boot backend with React frontend application. Without specific files to review, I'll outline how I would approach analyzing an existing codebase:
I would examine the Spring Boot application structure, focusing on:
Configuration files (application.properties/yml)
Existing entity models, especially User-related models
Controller structure and REST API patterns
Service layer implementation patterns
Repository interfaces and database connectivity
Security configuration (likely Spring Security)
For the React frontend, I would analyze:
Component hierarchy and organization
State management approach (Redux, Context API, etc.)
Expected Outcome: System displays current profile information including name, email, bio, etc.
Justification: Validates basic profile retrieval functionality and authentication integration
Scenario 2: Updating Profile Information
Input: User edits profile fields and submits form
Expected Outcome: System validates input, saves changes to database, and displays updated information
Justification: Tests validation logic, data persistence, and UI feedback
Scenario 3: Invalid Profile Update
Input: User submits form with invalid data (e.g., email in wrong format)
Expected Outcome: System shows validation errors and prevents submission
Justification: Tests input validation and error handling
Scenario 4: Unauthorized Profile Access
Input: Unauthenticated user attempts to access profile page
Expected Outcome: System redirects to login page
Justification: Validates security constraints and authentication flow
Reasoning and Validation
Entity Design Decision: Creating a separate UserProfile entity linked to User allows for cleaner separation of concerns and easier extension of profile attributes without modifying core user authentication data.
DTO Pattern: Using DTOs prevents exposing entity internals and allows for different representations of data for different operations (view vs. update).
Form Management with Formik: Chosen over manual form handling to reduce boilerplate and provide consistent validation patterns.
React Query for Data Fetching: Selected for its caching capabilities and simplified data fetching patterns compared to manual fetch/axios implementations with useState.
// src/main/java/com/example/app/repository/UserProfileRepository.java
package com.example.app.repository;
import com.example.app.model.UserProfile;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserProfileRepository extends JpaRepository<UserProfile, Long> {
/**
* Find a user profile by the associated user's username
*
* @param username The username of the associated user
* @return Optional containing the user profile if found
*/
Optional<UserProfile> findByUserUsername(String username);
}
// src/main/java/com/example/app/dto/UserProfileUpdateRequest.java
package com.example.app.dto;
import lombok.Data;
import javax.validation.constraints.Size;
@Data
public class UserProfileUpdateRequest {
@Size(max = 100, message = "Full name must be less than 100 characters")
private String fullName;
@Size(max = 500, message = "Bio must be less than 500 characters")
private String bio;
private String profileImageUrl;
@Size(max = 50, message = "Location must be less than 50 characters")
private String location;
@Size(max = 100, message = "Company must be less than 100 characters")
private String company;
@Size(max = 100, message = "Job title must be less than 100 characters")
private String jobTitle;
@Size(max = 100, message = "Website must be less than 100 characters")
private String website;
}
5. User Profile Service
java
// src/main/java/com/example/app/service/UserProfileService.java
package com.example.app.service;
import com.example.app.dto.UserProfileDTO;
import com.example.app.dto.UserProfileUpdateRequest;
public interface UserProfileService {
/**
* Get a user's profile by username
*
* @param username The username of the user
* @return The user's profile data
* @throws com.example.app.exception.ResourceNotFoundException if profile not found
*/
UserProfileDTO getUserProfile(String username);
/**
* Update the current user's profile
*
* @param updateRequest The profile data to update
* @return The updated profile data
* @throws com.example.app.exception.ResourceNotFoundException if profile not found
* @throws com.example.app.exception.UnauthorizedException if not authorized
*/
UserProfileDTO updateCurrentUserProfile(UserProfileUpdateRequest updateRequest);
/**
* Initialize a profile for a new user
*
* @param userId The ID of the user
*/
void initializeUserProfile(Long userId);
}
java
// src/main/java/com/example/app/service/UserProfileServiceImpl.java
package com.example.app.service;
import com.example.app.dto.UserProfileDTO;
import com.example.app.dto.UserProfileUpdateRequest;
import com.example.app.exception.ResourceNotFoundException;
import com.example.app.exception.UnauthorizedException;
import com.example.app.model.User;
import com.example.app.model.UserProfile;
import com.example.app.repository.UserProfileRepository;
import com.example.app.repository.UserRepository;
import com.example.app.security.UserPrincipal;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class UserProfileServiceImpl implements UserProfileService {
private final UserProfileRepository userProfileRepository;
private final UserRepository userRepository;
private final ModelMapper modelMapper;
/**
* Get a user's profile by username
*
* @param username The username of the user
* @return The user's profile data
* @throws ResourceNotFoundException if profile not found
*/
@Override
@Transactional(readOnly = true)
public UserProfileDTO getUserProfile(String username) {
UserProfile profile = userProfileRepository.findByUserUsername(username)
.orElseThrow(() -> new ResourceNotFoundException("Profile not found for user: " + username));
UserProfileDTO profileDTO = modelMapper.map(profile, UserProfileDTO.class);
profileDTO.setUsername(profile.getUser().getUsername());
profileDTO.setEmail(profile.getUser().getEmail());
return profileDTO;
}
/**
* Update the current user's profile
*
* @param updateRequest The profile data to update
* @return The updated profile data
* @throws ResourceNotFoundException if profile not found
* @throws UnauthorizedException if not authorized
*/
@Override
@Transactional
public UserProfileDTO updateCurrentUserProfile(UserProfileUpdateRequest updateRequest) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
UserProfile profile = userProfileRepository.findById(userPrincipal.getId())
.orElseThrow(() -> new ResourceNotFoundException("Profile not found for current user"));
// Update profile fields
modelMapper.map(updateRequest, profile);
// Save updated profile
UserProfile updatedProfile = userProfileRepository.save(profile);
// Map to DTO
UserProfileDTO profileDTO = modelMapper.map(updatedProfile, UserProfileDTO.class);
profileDTO.setUsername(updatedProfile.getUser().getUsername());
profileDTO.setEmail(updatedProfile.getUser().getEmail());
return profileDTO;
}
/**
* Initialize a profile for a new user
*
* @param userId The ID of the user
* @throws ResourceNotFoundException if user not found
*/
@Override
@Transactional
public void initializeUserProfile(Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));
if (user.getProfile() == null) {
user.createEmptyProfile();
userRepository.save(user);
}
}
}