如何让 ChatGPT 充当细致入微的 Java 代码优化工? | 得物技术

注:本文使用New Bing(GPT4.0)演示

让他扮演一个Java软件开发者

第一步:我们让ChatGPT扮演一个Java软件开发者的角色

  • 提示词插件:地址:ChatGPT BingChat GPT3 Prompt Generator App (Streamlit) - a Hugging Face Space by Kaludi

Java Software Developer Java软件开发者

I want you to act as a Java software developer.
 I will provide you with a list of commands and you will implement them. 
My first request is "I need help creating a Java application."

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F6cmCp13-1680781803341)(https://p3-sign.toutiaoimg.com/tos-cn-i-qvj2lq49k0/3154dd478bcf4428a299fdb7589cde82~tplv-obj.image?traceid=2023040619440086B0D19834A3D07F6624&x-expires=2147483647&x-signature=PxfL24%2B3sij9u48JKD%2BXuvm%2BQbY%3D)]

准备一个不太好的Java代码示例

第二步:我们准备一个写得不太好的Java代码示例

  • Bad Java Example:
public int calculateUsingIfElse(int a, int b, String operator) {
  int result = 0;
  if (operator.equals("add")) {
    result = a + b;
  } else if (operator.equals("subtract")) {
    result = a - b;
  } else if (operator.equals("multiply")) {
    result = a * b;
  } else if (operator.equals("divide")) {
    if (b == 0) {
      throw new IllegalArgumentException("Cannot divide by zero");
    }
    result = a / b;
  } else if (operator.equals("modulus")) {
    if (b == 0) {
      throw new IllegalArgumentException("Cannot divide by zero");
    }
    result = a % b;
  } else if (operator.equals("power")) {
    result = (int) Math.pow(a, b);
  } else if (operator.equals("square root")) {
    if (a < 0) {
      throw new IllegalArgumentException("Cannot take square root of negative number");
    }
    result = (int) Math.sqrt(a);
  } else if (operator.equals("absolute value")) {
    result = Math.abs(a);
  } else if (operator.equals("negate")) {
    result = -a;
  } else {
    throw new IllegalArgumentException("Invalid operator");
  }
  return result;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PnBNJmed-1680781803342)(https://p3-sign.toutiaoimg.com/tos-cn-i-qvj2lq49k0/1dfaa4fe52974d9d81d06969d0e025d1~tplv-obj.image?traceid=2023040619440086B0D19834A3D07F6624&x-expires=2147483647&x-signature=U2PAN7mTLtW6l%2FaXd6ajFt%2FC4dU%3D)]

让他优化这段代码

第三步:让newBing(ChatGPT)优化这段代码

  • 并且要求「整理成比较优雅的代码结构,比如自动拆分子函数、降低if和循环嵌套,甚至实现部分设计模式。」

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XWtVv4kL-1680781803342)(https://p3-sign.toutiaoimg.com/tos-cn-i-qvj2lq49k0/4830f34da78446b7b9bbea1b773ec153~tplv-obj.image?traceid=2023040619440086B0D19834A3D07F6624&x-expires=2147483647&x-signature=CqA1g7WWlEKKE2cqrt02AxCWCPk%3D)]

// 定义一个接口,表示不同的运算策略
public interface OperationStrategy {
  int apply(int a, int b);
}


// 定义一个枚举,表示不同的运算符和对应的策略
public enum Operator {
  ADD((a, b) -> a + b),
  SUBTRACT((a, b) -> a - b),
  MULTIPLY((a, b) -> a * b),
  DIVIDE((a, b) -> {
    if (b == 0) {
      throw new ArithmeticException("Cannot divide by zero");
    }
    return a / b;
  }),
  MODULUS((a, b) -> {
    if (b == 0) {
      throw new ArithmeticException("Cannot divide by zero");
    }
    return a % b;
  }),
  POWER((a, b) -> (int) Math.pow(a, b)),
  SQUARE_ROOT((a, b) -> {
    if (a < 0) {
      throw new ArithmeticException("Cannot take square root of negative number");
    }
    return (int) Math.sqrt(a);
  }),
  ABSOLUTE_VALUE(Math::abs),
  NEGATE(a -> -a);


  private final OperationStrategy strategy;


  Operator(OperationStrategy strategy) {
    this.strategy = strategy;
  }


  public int apply(int a, int b) {
    return strategy.apply(a, b);
  }
}


// 定义一个方法,根据运算符和操作数来计算结果
public int calculateUsingStrategy(int a, int b, String operatorName) {


   // 根据运算符名称找到对应的枚举常量,如果没有找到则抛出异常
   Operator operator = Operator.valueOf(operatorName.toUpperCase());
   if (operator == null) {
     throw new IllegalArgumentException("Invalid operator");
   }


   // 调用枚举常量的apply方法来执行相应的策略
   return operator.apply(a,b);
}

让他写个单测

第四步:我们最后让他收下尾——写个单测吧

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vtp1Gkkk-1680781803343)(https://p3-sign.toutiaoimg.com/tos-cn-i-qvj2lq49k0/8ccff9e1af85485ea512950bb797a43f~tplv-obj.image?traceid=2023040619440086B0D19834A3D07F6624&x-expires=2147483647&x-signature=BqCduSSI0TaxEIKZ%2FSdyw8FfW7U%3D)]

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


// 定义一个测试类,用@Test注解标记要执行的测试方法
public class CalculatorTest {


  // 定义一个测试方法,用assertEquals方法来验证计算结果是否正确
  @Test
  public void testAdd() {
    int result = calculateUsingStrategy(3, 5, "add");
    assertEquals(8, result);
  }


  // 定义其他的测试方法,分别测试不同的运算符和操作数
  @Test
  public void testSubtract() {
    int result = calculateUsingStrategy(10, 4, "subtract");
    assertEquals(6, result);
  }


  @Test
  public void testMultiply() {
    int result = calculateUsingStrategy(7, 9, "multiply");
    assertEquals(63, result);
  }


  @Test
  public void testDivide() {
    int result = calculateUsingStrategy(12, 3, "divide");
    assertEquals(4, result);
  }


   // 定义一个测试方法,用assertThrows方法来验证抛出了预期的异常
   @Test
   public void testDivideByZero() {
     assertThrows(ArithmeticException.class,
       () -> calculateUsingStrategy(10,0,"divide"));
   }


   // 定义其他的测试方法,分别测试不同的异常情况


   @Test
   public void testModulusByZero() {
     assertThrows(ArithmeticException.class,
       () -> calculateUsingStrategy(10,0,"modulus"));
   }


   @Test
   public void testSquareRootOfNegativeNumber() {
     assertThrows(ArithmeticException.class,
       () -> calculateUsingStrategy(-4,-2,"square root"));
   }


   // 定义一个测试方法,用assertThrows方法来验证抛出了预期的异常
   @Test
   public void testInvalidOperator() {
     assertThrows(IllegalArgumentException.class,
       () -> calculateUsingStrategy(10,-2,"foo"));
   }
}

最后,数据安全是最大的问题,不要乱贴数据到 ChatGPT,尤其是涉及后端核心存储账户密码、公司核心业务数据、部门核心战略规划等。因为首先,ChatGPT会使用你的问答语料进行训练;其次,你无法预料在什么Prompt提示词下,LLM模型会讲你无意中泄露的信息回答出去。

瑕不掩瑜,ChatGPT为代表的LLM模型,在充当我们无所不知的老师、充当不知疲倦的通用Util代码编写者这些角色时能极大的提高我们的开发效率,尤其在数据分析、前端、单测、重构等领域。

就像文章第一步写的一样,ChatGPT就像是一个百变身份,你可以让他扮演任何角色,而每一个角色都能在这个角色范围内帮助我们获得更美好的生活。

更有意思的用法期待大家的发掘。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值