Optimizing and Testing Java Code with ChatGPT: A Step-by-Step Guide

This guide shows how to prompt ChatGPT as a Java developer, transform a flawed if‑else calculator into a clean Strategy‑pattern implementation, and write comprehensive JUnit tests, while warning about code‑security risks when using large language models.

DeWu Technology
DeWu Technology
DeWu Technology
Optimizing and Testing Java Code with ChatGPT: A Step-by-Step Guide

Demonstrates how to use ChatGPT (New Bing, GPT‑4) to act as a Java software developer, guiding through four steps: role prompting, presenting a poorly written Java method, refactoring it with a strategy pattern, and adding unit tests.

Step 1 – Prompt

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."

Step 2 – 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;
}

Step 3 – Refactored code using Strategy pattern

// Define a strategy interface
public interface OperationStrategy {
  int apply(int a, int b);
}

// Enum of operators with corresponding strategies
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); }
}

// Helper method
public int calculateUsingStrategy(int a, int b, String operatorName) {
  Operator operator = Operator.valueOf(operatorName.toUpperCase());
  return operator.apply(a, b);
}

Step 4 – Unit tests with JUnit

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

public class CalculatorTest {

  @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);
  }

  @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"));
  }

  @Test
  public void testInvalidOperator() {
    assertThrows(IllegalArgumentException.class,
      () -> calculateUsingStrategy(10,-2,"foo"));
  }
}

The guide also warns about data‑security risks when sharing code with LLMs and mentions a related offline security‑focused tech salon.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaChatGPTCode Optimizationunit testing
DeWu Technology
Written by

DeWu Technology

A platform for sharing and discussing tech knowledge, guiding you toward the cloud of technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.