IntelliJ and Java Spring Microservices: Productivity Tips With GitHub Copilot
Explore productivity tips that can enhance your Java Spring Microservices development experience in IntelliJ, all made possible with the help of GitHub Copilot.
Join the DZone community and get the full member experience.
Join For FreeHave you ever wished for a coding assistant who could help you write code faster, reduce errors, and improve your overall productivity? In this article, I'll share my journey and experiences with GitHub Copilot, a coding companion, and how it has boosted productivity. The article is specifically focused on IntelliJ IDE which we use for building Java Spring-based microservices.
Six months ago, I embarked on a journey to explore GitHub Copilot, an AI-powered coding assistant, while working on Java Spring Microservices projects in IntelliJ IDEA. At first, my experience was not so good. I found the suggestions it provided to be inappropriate, and it seemed to hinder rather than help development work. But I decided to persist with the tool, and today, reaping some of the benefits, there is a lot of scope for improvement.
Common Patterns
Let's dive into some scenarios where GitHub Copilot has played a vital role.
Exception Handling
Consider the following method:
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;
}
Initially, without GitHub Copilot, we would have to manually add the exception handling code. However, with Copilot, as soon as we added the try block and started adding catch blocks, it automatically suggested the logger message and generated the entire catch block. None of the content in the catch block was typed manually. Additionally, other logger.error in the else part is prefilled automatically by Co-Pilot as soon as we started typing in logger.error.
Mocks for Unit Tests
In unit testing, we often need to create mock objects. Consider the scenario where we need to create a list of PartnerBankFundingAllocation
objects:
List<PartnerBankFundingAllocation> partnerBankFundingAllocations = new ArrayList<>();
when(this.fundAllocationRepository.getPartnerBankFundingAllocation(partnerBankObra.getBankId(), "Fico")).thenReturn(partnerBankFundingAllocations);
If we create a single object and push it to the list:
PartnerBankFundingAllocation partnerBankFundingAllocation = new PartnerBankFundingAllocation();
partnerBankFundingAllocation.setBankId(9);
partnerBankFundingAllocation.setScoreName("Fico");
partnerBankFundingAllocation.setScoreMin(680);
partnerBankFundingAllocation.setScoreMax(1000);
partnerBankFundingAllocations.add(partnerBankFundingAllocation);
GitHub Copilot automatically suggests code for the remaining objects. We just need to keep hitting enter and adjust values if the suggestions are inappropriate.
PartnerBankFundingAllocation partnerBankFundingAllocation2 = new PartnerBankFundingAllocation();
partnerBankFundingAllocation2.setBankId(9);
partnerBankFundingAllocation2.setScoreName("Fico");
partnerBankFundingAllocation2.setScoreMin(660);
partnerBankFundingAllocation2.setScoreMax(679);
partnerBankFundingAllocations.add(partnerBankFundingAllocation2);
Logging/Debug Statements
GitHub Copilot also excels in helping with logging and debugging statements. Consider the following code snippet:
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");
}
In this example, all the logger information statements are auto-generated by GitHub Copilot. It takes into account the context of the code condition and suggests relevant log messages.
Code Commenting
It helps in adding comments at the top of the method. In the code snippet below, the comment above the method is generated by the Copilot. We just need to start typing in // 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;
}
Alternatively, we can use a prompt like // Q : What is this method doing?
. Copilot will add the second line, // 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);
}
}
Another example of a different method we type in a prompt: // Q : What is this method doing?
. Copilot will add the second line, // 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;
}
Closing Thoughts
The benefits of using GitHub Copilot in IntelliJ for Java Spring Microservices development are significant. It saves time, reduces errors, and allows us to focus on core business logic instead of writing repetitive code. As we embark on our coding journey with GitHub Copilot, here are a few tips:
- Be patient and give it some time to learn and identify common coding patterns that we follow.
- Keep an eye on the suggestions and adjust them as needed. Sometimes, it hallucinates.
- Experiment with different scenarios to harness the full power of Copilot.
- Stay updated with Copilot's improvements and updates to make the most of this cutting-edge tool.
- We can use this in combination with ChatGPT. Here is an article on how it can help boost our development productivity.
Happy coding with GitHub Copilot!
Opinions expressed by DZone contributors are their own.
Comments