Presented as part of the JetBrains India & Core Java meetup in Thermo Fisher Scientific on 29th Feb. Has videos - so may code examples not display well in this presentation.
35. Refactoring to Builder pattern
import java.time.LocalDateTime;
import java.util.UUID;
public class DeviceBuilder {
private UUID deviceId;
private String name;
private boolean status;
private LocalDateTime startDateTime;
private double generatedPower;
public DeviceBuilder setDeviceId(UUID deviceId) {
this.deviceId = deviceId;
return this;
}
public DeviceBuilder setName(String name) {
this.name = name;
return this;
}
public DeviceBuilder setStatus(boolean status) {
this.status = status;
return this;
}
public DeviceBuilder setStartDateTime(LocalDateTime startDateTime) {
this.startDateTime = startDateTime;
return this;
}
public DeviceBuilder setGeneratedPower(double generatedPower) {
this.generatedPower = generatedPower;
return this;
}
public Device createDevice() {
return new Device(deviceId, name, status, startDateTime, generatedPower);
}
}
36. Refactoring to Builder pattern
var device = new DeviceBuilder().setDeviceId(UUID.randomUUID())
.setName("FSF11")
.setStatus(false)
.setStartDateTime(LocalDateTime.now())
.setGeneratedPower(0)
.createDevice();
var device = new Device(UUID.randomUUID(), "FSF11", false, LocalDateTime.now(), 0);
37. Auto refactor to functional
programming!
Key idea is to use internal iteration (e.g., forEach)
instead of external iteration (e.g., for loops)
Another key idea is to use stream API
instead of “hand-coding” loops
41. This refactoring is manual!
public static void main(String []file) throws Exception {
// process each file passed as argument
// try opening the file with FileReader
try (FileReader inputFile = new FileReader(file[0])) {
int ch = 0;
while( (ch = inputFile.read()) != -1) {
// ch is of type int - convert it back to char
System.out.print( (char)ch );
}
}
// try-with-resources will automatically release FileReader object
}
public static void main(String []file) throws Exception {
Files.lines(Paths.get(file[0])).forEach(System.out::println);
}
42. There are some things money can't buy.
For everything else, there's MasterCard!
43. There are some things you have to hand-code.
For everything else, there's IntelliJ!