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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
DeWu Technology
A platform for sharing and discussing tech knowledge, guiding you toward the cloud of technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
