服务粉丝

我们一直在努力
当前位置:首页 > 财经 >

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

日期: 来源:AI实战收集编辑:点击关注

关注 AI 实战,开启智能生活!

推荐阅读:

用上 ChatGPT 啦,打破你的认知!

Spring + OpenAI 生成图像,真香!
Spring Boot + ChatGPT 项目实战来了!
来源:https://www.cnblogs.com/scy251147/p/17242557.html
ChatGPT出来好久了,vscode上面由于集成了相关的插件,所以用起来很简单,经过本人深度使用后,发觉其能力的强大之处,在书写单元测试,书写可视化小工具,代码纠错,代码规范,编程辅助方面,极其可靠,而且能识别一些坑并绕过,下面来看看他能干的一些事情吧。
注意:由于英文的表述可以让ChatGPT的反馈更准确,所以这里的问题我均以英文来描述。
现在官方已经关闭注册了,加入我们的知识星球,免费送一个 ChatGPT 账号,我也只有最后不到 100 个,送完即止。


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());}}
生成的单测可以完美运行且包含所有的场景,完美。

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;}}}
有点呆住了,居然完全正确的生成了我要的工具且能正常运行(稍微调整下界面布局)。

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.
很明显,一针见血的指出了高并发下存在的问题。
另外,如果你近期准备面试跳槽,建议在Java面试库小程序在线刷题,涵盖 2000+ 道 Java 面试题,几乎覆盖了所有主流技术面试题。

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 知识星球,R哥最近 ChatGPT 玩疯了,用它写文章、生成代码、做表格、写 PPT、写文案、做面试题,效率提升了 N 倍。
建议尽快上车,现在上手成本是越来越高了。。
加入星球福利:
1、加入即送一个超难注册的 ChatGPT 账号,个人独享,目前官方已经关闭注册,一号难求,我也只有最后不到 100 个了,送完即止。
加入星球会持续送账号,但是账号注册成本一直在增加,星球也会涨价,早加入就是优势。
2、不割韭菜,R哥是实实在在分享东西。星球分享了大量 ChatGPT 学习资料, 还输出了 40+ 篇保姆级教程,持续更新中,涉及方方面面,真正的高质量知识星球。
以上早已值回票价,光一个账号就值几十块!
目前还是优惠价,快扫码加入吧:
1000 人后正式涨价啦,早就是优势!
ChatGPT 不会替代你,但掌握它的人会!

相关阅读

  • 达州大数据基地建设项目主体结构今天封顶

  • 经过6个月左右的施工建设,4月26日,达州大数据基地建设项目实现主体结构封顶,为年底前交付使用打下坚实基础。达州大数据基地建设项目位于达州数字经济产业园,自去年10月中标以来
  • 在 Git 中撤消更改的 6 种方法!

  • 关注“脚本之家”,与百万开发者在一起出品 | 前端充电宝(ID:FE-Charge)如若转载请联系原公众号当使用 Git 进行项目代码管理时,难免会出现一些错误操作或需求变更,需要对代码进
  • 如何利用私域流量实现变现

  • 点击上方“蓝字”,关注更多精彩随着生活节奏的加快,网购的模式越来越受用户的青睐,企业将更注重线上渠道的布局,但第三方平台的获客成本过高,且数据掌握在第三方平台手里,因此构建
  • 小卡片上的“同城约x”二维码,你敢扫吗?

  • 你的车窗上是否被放过这样的小卡片露骨的照片低俗的暗示醒目的二维码要是你“热血沸腾”去扫了准上当!01“小卡片”引诱入局2023年4月17日,宜宾市民张某报警称自己被骗了。经
  • 【每日资讯简报】3月31日 周五

  • 【每日资讯简报,一分钟知天下事】3月31日 星期五 农历闰二月初十1、冷空气来袭:北方多地降温将超15℃,南方重启“湿凉模式”;2、机票燃油附加费年内第二次下调:4月5日起单程最
  • 【每日资讯简报】3月29日 周三

  • 【每日资讯简报,一分钟知天下事】3月29日 星期三 农历闰二月初八1、网信办:全面清理通过伪造等手法摆拍制作的导向不良的短视频;2、第八批国家组织药品集采今日将开标,肝素类
  • 【每日资讯简报】4月27日 周四

  • 【每日资讯简报,一分钟知天下事】4月27日 星期四 农历三月初八1、国办:支持国企扩大招聘规模,实施百万就业见习岗位募集计划;2、市监总局:严厉打击“三假直播”(假人气、假优惠

热门文章

  • “复活”半年后 京东拍拍二手杀入公益事业

  • 京东拍拍二手“复活”半年后,杀入公益事业,试图让企业捐的赠品、家庭闲置品变成实实在在的“爱心”。 把“闲置品”变爱心 6月12日,“益心一益·守护梦想每一步”2018年四
  • 美国对华2000亿关税清单,到底影响有多大?

  • 1 今天A股大跌,上证最大跌幅超过2%。直接导火索是美国证实计划对华2000亿美元产品加征25%关税。 听起来,2000亿美元数目巨大,我们来算笔账。 2000亿美元,按现在人民币汇率

最新文章

  • 不要和陌生人一起创业

  • 今天的文章由这个标题而来。我经常这样写东西,觉得某句话适合做标题,于是就打算顺手写一篇文章。‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍我昨天看了孟岩公众号的那篇文章,不知道怎么
  • 团购 ChatGPT 4.0 Plus,把价格打下来

  • 组织一下ChatGPT PLUS团购,帮助有需要的人,毕竟升级ChatGPT PLUS确实费事儿。言归正传,真正使用ChatGPT的协助工作的人都会使用ChatGPT PLUS,因为给的结果更准确,让我们的工作更
  • 命令执行漏洞利用及绕过方式总结

  • 命令注入常见的方法1.常见管道符  Windows系统支持的管道符  Linux系统支持的管道符2.空格过滤  ${IFS}  重定向符<>  %09(需要php环境)3.黑名单绕过  拼接  ba
  • 截至2022年底我区拥有地理标志证明/集体商标90件

  •   石榴云/新疆日报讯(记者任华 任春香报道)记者从自治区人民政府新闻办公室4月27日召开的“强化协同 优化环境 合力开创知识产权强区建设新局面”新闻发布会上获悉,截至2022
  • 用 ChatGPT 写代码,效率杠杠的!

  • 关注 AI 实战,开启智能生活!推荐阅读:用上 ChatGPT 啦,打破你的认知!Spring + OpenAI 生成图像,真香!Spring Boot + ChatGPT 项目实战来了!来源:https://www.cnblogs.com/scy251147/p
  • 马斯克官宣 TruthGPT,正面硬刚 ChatGPT。。。

  • 关注 AI 实战,开启智能生活!推荐阅读:用上 ChatGPT 啦,打破你的认知!Spring + OpenAI 生成图像,真香!Spring Boot + ChatGPT 项目实战来了!在过去的几年里,人工智能(AI)发展迅速,引发