当前位置:Java -> IntelliJ与Java Spring微服务:利用GitHub Copilot的生产力技巧

IntelliJ与Java Spring微服务:利用GitHub Copilot的生产力技巧

你是否曾经希望有一个编程助手能帮助你更快地编写代码,减少错误,并提高整体生产力?在本文中,我将分享我的经历和GitHub Copilot这个编程伴侣,以及它如何提高了生产力。本文专注于我们用于构建Java Spring微服务的IntelliJ IDE。

六个月前,我开始探索GitHub Copilot,一个由人工智能驱动的编程助手,在IntelliJ IDEA中开发Java Spring微服务项目时。一开始,我的经历并不是很好。我发现它提供的建议不合适,似乎阻碍了开发工作的进展。但我决定坚持使用这个工具,今天,收获了一些好处,还有很大的改进空间。

常见模式

让我们深入探讨GitHub Copilot在一些场景中发挥关键作用的情况。

异常处理

考虑下面的方法:

private boolean isLoanEligibleForPurchaseBasedOnAllocation(LoanInfo loanInfo, PartnerBank partnerBank){
        boolean result = false;
        try {

            if (loanInfo != null && loanInfo.getFico() != null) {
                Integer fico = loanInfo.getFico();
                // Removed Further code for brevity
            } else {
                logger.error("ConfirmFundingServiceImpl::isLoanEligibleForPurchaseBasedOnAllocation - Loan info is null or FICO is null");
            }
        } catch (Exception ex) {
            logger.error("ConfirmFundingServiceImpl::isLoanEligibleForPurchaseBasedOnAllocation - An error occurred while checking loan eligibility for purchase based on allocation, detail error:", ex);
        }
        return result;
    }


最初,如果没有GitHub Copilot,我们需要手动添加异常处理代码。然而,有了Copilot,当我们添加try块并开始添加catch块时,它会自动建议日志消息并生成整个catch块。catch块中的内容都不是手动输入的。此外,当我们开始输入logger.error的时候,Copilot也会自动填充else部分中的其他logger.error。

单元测试的模拟

在单元测试中,我们经常需要创建模拟对象。考虑一种情况,我们需要创建一个PartnerBankFundingAllocation对象列表:

List<PartnerBankFundingAllocation> partnerBankFundingAllocations = new ArrayList<>();
when(this.fundAllocationRepository.getPartnerBankFundingAllocation(partnerBankObra.getBankId(), "Fico")).thenReturn(partnerBankFundingAllocations);


如果我们创建一个对象并将其推送到列表中:

PartnerBankFundingAllocation partnerBankFundingAllocation = new PartnerBankFundingAllocation();
partnerBankFundingAllocation.setBankId(9);
partnerBankFundingAllocation.setScoreName("Fico");
partnerBankFundingAllocation.setScoreMin(680);
partnerBankFundingAllocation.setScoreMax(1000);
partnerBankFundingAllocations.add(partnerBankFundingAllocation);


GitHub Copilot会自动为剩余的对象提供代码建议。我们只需要不断按enter键,并在建议不合适时进行调整。

PartnerBankFundingAllocation partnerBankFundingAllocation2 = new PartnerBankFundingAllocation();
partnerBankFundingAllocation2.setBankId(9);
partnerBankFundingAllocation2.setScoreName("Fico");
partnerBankFundingAllocation2.setScoreMin(660);
partnerBankFundingAllocation2.setScoreMax(679);
partnerBankFundingAllocations.add(partnerBankFundingAllocation2);


日志/调试语句

GitHub Copilot在帮助记录和调试语句方面也表现出色。考虑以下代码片段:

if (percentage < allocationPercentage){
    result = true;
    logger.info("ConfirmFundingServiceImpl::isLoanEligibleForPurchaseBasedOnAllocation - Loan is eligible for purchase");
} else{
    logger.info("ConfirmFundingServiceImpl::isLoanEligibleForPurchaseBasedOnAllocation - Loan is not eligible for purchase");
}


在这个例子中,所有的日志信息语句都是由GitHub Copilot自动生成的。它考虑了代码条件的上下文,并建议相关的日志消息。

代码注释

它有助于在方法顶部添加注释。在下面的代码片段中,方法上面的注释是由Copilot生成的。我们只需要开始输入// This method

// THis method is used to get the loan program based on the product sub type
public static String getLoanProgram(List<Product> products, Integer selectedProductId) {
  String loanProgram = "";
  if (products != null && products.size() > 0) {
    Product product = products.stream().filter(p -> p.getProductId().equals(selectedProductId)).findFirst().orElse(null);
    if (product != null) {
      String productSubType = product.getProductSubType();
      switch (productSubType) {
        case "STANDARD":
          loanProgram = "Standard";
          break;
        case "PROMO":
          loanProgram = "Promo";
          break;
        default:
          loanProgram = "NA";
          break;
      }
    }

  }
  return loanProgram;
}


或者,我们可以使用类似// Q : What is this method doing?的提示。Copilot会添加第二行,// A : This method is used to log the payload for the given api name

// Q : What is this method doing?
// A : This method is used to log the payload for the given api name
public static void logPayload(String apiName, Object payload) {
  try {
    if (payload != null && apiName != null && apiName.trim().length() > 0) {
      ObjectMapper mapper = new ObjectMapper();
      String payloadResponse = mapper.writeValueAsString(payload);
      logger.info("UnderwritingUtility::logPayload - For api : " + apiName + ", payload : " + payloadResponse);
    } else {
      logger.error("UnderwritingUtility::logPayload - Either object was null of api name was null or empty");
    }
  } catch (Exception ex) {
    logger.error("UnderwritingUtility::logPayload - An error occurred while logging the payload, detail error : ", ex);
  }
}


另一个不同方法的示例,我们输入一个提示:// Q : What is this method doing?。Copilot会添加第二行,// A : This method is used to validate the locale from request, if locale is not valid then set the default locale

//Q - Whats below method doing?
//A - This method is used to validate the locale from request, if locale is not valid then set the default locale
public static boolean isLocaleValid(LoanQuoteRequest loanQuoteRequest){
  boolean result = false;
  try{
    if (org.springframework.util.StringUtils.hasText(loanQuoteRequest.getLocale())){
      String localeStr = loanQuoteRequest.getLocale();
      logger.info("UnderwritingUtility::validateLocale - Locale from request : " + localeStr);
      Locale locale = new Locale.Builder().setLanguageTag(localeStr).build();
      // Get the language part
      String language = locale.getLanguage();
      if (language.equalsIgnoreCase("en")){
        result = true;
        if (!localeStr.equalsIgnoreCase(UwConstants.DEFAULT_LOCALE_CODE)){
          loanQuoteRequest.setLocale(UwConstants.DEFAULT_LOCALE_CODE);
        }
      } else if (language.equalsIgnoreCase("es")){
        result = true;
        if (!localeStr.equalsIgnoreCase(UwConstants.SPANISH_LOCALE_CODE)){
          loanQuoteRequest.setLocale(UwConstants.SPANISH_LOCALE_CODE);
        }
      }
    } else{
      result = true;
      loanQuoteRequest.setLocale(UwConstants.DEFAULT_LOCALE_CODE);
    }
  } catch (Exception ex){
    logger.error("UnderwritingUtility::validateLocale - An error occurred, detail error : ", ex);
  }
  return result;
}


结束语

在IntelliJ中使用GitHub Copilot开发Java Spring微服务的好处是显着的。它节省时间,减少错误,并允许我们专注于核心业务逻辑,而不是编写重复的代码。在我们使用GitHub Copilot踏上编程之旅时,这里有一些小贴士:

  • 要有耐心,给它一些时间来学习和识别我们遵循的常见编码模式。
  • 关注建议并根据需要调整它们。有时它会产生幻觉。
  • 尝试不同的场景,以充分发挥Copilot的全部功能。
  • 保持了解Copilot的改进和更新,以充分利用这个尖端工具。
  • 我们可以将其与ChatGPT结合使用。 这里有一篇文章介绍了它如何帮助提高我们的开发生产力。

使用GitHub Copilot愉快编程!

推荐阅读: 程序员中的恶行竞争有多严重?

本文链接: IntelliJ与Java Spring微服务:利用GitHub Copilot的生产力技巧