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

这篇具有很好参考价值的文章主要介绍了用 ChatGPT 写代码,效率杠杠的!。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

来源: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.toymoban.com/news/detail-428107.html

到了这里,关于用 ChatGPT 写代码,效率杠杠的!的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 小程序 - Taro小程序中打开h5页面链接 - 并解决:无法打开该页面 - 不支持打开 https://www.baidu.com/,请在“小程序右上角更多->反馈与投诉”中和开发者反馈

    Taro 小程序中h5跳转打开页面 借助 webView 组件打开h5页面 @/pages/webView/webView.js 文件 Taro 中 webView 组件 29 行 主要代码 无法打开该页面 - 不支持打开 https://www.baidu.com/,请在“小程序右上角更多-反馈与投诉”中和开发者反馈 解决 - 在微信公众平台 小程序进行业务域名配置 具体

    2024年02月09日
    浏览(28)
  • 云计算与openStack-openStack学习 https://www.bilibili.com/video/BV1Jq4y1M7GC?p=22&spm_id_from=pageDriver

    一.openStack的主要组件 openStack提供硬件的管理能力,不提供硬件,支持不同厂商的硬件环境,将不同的硬件环境放在硬件池里面来统一管理 openStack还提供了认证服务、监测服务和数据库服务三大共享服务来服务上面的三大组件 ,应用程序可以通过API来管理提供的这三大组件和组件

    2023年04月14日
    浏览(30)
  • nginx将xxx.com重定向到www.xxx.com配置

    有时候,我们网站,需要将顶级域名xxx.com统一跳转到二级域名www.xxx.com下。这时候,我们可以通过修改nginx配置达到我们的目的。

    2024年03月23日
    浏览(43)
  • Docker未授权访问漏洞(www.hetianlab.com)

    Docker是一个开源的引擎,可以轻松的为任何应用创建一个轻量级的、可移植的、自给自足的容器。开发者在笔记本上编译测试通过的容器可以批量地在生产环境中部署,包括VMs(虚拟机)、bare metal、OpenStack 集群和其他的基础应用平台。 产生原因 如果在docker上配置了远程访问,d

    2024年02月04日
    浏览(46)
  • wwwxxx域名选择(www.xxx.com或者.cn)

    域名就是网站的网址,就跟家庭住址一样,那么域名就是我们网站的地址,我们使用方便记忆的域名(字母/数字+.COM等域名后缀:www.xxx.com)。 按所属机构分 常见后缀形式: COM:商业性的机构/公司/个人,因为COM这个后缀公信度高,所以用得比较多 ORG :非盈利的组织、团体

    2024年02月05日
    浏览(55)
  • 实例35---字符串反转,如将字符串 “www.runoob.com“ 反转为 “moc.boonur.www“。

    本系列为C语言菜鸟100道基础经典例题详解刷题系列。点滴成长,一起逆袭。 实例35—字符串反转( 字符串数组逆序输出 ),如将字符串 “www.runoob.com” 反转为 “moc.boonur.www”。 对c语言的字符串进行反转,将abcdef反转为fedcba的办法有很多,而我所使用的方法是 for循环来将字

    2024年02月04日
    浏览(35)
  • 虚拟机 ping: www.baidu.com:未知的名称或服务

    1、打开ifcfg-ens33文件 2、如下,加上网关和dns就行了,紫色部分,也就是 DNS1=“114.114.114.114” 2.1、 注释: 2.2、网关怎么看,静态IP地址如何确定? 第一步:网关确定,打开虚拟机网络编辑器,找到vmnet8,里面就有个网关,自动获取的: 这个网关,就是我们要填的。 第二部:

    2024年02月06日
    浏览(39)
  • 用ChatGPT搭建代码知识库,提升开发效率

    ChatGPT 的数据覆盖范围仅至 2021 年 9 月前,这意味着如果出现了 2021 年 9 月之后的新信息或技术,ChatGPT 可能无法提供准确的答案或建议。例如,前端开发中经常使用的公司开源项目 TDesign 就是一个例子: 幸运的是,针对这个问题,业界已经提供了解决方案——构建知识库,

    2024年02月15日
    浏览(28)
  • OpenAI API(ChatGPT)接口地址https://api.openai.com/v1/chat网络问题无法访问Error: connect ECONNREFUSED ETIMEDOUT

    https://api.openai.com/v1/chat是openAI的API接口地址,因为长城的原因,23年年初一次更新后便无法访问,访问接口会提示Error: connect ETIMEDOUT等网络相关的问题。 解决办法有三种: 本文只做方法讨论,供读者自行研究。如需实际的解决方案,请联系我 1. 代理(适用于大型的场景) 在

    2023年04月18日
    浏览(121)
  • Restclient-cpp库介绍和实际应用:爬取www.sohu.com

    Restclient-cpp是一个用C++编写的简单而优雅的RESTful客户端库,它可以方便地发送HTTP请求和处理响应。它基于libcurl和jsoncpp,支持GET, POST, PUT, PATCH, DELETE, HEAD等方法,以及自定义HTTP头部,超时设置,代理服务器等功能。 本文将介绍如何使用Restclient-cpp库来实现一个简单的爬虫程序

    2024年02月07日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包