Write an ApiResponse class with a private constructor and public static factories ok(data) and error(code, message); fields are private final with public getters, and print several responses.
Solution
Main.java
final class ApiResponse {
private final int status;
private final String data;
private final String error;
private ApiResponse(int status, String data, String error) { this.status = status; this.data = data; this.error = error; }
public static ApiResponse ok(String data) { return new ApiResponse(200, data, null); }
public static ApiResponse error(int status, String message) {
if (status < 400 || status > 599) throw new IllegalArgumentException("not an error status: " + status);
return new ApiResponse(status, null, message);
}
public boolean isOk() { return error == null; }
public int status() { return status; }
@Override public String toString() { return isOk() ? status + " " + data : status + " ERROR " + error; }
}
public class Main {
public static void main(String[] args) {
System.out.println(ApiResponse.ok("{\"user\":\"asha\"}"));
System.out.println(ApiResponse.error(404, "user not found"));
ApiResponse r = ApiResponse.error(503, "try later");
System.out.println(r.isOk() + " " + r.status());
try {
ApiResponse.error(200, "oops");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Output Verified by compiling and running
200 {"user":"asha"}
404 ERROR user not found
false 503
not an error status: 200
With the constructor private, only the two factories can create responses, so an "ok" with an error message cannot exist.
More Access Modifiers and Packages practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!