banner
lMingyul

lMingyul

记录穿过自己的万物
jike

Using the Series - Programming with ChatGPT

Recently, our company has been promoting the use of ChatGPT among programmers. Some people who have tried it feel that it affects their coding thinking and reduces efficiency, while others find it very useful and can't live without it. I also want to record my use of ChatGPT in the field of programming.

Code#

Code Understanding#

When writing requirements in daily work, it is often not starting from scratch. Many times, it is based on the code written by others. Each person's coding style and complexity are different. At this time, we can use ChatGPT to help us organize the basic logic of the code.

Keywords: Code explanation, for example: {code snippet}

Example

@Aspect
@Slf4j
@Component
public class LogAspect {

    public final static String TRACE_LOG_ID = "traceId";

    /**
     * Aspect expression, this aspect is the implementation class of service
     */
    @Pointcut("execution(* org.lmingyu.projects.cs.*.service.*.impl.*.*(..))")
    public void logPointcut() {

    }

    /**
     * Print logs
     *
     * @param pjp Parameters, traceId is obtained from the first parameter
     * @return Result
     * @throws Throwable Exception
     */
    @Around("logPointcut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        String traceId = MDC.get(TRACE_LOG_ID);
        if (StringUtils.isBlank(traceId)) {
            if (pjp.getArgs().length > 0 && pjp.getArgs()[0] instanceof BaseReq) {
                BaseReq req = (BaseReq) pjp.getArgs()[0];
                if (StringUtils.isNotBlank(req.getTraceId())) {
                    traceId = req.getTraceId();
                }
            }
            if (StringUtils.isNotBlank(traceId)) {
                MDC.put(TRACE_LOG_ID, traceId);
            } else {
                MDC.put(TRACE_LOG_ID, UUID.randomUUID().toString());
            }
        }

        long startTime = System.currentTimeMillis();
        // Print request parameters
        log.info("Input:{}", JSON.toJSONString(pjp.getArgs()));

        Object result = pjp.proceed();
        // Print output parameters
        log.info("Time consumed {}ms, Output:{}", System.currentTimeMillis() - startTime, JSON.toJSONString(result));
        return result;
    }

}

ChatGPT's answer:

CleanShot-2023-05-21-10-14-31@2x


Writing Code#

Sometimes it is very difficult to write a piece of code in a language that you have not learned. At this time, you can ask ChatGPT to help you write it. Or if you have a general idea of the implementation but don't know where to start, you can ask ChatGPT to write a demo for you.

# Tell ChatGPT to use what language, language version, and complete the code for me
Keywords: Please write a snake game using python3.7 and give me the complete code

CleanShot-2023-05-21-11-01-00@2x

  • If the given code is not complete, there is a word limit for ChatGPT
    • You can provide: Please provide the remaining code
  • If the given code has problems and throws errors when running
    • You can provide: Describe the problem, please complete the code
    • If the code is too long and generating code wastes time or token limit, you can describe it like this: Describe the problem, please point out which line of code needs to be modified

Sometimes the code provided by ChatGPT is always problematic. At this time, you need to understand the code yourself (you can also ask ChatGPT to explain the meaning of the code to you), find the problem in the code, and clearly point out the problem to ChatGPT, which can improve the speed of problem solving.


Improving Code Quality#

Let ChatGPT help you fix bugs

When you finish writing a requirement and have several core logic sections, you can ask ChatGPT to check if there are any bugs in the code. Or if there is a problem in the production environment and you know exactly which section of the code has a problem, but you are not sure where the problem is, you can ask ChatGPT to check and provide you with a solution.

Keywords: Fix bug: {code snippet}

CleanShot-2023-05-21-11-44-50@2x

  • Sometimes the error message shows which line the error occurred, you can also tell ChatGPT which line of code has a problem, so that it can locate and solve the problem more accurately.
  • You can also add more detailed description in the code

Let ChatGPT help you optimize the code

ChatGPT can also help you optimize the code

Keywords: Optimize code: {code snippet}

CleanShot-2023-05-21-13-45-04@2x

SQL can also be optimized

Keywords: SQL optimization: {SQL snippet}

CleanShot-2023-05-21-14-04-29@2x

-- SQL before optimization
SELECT COUNT(*) AS 'order_count',
SUM(amount) AS 'total_sales',
SUM(amount) / COUNT(*) AS'avg_sales_per_order'
FROM sales
WHERE user_id = 123
AND created_at BETWEENDATE_SUB(NOW(),INTERVAL 7 DAY) AND NOW();

--- SQL after optimization
SET @start_date = DATE_SUB(NOW(), INTERVAL 7 DAY);

SELECT 
  COUNT(*) AS 'order_count',
  SUM(amount) AS 'total_sales',
  SUM(amount) / COUNT(*) AS 'avg_sales_per_order'
FROM sales
WHERE 
  user_id = 123 AND 
  created_at BETWEEN @start_date AND NOW();


Testing Scenarios#

Generating Test Data#

When we finish development, we often need to test the functionality ourselves. At this time, we can ask ChatGPT to generate test data for us. Sometimes, we can also ask ChatGPT to generate Python code for the corresponding data.

CleanShot-2023-05-21-14-37-40@2x

Generating Unit Test Cases#

When we finish writing a piece of code, we need to write corresponding unit test cases to ensure the stability and accuracy of the code. However, writing unit test cases is often time-consuming, and sometimes even more complex than the original logic. At this time, we can ask ChatGPT to help us write the unit test cases for the code.

Keywords: Generate corresponding unit test cases {code snippet}

Problem Solving Assistant#

When you receive a requirement, you often have no idea or there are multiple implementation methods. At this time, you can ask ChatGPT for a solution, and let it provide you with a solution and give you a problem-solving idea.

Companion for Learning Programming#

When learning a new technology, you often don't know where to start. You can also ask ChatGPT for a learning outline, arrange a learning plan for you, and throw the problems you encounter to it. Why not?

Tips for Use#

  • When your conversation will last for a long time, you can communicate with it in sections, and add If you understand, please answer clearly in each section of the conversation.
  • When ChatGPT's answer is already comprehensive, but only a small part needs to be modified, it is recommended to do it yourself. If you insist on asking ChatGPT for a completely matching answer, it may not be worth the effort.

Finally, ChatGPT is not omnipotent. Don't expect to rely on it to solve everything when you don't know anything. It is like a tool that can assist you in solving problems and providing ideas.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.