오늘의 삽질📢
기존 코드는 아래와 같이 되어 있으며, 내 역할은 resize 메서드에서 리사이징 된 동영상의 바이트를 갖는 새 VideoCustomFile 객체를 반환하는 것이었다.
@Getter
public class VideoCustomFile implements CustomFile {
private final byte[] bytes;
private final String base;
private final String fileName;
public VideoCustomFile(MultipartFile multipartFile) {
this.fileName = addRandomValueFilePrefix(multipartFile);
this.base = "video";
try {
this.bytes = multipartFile.getBytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public CustomFile resize() {
}
}
삽질 과정
"VideoCustomFile에서 매개변수로 MultipartFile을 받고 있으니 byte[]를 MultipartFile로 변환하자 !"
MultipartFile을 구현하는 CustomMultipartFile을 만들었다. 삽질의 결과물↓
@Getter
public class VideoCustomFile implements CustomFile {
private final byte[] bytes;
private final String base;
private final String fileName;
public VideoCustomFile(MultipartFile multipartFile) {
this.fileName = addRandomValueFilePrefix(multipartFile);
this.base = "video";
try {
this.bytes = multipartFile.getBytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public CustomFile resize() {
var customRes = new IVSize();
customRes.setWidth(854);
customRes.setHeight(480);
try {
var resizedVideo =
new IVCompressor().reduceVideoSizeWithCustomRes(bytes, VideoFormats.MP4, customRes);
var customMultipartFile = new CustomMultipartFile(resizedVideo);
return new VideoCustomFile(customMultipartFile);
} catch (VideoException e) {
throw new RuntimeException(e);
}
}
}
수정 후
지현님의 피드백을 토대로 빌더 패턴(Builder Pattern)을 사용하여 코드를 심플하게 만들었다.
VideoCustomFile은 bytes를 필드로 갖기 때문에, 굳이 MultipartFile 구현하여 byte → MultipartFile → byte의 형태로 갈 필요 없이 새로운 생성자 함수(여기서는 빌더 패턴)로 객체를 생성하면 되는 것이다.
@Getter
@Builder
@RequiredArgsConstructor
public class VideoCustomFile implements CustomFile {
private final byte[] bytes;
private final String base;
private final String fileName;
public VideoCustomFile(MultipartFile multipartFile) {
this.fileName = addRandomValueFilePrefix(multipartFile);
this.base = "video";
try {
this.bytes = multipartFile.getBytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public CustomFile resize() {
var customRes = new IVSize();
customRes.setWidth(854);
customRes.setHeight(480);
try {
var resizedVideo =
new IVCompressor().reduceVideoSizeWithCustomRes(bytes, VideoFormats.MP4, customRes);
return VideoCustomFile.builder()
.bytes(resizedVideo)
.base(base)
.fileName(fileName)
.build();
} catch (VideoException e) {
throw new RuntimeException(e);
}
}
}
느낀점
간단한 문제임에도 MultipartFile에만 꽂혀 다른 생성자 함수를 만들 생각을 하지 못했다.
프로그래밍은 문제 해결 능력도 중요하지만 문제를 바라보는 시야가 훨씬 중요함을 매번 느낀다.
문제 해결 과정이 이상하리만큼 복잡하다면 되돌아가 문제를 다시 들여다볼 필요가 있다.
'Coding' 카테고리의 다른 글
[Spring] @JsonInclude와 @JsonIgnore (0) | 2023.07.12 |
---|---|
[AWS S3] 여러 객체 삭제 (0) | 2023.07.10 |
[JAVA] var 사용 시 주의할 점과 장단점 - 지역 변수 추론 타입 (0) | 2023.06.27 |
[REST API] UrlConnection vs. RestTemplate vs. WebClient (0) | 2023.06.24 |
[JAVA] Objects.isNull vs. object == null (0) | 2023.06.12 |