Skip to main content

Apply Best Practices for Code Implementation

๐ŸŽฏcontext

In this document you can find some best practice code samples that might be helpful while writing code for Java domain service projects.

Descriptionโ€‹

This How-To will show you best practices that needs to be applied in different scenarios during the Java Domain Service implementation. The different scenarios will offer several implementation tips which will help you understand and streamline the code.

Examplesโ€‹

Chained Responseโ€‹

Sometimes code can be written in a more concise way by using the chaining style. See the follwoing example where chaining is used rather than an if-else block to either respond with the found entity or an NOT_FOUND status, if the requested entity couldn't be found.

Optional<de.knowis.pe.peproctl.sdk.domain.cat.entity.CatalogItem> loaded = repo.findById(id);

ResponseEntity<CatalogItem> res = loaded.map(item -> CatalogItemMapper.toApiModel(item))

.map(item -> ResponseEntity.ok(item)).orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).build());

return res;

Use a logger for every incoming request and responseโ€‹

The following example shows how you can implement some default logging for all requests by implementing a filter.

@Component
public class RequestResponseLoggingFilter implements Filter {

private static Logger log = LoggerFactory.getLogger(RequestResponseLoggingFilter.class);

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
log.debug("Logging Request {} : {}", req.getMethod(), req.getRequestURI());
chain.doFilter((HttpServletRequest) request, (HttpServletResponse) response);
log.debug("Logging Response :{}", res.getContentType());
}

}

Use Exception / Error Handlerโ€‹

This is an example using a global exception handler together with a custom exception to centralize handling of errors.

package de.knowis.nlb.abcimds.api.exception;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import de.knowis.nlb.abcimds.sdk.api.v1.model.ErrorResponse;
@ControllerAdvice
public class GlobalExceptionHandler {
private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(HttpErrorRuntimeException.class)
public ResponseEntity<?> handleHttpErrorRuntimeException(HttpServletRequest req, HttpErrorRuntimeException e) {
log.info("HttpErrorRuntimeException [method={}, requestUrl={}, constraintViolations={}, exceptionMessage={}]",
req.getMethod(), req.getRequestURL(), e.getMessage());
log.debug("HttpErrorRuntimeException [method={}, requestUrl={}, constraintViolations={}]", req.getMethod(),
req.getRequestURL(), e);
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setStatusCode(e.getHttpStatus().value());
errorResponse.setMessage(e.getMessage());
errorResponse.setDescription(e.getDescription());
return ResponseEntity.status(e.getHttpStatus()).body(errorResponse);
}
}
package de.knowis.nlb.abcimds.api.exception;
import org.springframework.http.HttpStatus;
public class HttpErrorRuntimeException extends RuntimeException {
private static final long serialVersionUID = -1728239447170591463L;
private HttpStatus httpStatus;
private String message;
private String description;
public HttpErrorRuntimeException(HttpStatus httpStatus, String message) {
this.httpStatus = httpStatus;
this.message = message;
}
public HttpErrorRuntimeException(HttpStatus httpStatus, String message, String description) {
this.httpStatus = httpStatus;
this.message = message;
this.description = description;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
public void setHttpStatus(HttpStatus httpStatus) {
this.httpStatus = httpStatus;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

How to use findByExampleโ€‹

This example is about finder methods and uses an example object to find similar objects matching in the details specified in the example.

public List<AbciMatrix> find(FindAbciMatrizenInput findAbciMatrizenInput) {

ExampleMatcher matcher = ExampleMatcher.matchingAll().withIgnorePaths("id", "schemaVersion", "dbModelVersion");
Example<AbciMatrix> example = Example.of(entityBuilder.getAbcim().getAbciMatrix()
.setStatus(findAbciMatrizenInput.getStatus()).setGeschaeft(findAbciMatrizenInput.getGeschaeft()).build(),
matcher);

List<AbciMatrix> queryResult = repo.getAbcim().getAbciMatrix().findAll(example);

return queryResult;
}
๐ŸŒŸresult

Congratulations! You have learned some best practices for different scenarios that you can use to implement the Java domain service.