用 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 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());}}生成的单测可以完美运行且包含所有的场景,完美。
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 codeChatGPT回答如下:
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);}@Overridepublic 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 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;}}} 有点呆住了,居然完全正确的生成了我要的工具且能正常运行(稍微调整下界面布局)。
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 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;}@Overrideprotected 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实现,确实如此),到这里有些折服了。
近期热文推荐:
1.1,000+ 道 Java面试题及答案整理(2022最新版)
2.劲爆!Java 协程要来了。。。
3.Spring Boot 2.x 教程,太全了!
4.别再写满屏的爆爆爆炸类了,试试装饰器模式,这才是优雅的方式!!
5.《Java开发手册(嵩山版)》最新发布,速速下载!
觉得不错,别忘了随手点赞+转发哦!
关键词:
- 广州科技活动周进入预热 明日正式启动300多场主题活动接踵而来
- 深化重点领域信用建设 广州正式出台新型监管机制实施方案
- 女童不慎掉入20米深井 18岁小姨三次下井成功营救
- 西安3个区域12月28日起每日开展全员核酸 官方提倡民众居家健身
- 浙江乐清一核酸检测结果异常人员 复采复检为阴性
- 浙江本轮疫情报告确诊病例490例 提倡“双节”非必要不出省
- 西安警方通报6起涉疫违法案件
- 西安新一轮核酸筛查日检测能力达160万管
- 西安市累计报告本土确诊病例811例
- 重庆曝光4起违反中央八项规定精神典型问题 警示党员干部清新过节
-
云南清水河边检站查获走私玉石和玉石毛料65公斤
中新网临沧12月28日电 (徐媛 雷珍玉)记者28日从云南清水河出入境边防检查站获悉,该站近日在清水河口岸查获一起利用货车藏匿走私玉石
-
让农民工不再忧“薪” 湖南祁阳高效根治欠薪
中新网永州12月28日电 (刘志军 周盛波)“感谢你们,没有你们不辞辛苦、多次讨要,我们肯定拿不着钱,这个年肯定过不好。”27日,农民
-
浙江缙云九旬老党员20多年义务为乡村老人理发
中新网丽水12月28日电(范宇斌 蒋依笑)在浙江省丽水市缙云县七里乡大园村周坎头自然村,今年90岁的陶岳贵在年近古稀时拾起剃刀,20多年
-
疫情下的边城东兴:停摆的城 夜行的人
(抗击新冠肺炎)疫情下的边城东兴:停摆的城 夜行的人 中新社广西东兴12月28日电 题:疫情下的边城东兴:停摆的城 夜行的人
-
长江流域生态管护员:我与长江的十年之约
中新网江西彭泽12月28日电 (袁昕 记者 王昊阳)“这是我今天第三次巡查了。”穿着新制服的长江流域生态管护员吴成年站立船头,在
-
吉林查干湖冬捕启幕 头鱼拍出2999999元
中新网松原12月28日电 (石洪宇 谭伟旗 薛栋栋)中国查干湖第二十届冰雪渔猎文化旅游节28日开幕,数万名游客现场直击鱼跃湖面的盛况。
-
甘肃中药炮制师研习古法30载:掌心留痕,翻烂资料书
中新网兰州12月28日电 (张婧)从事中药饮片加工技艺30年的张良,右手掌心有一条老疤痕,“20年前跟着老师傅学习中药材性状鉴别,传统方
-
广东启用涉疫风险人员排查12320专号
中新网广州12月28日电 (记者 蔡敏婕)广东省28日正式启用涉疫风险人员排查12320专号。即日起,涉疫风险人员来(返)粤前可在“粤省事”
-
武汉协和医院开设互联网儿童医学中心
中新网武汉12月28日电 (聂文闻 彭锦弦 陈有为)记者28日从华中科技大学附属协和医院(以下简称“武汉协和医院”)获悉,该院在湖北省首
-
四川:力争三年完成638个历史遗留矿山生态修复
中新网成都12月28日电 (杨予頔)28日,四川省自然资源厅发布消息称,近日,四川省自然资源厅印发了《四川省历史遗留矿山生态修复三年行
X 关闭
北京试点全龄友好住宅项目 老年家庭购房首付最低35%
西安新增本土确诊病例150例 详情发布
广东最低气温跌至-6℃现冰挂 部分道路及海上交通受影响
“2022科学跨年系列活动”启动 提高公众对科学类流言“免疫力”
珠科院多举措助力大湾区抗旱防咸保供水
X 关闭
Omdia:苹果为2022年全球最大的便携电脑显示面板采购商_精选
网游概念爆发,掌趣科技、冰川网络等涨停,昆仑万维再创新高
掌阅科技独家首发 “外卖诗人”王计兵诗集《赶时间的人》谱写人间烟火气
当前热门:共同推动新时代新征程政协工作
均悦充全新IP形象均宝正式上线,为人们“电”亮快乐生活!