I researched a bit and i'm not sure about this.
I have a proccess that need returns a bunch of data. I put the data in a Result class:
public final class Result implements Serializable {
/** Inmmutable class
*
*/
private static final long serialVersionUID = -916675731077365794L;
private final String nick;
private final LocalDateTime date_init;
private final LocalDateTime date_end;
private final double profit;
private final double tax;
private final Double balance;
private final int inputs;
private final List<CustomObjects> inputs_by_month;
// Keep going...
// constructor
Results(String nick, LocalDateTime date_init, LocalDateTime date_end,
double profit, double tax/* Keep going... */) {
super();
this.nick = nick;
this.date_init = date_init;
this.date_end = date_end;
this.profit = profit;
this.tax = tax;
/* Keep going... */
}
/* getters here */
}
I'm not sure how i could create this object. Yeah, i could use a Factory class
public final class ResultFactory {
private String nick;
private LocalDateTime date_init;
private LocalDateTime date_end;
private double profit;
private double tax;
private Double balance;
private int inputs;
private List<CustomObjects> inputs_by_month;
// Keep going...
public Result getResult()
{
return Result(nick,date_init,date_end,/*...*/);
}
public void setNick(String nick)
{
this.nick = nick;
}
public void setDateInit(LocalDateTime date_init){
this.date_init = date_init;
}
/* ... */
}
But i am duplicating the entire structure. It doesn't look right.
I'm looking for a pattern for store data in a inmutable class.
What you can do is split your Result
class in more classes.
public class Result {
private final String nick;
private final LocalDateTime date_init;
private final LocalDateTime date_end;
private final MonetaryResult monetaryResult;
private final InputsResult inputsResult;
Results(String nick, LocalDateTime date_init, LocalDateTime date_end, MonetaryResult monetaryResult, InputsResult inputsResult) {
...
this.monetaryResult = monetaryResult;
this.inputsResult = inputsResult;
...
}
}
This way, you could avoid having a class with many properties, which makes difficult its construction.
You can construct your result object like this.
new Restult(
"nick",
createDate(),
createDate(),
new MonetaryResult(...),
...
)
You can use Lombok @Value
and @Builder
annotations:
@Builder
@Value
public final class Result implements Serializable {
String nick;
LocalDateTime date_init;
LocalDateTime date_end;
double profit;
double tax;
Double balance;
int inputs;
List<CustomObjects> inputs_by_month;
// Keep going...
}
Lombok will generate for you:
private final
keywords on fields toString
, equals
and hashCode
methods Result.builder().nick("foo").build()
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.