问题描述
我有一个客户端库,其中我正在对我的休息服务进行http远程调用,然后我将 List< DataResponse>
返回给正在呼叫我们的客户端图书馆的回应我从我的REST服务中得到,如果有任何包裹在 DataResponse
对象的任何错误。
I have a client library in which I am making http remote calls to my rest service and then I am returning List<DataResponse>
back to the customer who is calling our library with the response I am getting from my REST service along with any errors if there are any wrapped around DataResponse
object.
public class DataResponse {
private final String response;
private final boolean isLink;
private final TypeOfId idType;
private final long ctime;
private final long lmd;
private final String maskInfo;
// below are for error stuff
private final ErrorCode error;
private final StatusCode status;
// constructors and getters here
}
这是我的 ErrorCode
枚举类:
public enum ErrorCode {
// enum values
private final int code;
private final String status;
private final String description;
// constructors and getters
}
这里是我的 StatusCode
枚举类:
public enum StatusCode {
SUCCESS, FAILURE;
}
正如您在我的 DataResponse
class我有很多字段,所以我有一个很长的构造函数,每次当我做一个 DataResponse
对象我有一个大的行与 new DataResponse(.......)
。将来我可能会有更多的字段,但现在我只有这些字段。
As you can see in my DataResponse
class I have lot of fields so basis on that I have a very long constructor and everytime when I make a DataResponse
object I have a big line with new DataResponse(.......)
. In future I might have more fields but for now I only have these fields.
有没有什么更好的方法可以用来制作一个 DataResponse
对象,然后从我的图书馆返回列表< DataResponse>
Is there any better way I can use to make a DataResponse
object and then return back List<DataResponse>
from my library?
推荐答案
请勿立即使用 不适用于需要大量 字段的类型。这是用于具有吨可选字段的类型。
Do not use the builder pattern right away. It is not for types with tons of required fields. It's for types with tons of optional fields.
通过构造函数指定构建器所需的属性。你不是被迫使用方法来定义值,这使得这些值是可选的。
Builders' required properties are specified via the constructor. You are not forced to define values using methods, which makes those values optional.
这使您的对象只能部分构建。使用构建器可能会滥用设计。
This leaves potential for your object being only partially constructed. Using a builder for this would be abuse of the design.
就是说,你应该是什么决定的。
With that said, you should decompose your type. I'm not sure what lmd
or ctime
is, or really what a DataResponse
is supposed to represent, so I cannot tell you in which way you should decompose. But I can tell you cohesion is what determines such.
isLink
, maskInfo
和 idType
可能被分解成一个
DataResponseDetails
对象:
class DataResponseDetails {
private boolean isLink;
private String maskInfo;
private TypeOfId idType;
public DataResponseDetails(boolean isLink, String maskInfo, TypeOfId idType) {
//...
}
}
现在您的 DataResponse
可以由 DataResponseDetails
:
class DataResponse {
private DataResponseDetails details;
private String response;
//...
public DataResponsw(DataResponseDetails details, String response, ...) {
//...
}
}
感觉你的构造函数需要太多的静态?分解更多!
Feel your constructor requires too much still? Decompose more!
这篇关于如何避免制作长的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!