用 ChatGPT 写代码,效率杠杠的!

yizhihongxing

来源:https://www.cnblogs.com/scy251147/p/17242557.html

ChatGPT出来好久了,vscode上面由于集成了相关的插件,所以用起来很简单,经过本人深度使用后,发觉其能力的强大之处,在书写单元测试,书写可视化小工具,代码纠错,代码规范,编程辅助方面,极其可靠,而且能识别一些坑并绕过,下面来看看他能干的一些事情吧。

注意:由于英文的表述可以让ChatGPT的反馈更准确,所以这里的问题我均以英文来描述。

1、单测用例生成

待生成单测的测试类,此类就是一个静态工厂类,可以根据传入的数据类型和语言类型,创建出几个语言数据服务,包括ducc,mysql,配置,空语言数据服务:

public class SepI18nDataFactory {

    /**
     * 配置文件数据服务
     */
    public static ISepI18nDataService dataService;

    /**
     * 构建数据服务
     *
     * @param dataType
     * @return
     */
    public static ISepI18nDataService buildDataService(SepI18nDataType dataType, SepI18nLanguageType languageType) {
        //按照数据类型判断
        switch (dataType) {
            //从ducc中构建多语言服务
            case DUCC:
                return getInstance(languageType, x -> new SepI18nDuccDataService(x));
            //从mysql中构建多语言服务
            case MYSQL:
                return getInstance(languageType, x -> new SepI18nMysqlDataService(x));
            //从本地配置中构建多语言服务
            case CONFIG:
                return getInstance(languageType, x -> new SepI18nConfigDataService(x));
            //空数据服务,兜底逻辑
            default:
                return getInstance(languageType, x -> new SepI18nEmptyDataService(x));
        }
    }

    /**
     * 高并发下实例创建管控
     *
     * @param languageType
     * @param callback
     * @return
     */
    private static ISepI18nDataService getInstance(SepI18nLanguageType languageType, Function<SepI18nLanguageType, ISepI18nDataService> callback) {
        if (dataService == null) {
            synchronized (SepI18nDataFactory.class) {
                if (dataService == null) {
                    dataService = callback.apply(languageType);
                }
            }
        }
        return dataService;
    }
}

ChatGPT问题如下(要求:为类中的所有方法创建单测并包含所有的场景):

program unit tests for all methods for below class , you need test all scenarios, show me the code by using java language:

public class SepI18nDataFactory {

	/** * 配置文件数据服务 */
	public static SepI18nConfigDataService configDataService;

	/** * 数据库数据服务 */
	public static SepI18nMysqlDataService mysqlDataService;

	/** * ducc数据服务 */
	public static SepI18nDuccDataService duccDataService;

	/** * 空数据服务 - 兜底服务 */
	public static SepI18nEmptyDataService emptyDataService;

	/** * 构建数据服务
	 * @param dataType
	 * @return
	 */
	 public static ISepI18nDataService buildDataService(SepI18nDataType dataType, SepI18nLanguageType languageType) {
	 //区域设定 Locale locale = null;

	 //按照数据类型判断
	 switch (dataType) {
	 	//从ducc中构建多语言服务
	 	case DUCC:
	 	if (duccDataService == null) {
	 		duccDataService = new SepI18nDuccDataService(languageType);
	 	}
	 	return duccDataService;
	 	//从mysql中构建多语言服务
	 	case MYSQL:
	 	if (mysqlDataService == null) {
	 		mysqlDataService = new SepI18nMysqlDataService(languageType);
	 	}
	 	return mysqlDataService;
	 	//从本地配置中构建多语言服务
	 	case CONFIG:
	 	if (configDataService == null) {
	 		configDataService = new SepI18nConfigDataService(languageType);
	 	} return configDataService;
	 	//空数据服务,兜底逻辑
	 	default:
	 	if (emptyDataService == null) {
	 		emptyDataService = new SepI18nEmptyDataService(languageType);
	 	}
	 	return emptyDataService;
	 }
   }
}

ChatGPT回答如下:

import static org.junit.Assert.assertEquals; import org.junit.Test;

public class SepI18nDataFactoryTest {

    @Test
    public void testBuildDataService_DUCC() {
        SepI18nDataType dataType = SepI18nDataType.DUCC;
        SepI18nLanguageType languageType = SepI18nLanguageType.EN;
        ISepI18nDataService dataService = SepI18nDataFactory.buildDataService(dataType, languageType);
        assertEquals(SepI18nDuccDataService.class, dataService.getClass());
        }

    @Test
    public void testBuildDataService_MYSQL() {
        SepI18nDataType dataType = SepI18nDataType.MYSQL;
        SepI18nLanguageType languageType = SepI18nLanguageType.EN;
        ISepI18nDataService dataService = SepI18nDataFactory.buildDataService(dataType, languageType);
        assertEquals(SepI18nMysqlDataService.class, dataService.getClass());
    }

    @Test
    public void testBuildDataService_CONFIG() {
        SepI18nDataType dataType = SepI18nDataType.CONFIG;
        SepI18nLanguageType languageType = SepI18nLanguageType.EN;
        ISepI18nDataService dataService = SepI18nDataFactory.buildDataService(dataType, languageType);
        assertEquals(SepI18nConfigDataService.class, dataService.getClass());
    }

    @Test
    public void testBuildDataService_Default() {
        SepI18nDataType dataType = SepI18nDataType.OTHER;
        SepI18nLanguageType languageType = SepI18nLanguageType.EN;
        ISepI18nDataService dataService = SepI18nDataFactory.buildDataService(dataType, languageType);
        assertEquals(SepI18nEmptyDataService.class, dataService.getClass());}}

生成的单测可以完美运行且包含所有的场景,完美。

用 ChatGPT 写代码,效率杠杠的!

2、编写小工具

由于在工作中,我们免不了需要写一些小工具来辅助业务,所以看看是否可以把这种活儿交给ChatGPT来干一下。 这里我们准备让其编写基于javafx框架的form界面工具,然后实际运行这个小工具来检验其编写小工具的可行性。

ChatGPT问题如下(界面上,两个文本框,两个按钮,点击第一个按钮,会选择文件夹,然后点击第二个按钮会将文件夹下的enum类名显示到另一个文本框中):

a form with two textfields, two buttons, click one button to locate the directory path and fill it into a textfield, and click another button to start to find the enum .class file from the directory path and show the enum class name into textfield, using javafx structure and show me the java code

ChatGPT回答如下:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class EnumFinder extends Application {

private TextField directoryPathTextField;

private TextField enumClassNameTextField;

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) {
    directoryPathTextField = new TextField();
    Button directoryPathButton = new Button("Select Directory");
    directoryPathButton.setOnAction(e -> {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        File selectedDirectory = directoryChooser.showDialog(primaryStage);
        if (selectedDirectory != null) {
            directoryPathTextField.setText(selectedDirectory.getAbsolutePath());
        }
    });

    Button findEnumButton = new Button("Find Enum");
    findEnumButton.setOnAction(e -> {
        String directoryPath = directoryPathTextField.getText();
        try (Stream<Path> paths =Files.walk(Paths.get(directoryPath))){
            paths.filter(Files::isRegularFile).filter(p -> p.toString().endsWith(".class")).filter(p ->isEnumClass(p)).forEach(p -> enumClassNameTextField.setText(p.getFileName().toString().replace(".class","")));}catch(IOException ex){
            ex.printStackTrace();}});

    enumClassNameTextField =newTextField();
    enumClassNameTextField.setEditable(false);HBox hBox =newHBox(directoryPathTextField, directoryPathButton, findEnumButton, enumClassNameTextField);Scene scene =newScene(hBox);
    primaryStage.setScene(scene);
    primaryStage.show();}privatebooleanisEnumClass(Path path){try{Class clazz =Class.forName(path.toString().replace(".class",""));return clazz.isEnum();}catch(ClassNotFoundException e){
        e.printStackTrace();returnfalse;}}}

有点呆住了,居然完全正确的生成了我要的工具且能正常运行(稍微调整下界面布局)。

用 ChatGPT 写代码,效率杠杠的!

3. 修复代码bug

Sample1:高并发bug

还是之前的代码,改了改,让其在高并发压力下,工作的不那么ok:

public class SepI18nDataFactory {

    /**
     * 配置文件数据服务
     */
    public static ISepI18nDataService dataService;

    /**
     * 构建数据服务
     *
     * @param dataType
     * @return
     */
    public static ISepI18nDataService buildDataService(SepI18nDataType dataType, SepI18nLanguageType languageType) {
        //按照数据类型判断
        switch (dataType) {
            //从ducc中构建多语言服务
            case DUCC:
                return getInstance(languageType, x -> new SepI18nDuccDataService(x));
            //从mysql中构建多语言服务
            case MYSQL:
                return getInstance(languageType, x -> new SepI18nMysqlDataService(x));
            //从本地配置中构建多语言服务
            case CONFIG:
                return getInstance(languageType, x -> new SepI18nConfigDataService(x));
            //空数据服务,兜底逻辑
            default:
                return getInstance(languageType, x -> new SepI18nEmptyDataService(x));
        }
    }

    /**
     * 高并发下实例创建管控
     *
     * @param languageType
     * @param callback
     * @return
     */
    private static ISepI18nDataService getInstance(SepI18nLanguageType languageType, Function<SepI18nLanguageType, ISepI18nDataService> callback) {
        if (dataService == null) {
              dataService = callback.apply(languageType);
        }
        return dataService;
    }
}

ChatGPT训练如下(指出代码在高并发下工作不太正常,让其修复):

below class is worked not ok under high flow pressure, please find the bug and fix for me :

public class SepI18nDataFactory {

	/** 配置文件数据服务 */
	public static ISepI18nDataService dataService;

	/** 构建数据服务
	* @param dataType
	* @return
	*/
	public static ISepI18nDataService buildDataService(SepI18nDataType dataType, SepI18nLanguageType languageType) {
	//按照数据类型判断
	switch (dataType) {
		//从ducc中构建多语言服务 case DUCC: return getInstance(languageType, x -> new SepI18nDuccDataService(x));
		//从mysql中构建多语言服务 case MYSQL: return getInstance(languageType, x -> new SepI18nMysqlDataService(x));
		//从本地配置中构建多语言服务 case CONFIG: return getInstance(languageType, x -> new SepI18nConfigDataService(x));
		//空数据服务,兜底逻辑 default: return getInstance(languageType, x -> new SepI18nEmptyDataService(x));
		}
	}

    /** 高并发下实例创建管控
     * @param languageType
     * @param callback
     * @return
     */
     private static ISepI18nDataService getInstance(SepI18nLanguageType languageType, Function callback) {
      if (dataService == null) {
     	 synchronized (SepI18nDataFactory.class) {
     		if (dataService == null) {
     			dataService = callback.apply(languageType);
     		}
     	}
     }
     return dataService;
   }
}

ChatGPT回答如下:

It looks like the bug is in the getInstance() method. The dataService variable is not being synchronized, which can cause issues with concurrent access. To fix this, you can add a synchronized block around the code that checks and sets the dataService variable. This will ensure that only one thread can access the variable at a time.

很明显,一针见血的指出了高并发下存在的问题。

Sample2: 自定义锁bug

随便写了个基于AQS锁框架的自定义锁,代码如下:

class SepSync extends AbstractQueuedSynchronizer {

    @Override
    protected boolean tryAcquire(int arg) {
        if (compareAndSetState(0, 1)) {
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        return false;
    }

    @Override
    protected boolean tryRelease(int arg) {
        if (getState() == 0) {
            throw new IllegalMonitorStateException();
        }
        setExclusiveOwnerThread(null);
        setState(0);
        return true;
    }

    public void lock() {
        acquire(1);
    }

    public void unlock() {
        release(1);
    }
}

ChatGPT问题如下(大意是帮忙看下锁写的有没有问题):

below is the lock class, please find the bug and fix it for me :

class SepSync extends AbstractQueuedSynchronizer {

	@Override protected boolean tryAcquire(int arg) {
		if (compareAndSetState(0, 1)) {
			setExclusiveOwnerThread(Thread.currentThread());
			return true;
		}

		return false;
	}

	@Override
	protected boolean tryRelease(int arg) {
		if (getState() == 0) {
			throw new IllegalMonitorStateException();
		}
		setExclusiveOwnerThread(null);
		setState(0);
		return true;
	}

	public void lock() {
		acquire(1);
	}

	public void unlock() {
		release(1);
	}
}

ChatGPT回答如下:

The bug in the above code is that the tryRelease() method does not check if the current thread is the exclusive owner thread before releasing the lock. This can lead to a situation where the lock is released by a thread that does not own it.

To fix this bug, the tryRelease() method should be modified to check if the current thread is the exclusive owner thread before releasing the lock. The modified code should look like this:

@Override protected boolean tryRelease(int arg){
	if(Thread.currentThread() != getExclusiveOwnerThread()){
		throw new IllegalMonitorStateException();
	}
	setExclusiveOwnerThread(null);
	setState(0);
	return true;
}

大意就是,我的锁写的有点问题,其他线程可以释放不属于它的锁。(幸好偷偷去看了ReetrentLock实现,确实如此),到这里有些折服了。

用 ChatGPT 写代码,效率杠杠的!

近期热文推荐:

1.1,000+ 道 Java面试题及答案整理(2022最新版)

2.劲爆!Java 协程要来了。。。

3.Spring Boot 2.x 教程,太全了!

4.别再写满屏的爆爆爆炸类了,试试装饰器模式,这才是优雅的方式!!

5.《Java开发手册(嵩山版)》最新发布,速速下载!

觉得不错,别忘了随手点赞+转发哦!

原文链接:https://www.cnblogs.com/javastack/p/17362400.html

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:用 ChatGPT 写代码,效率杠杠的! - Python技术站

(0)
上一篇 2023年4月30日
下一篇 2023年4月30日

相关文章

  • java 获取当前时间的三种方法

    下面是关于”java获取当前时间的三种方法”的详细攻略。 1. 使用java.util.Date类 我们可以使用Java中的java.util.Date类来获取当前日期时间。代码示例如下: import java.util.Date; public class GetDateTimeExample1 { public static void main(Str…

    Java 2023年5月20日
    00
  • java使用UDP实现点对点通信

    下面是我为您提供的“java使用UDP实现点对点通信”的攻略。 一、什么是UDP UDP是无连接的传输协议,数据报(Datagram)套接字就是基于UDP协议实现的,它不会像TCP那样保证数据传输的可靠性,传输的数据包也不要求应答。但是,UDP具备比TCP更快的传输速度和更小的网络开销,因此,当需要高效传输数据时,可以选择UDP协议。 二、使用UDP实现点对…

    Java 2023年5月20日
    00
  • java实现Composite组合模式的实例代码

    下面我将为你讲解Java实现Composite组合模式的实例代码完整攻略。在完成该过程前,我先将Composite组合模式的一些基本概念进行简单介绍。 Composite组合模式是一种结构化设计模式,用于将对象组合成树状结构,以表示“部分-整体”的层次关系。该模式使得客户端能够使用统一的接口处理单个对象以及对象组合,从而将单个对象与组合对象视为等同的对象。 …

    Java 2023年5月19日
    00
  • SpringMVC整合SSM实现异常处理器详解

    SpringMVC整合SSM实现异常处理器详解 在 Web 应用程序开发中,异常处理是一个非常重要的问题。如果我们不处理异常,那么当应用程序出现异常时,用户将会看到一个不友好的错误页面,这会影响用户体验。因此,我们需要在应用程序中实现异常处理器,以便更好地管理和维护应用程序。本文将详细讲解 SpringMVC 整合 SSM 实现异常处理器的完整攻略,包括异常…

    Java 2023年5月18日
    00
  • SpringBoot整合Scala构建Web服务的方法

    针对这个问题,我会分为以下几个部分来逐步讲解: SpringBoot整合Scala的基础知识 构建Scala的Web服务 示例说明 总结 接下来,我会一步步讲解每一个部分。 1. SpringBoot整合Scala的基础知识 首先需要介绍Scala语言和SpringBoot框架的基本概念。 Scala是一种面向对象的静态类型编程语言,同时也支持函数式编程,是…

    Java 2023年6月3日
    00
  • 几种常用DB驱动和DB连接串小结

    关于“几种常用DB驱动和DB连接串小结”的攻略,以下是详细的介绍和示例说明。 1. 常见的DB驱动 在Java中常用的DB驱动主要有以下几种: 1.1 MySQL驱动 MySQL驱动目前最常用的是Connector/J,它是MySQL官方提供的Java驱动程序。可以从MySQL官网下载到最新的MySQL驱动。 1.2 Oracle驱动 Oracle官方提供的…

    Java 2023年6月16日
    00
  • 浅谈Spring Security 对于静态资源的拦截与放行

    浅谈Spring Security 对于静态资源的拦截与放行 背景 在开发Web应用时,通常需要对系统中的URL资源进行访问控制,以保证系统安全。在Web开发中,Spring Security 是常见的安全框架,它提供了一系列的安全解决方案来对系统进行保护。其中一项功能就是对静态资源的拦截和放行。 Spring Security 配置 Spring Secu…

    Java 2023年5月20日
    00
  • Spring MVC全局异常实例详解

    Spring MVC全局异常实例详解 Spring MVC是一种基于Java的Web框架,它提供了许多便捷的功能和工具,使得开发者可以更加高效地开发Web应用程序。其中,全局异常处理是Spring MVC中常用的一种技术,本文将详细讲解如何在Spring MVC中实现全局异常处理,并提供两个示例来说明如何实现这一过程。 步骤一:创建Spring MVC项目 …

    Java 2023年5月17日
    00
合作推广
合作推广
分享本页
返回顶部