Current location: Home> Grok Tutorial> How to ensure the readability of the code when writing Grok code?

How to ensure the readability of the code when writing Grok code?

Author: LoRA Time:

When writing Grok code, ensuring the readability of the code is very important for subsequent maintenance and teamwork. Here are some specific methods:

1. Structured Prompt Project

1.1 Clarify readability requirements

 Please use Python to implement a quick sorting algorithm, and require:
1. Add Google-style docstring documentation 2. Use meaningful variable names 3. Keep the function no more than 20 lines 4. Add comments for key steps 5. Follow the PEP 8 specification

1.2 Segmented Request Code

 First generate quick sorted function signatures and docstring
Confirm and generate specific implementation

2. Code style control skills

2.1 Specify coding specifications

 # Require Grok to generate code according to the following specifications:
# - Variable naming: snake_case
# - Constant Naming: UPPER_CASE
# - Class name: PascalCase
# - Spaces on both sides of the operator# - Maximum line width of 79 characters

2.2 Sample template

 def calculate_circle_area(radius: float) -> float:
    """ Calculate the area of ​​a circle
        Args:
        radius: The radius of the circle must be a positive number
            Returns:
        Area of ​​a circle
            Raises:
        ValueError: When the radius is negative """
    if radius < 0:
        raise ValueError("Radial cannot be negative")
    return math.pi * radius ** 2

3. Key elements for improving readability

3.1 Variable Naming Optimization

Bad tips:

 Write a function to process user data

High-quality tips:

 Write a function that handles orders for e-commerce users, requiring:
- Name the input parameter customer_orders
- Temporary variables avoid single letters - Boolean variables start with is_/has_

3.2 Control code complexity

 When generating Python code:
1. Each function only does one thing 2. The circle complexity does not exceed 5
3. Nested no more than 2 layers 4. Functions with more than 15 rows must be decomposed

4. Document generation strategy

4.1 Automatically generate documents

 """
Please generate a complete Sphinx format document for the following functions, including:
1. Function Description 2. Parameter Type and Description 3. Return Value Description 4. Use Example 5. Possible Exceptions """

4.2 Type annotation enhancement

 # Require all functions to use Python type annotations# Use TypedDict for complex parameters
# Clearly state when the return value is Union type

5. Code organization skills

5.1 Modular Tips

 Split the shopping cart function into independent modules:
1. cart.py - main logic 2. discount.py - discount calculation 3. validation.py - input verification please give the module structure design first

5.2 Design pattern application

 Implementing a payment processor using factory mode:
1. Define clear interface 2. Each payment method is used as a subclass 3. Type prompts to use abstract base class to display the class diagram relationship first

6. Verification and Refactoring

6.1 Readability Check

 Perform the following check on the generated code:
1. Whether the variable name is self-interpreted 2. Whether the magic number is defined as a constant 3. Whether the complex logic is commented on 4. Whether the function length is reasonable, please indicate the parts that need to be improved

6.2 Refactoring suggestions

 Please refactor the following code into a more readable form:
1. Decompose the long function 2. Replace complex conditional expression 3. Improve the readability of exception handling

7. Industry best practices

7.1 Teamwork Specifications

 Generate Python code that complies with our team's code specifications:
1. Document strings use numpy format 2. Import grouping: standard library, third-party library, local module 3. Overwrite existing content

7.2 Performance and readability balance

 When optimization of performance is required:
1. Compare the code examples with good readability**

**Low readability code**:
```python
def p(d):
    return [i for i in d if i%2==0]

High readability code:

 def filter_even_numbers(numbers: list[int]) -> list[int]:
    """Filter out even numbers in the list
        Args:
        numbers: list containing integers
            Returns:
        New list containing only even numbers """
    return [num for num in numbers if num % 2 == 0]

8. Continuous improvement

8.1 Automatic inspection

 Add the following tool configuration to the generated code:
1. .pre-commit-config.yaml
2. Pylintrc configuration 3. Mypy type check

8.2 Readability indicators

 Please analyze this code:
1. Maintenance index 2. Document coverage 3. Naming consistency

With the above method, you can ensure that the code generated by Grok is not only functionally correct, but also professionally readable.