Loading...
Loading...
Automatically detect code quality issues and provide improvement recommendations
npx skill4agent add wutongci/agentdemo code-quality// ❌ High Complexity
func ProcessOrder(order Order) error {
if order.Status == "pending" {
if order.Amount > 1000 {
if order.User.IsVIP {
// Complex logic
} else {
// Another complex logic
}
} else {
// More logic
}
} else if order.Status == "confirmed" {
// More nesting
}
return nil
}
// ✅ Reduce Complexity: Extract Methods
func ProcessOrder(order Order) error {
if order.Status == "pending" {
return processPendingOrder(order)
}
if order.Status == "confirmed" {
return processConfirmedOrder(order)
}
return nil
}
func processPendingOrder(order Order) error {
if order.Amount > 1000 {
return processLargeOrder(order)
}
return processSmallOrder(order)
}// ❌ High Cognitive Complexity
func ValidateUser(user User) error {
if user.Name != "" {
if user.Email != "" {
if user.Age >= 18 {
return nil
} else {
return errors.New("age must be >= 18")
}
} else {
return errors.New("email required")
}
} else {
return errors.New("name required")
}
}
// ✅ Low Cognitive Complexity: Use Guard Clauses
func ValidateUser(user User) error {
if user.Name == "" {
return errors.New("name required")
}
if user.Email == "" {
return errors.New("email required")
}
if user.Age < 18 {
return errors.New("age must be >= 18")
}
return nil
}// ❌ Duplicate Code
func CreateUserOrder(user User, items []Item) error {
total := 0.0
for _, item := range items {
total += item.Price * float64(item.Quantity)
}
discount := total * 0.1
final := total - discount
return saveOrder(user.ID, final)
}
func CreateGuestOrder(email string, items []Item) error {
total := 0.0
for _, item := range items {
total += item.Price * float64(item.Quantity)
}
discount := total * 0.1
final := total - discount
return saveGuestOrder(email, final)
}
// ✅ Extract Common Logic
func calculateOrderTotal(items []Item) float64 {
total := 0.0
for _, item := range items {
total += item.Price * float64(item.Quantity)
}
discount := total * 0.1
return total - discount
}
func CreateUserOrder(user User, items []Item) error {
total := calculateOrderTotal(items)
return saveOrder(user.ID, total)
}
func CreateGuestOrder(email string, items []Item) error {
total := calculateOrderTotal(items)
return saveGuestOrder(email, total)
}// ❌ Too many parameters
func CreateUser(name, email, phone, address, city, country, zipCode string, age int) error {
// ...
}
// ✅ Use object encapsulation
type UserInfo struct {
Name string
Email string
Phone string
Address Address
Age int
}
type Address struct {
Street string
City string
Country string
ZipCode string
}
func CreateUser(info UserInfo) error {
// ...
}// ❌ Poor naming
var d int // What does d stand for?
var data []byte // Too generic
var x User // Meaningless
// ✅ Good naming
var daysSinceLastLogin int
var requestBody []byte
var currentUser User// ❌ Unclear
func proc() error { ... }
func handle(d Data) { ... }
// ✅ Clear and expressive
func ProcessPayment() error { ... }
func HandleUserRegistration(data RegistrationData) { ... }// ❌ Magic numbers
if user.LoginAttempts > 5 { ... }
time.Sleep(300 * time.Second)
// ✅ Named constants
const MaxLoginAttempts = 5
const DefaultTimeout = 300 * time.Second
if user.LoginAttempts > MaxLoginAttempts { ... }
time.Sleep(DefaultTimeout)// ✅ Explain why
// Use exponential backoff to avoid thundering herd during service restart
func retryWithBackoff() { ... }
// Explain business rules
// According to tax regulations, orders over 1000 yuan require additional review
if order.Amount > 1000 { ... }// ❌ Repeat code content
// Set name to John
name := "John"
// Loop through users
for _, user := range users { ... }// ❌ Ignore error
file, _ := os.Open("config.json")
// ❌ Lose context
return err
// ✅ Good error handling
file, err := os.Open("config.json")
if err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}
defer file.Close()// ✅ Use defer to ensure closure
file, err := os.Open("data.txt")
if err != nil {
return err
}
defer file.Close()// ✅ Use sync.WaitGroup
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
// Processing
}(i)
}
wg.Wait()// ❌ Tight coupling
type UserService struct {
db *sql.DB // Direct dependency on concrete implementation
}
// ✅ Dependency injection
type UserRepository interface {
FindByID(id string) (*User, error)
Save(user *User) error
}
type UserService struct {
repo UserRepository // Depend on abstraction
}### Code Quality Issue: [Issue Type]
**Location**: [Filename:Line Number]
**Problem**: [Describe the issue]
**Severity**: P0 / P1 / P2 / P3
**Impact**: [Explain the impact]
**Recommended Fix**:
[Provide specific improved code]
**Reason**: [Explain why this change is needed]