b******y 发帖数: 1684 | 1 比如有个validation的函数,如果pass就是返回一个GoodO
如果不pass的,有多种可能性 BadFlag1, BadFlag2...
我现在的design是return a ResponseO
{
enum status;
GoodO g;
}
然后在代码里面很多的
if ...
status = Good; / g = New GoodO(...);
else
if ...
status = BadFlag1;
else
if ...
status = BadFlag2;
else
....
好像很丑陋啊。。。想过用throw exception的方法,不知道是不是更好? |
g**********y 发帖数: 14569 | 2 主要看你接受端想怎么处理,如果接受方只显示Error message, 那就一种Exception就
够了;如果接受方要根据error code进行不同处理,那inheritance更好,比如:
GoodO, BadO1, BadO2, BadO3, ... all extend from ReceiveO
validator里就是:
if ... return GoodO;
if ... return BadO1;
...
if ... return BadOn;
Receiver里就是:
ReceiveO obj = validate();
obj.postProcess();
这样你就把相应的post-process delegate到child class里。 |
g*****g 发帖数: 34805 | 3 Since it's enum, why don't you use switch?
【在 b******y 的大作中提到】 : 比如有个validation的函数,如果pass就是返回一个GoodO : 如果不pass的,有多种可能性 BadFlag1, BadFlag2... : 我现在的design是return a ResponseO : { : enum status; : GoodO g; : } : 然后在代码里面很多的 : if ... : status = Good; / g = New GoodO(...);
|
b******y 发帖数: 1684 | 4 the validation logic in the ifs are not enum ah..
for example, if (length < 8) --> too short
if (no lower case) --> ...
【在 g*****g 的大作中提到】 : Since it's enum, why don't you use switch?
|
b******y 发帖数: 1684 | 5 our code style requires only 1 return xxx at the end of any method...
the reason is this would make code easier to read/maintain
thus I got this awkward situation...
【在 g**********y 的大作中提到】 : 主要看你接受端想怎么处理,如果接受方只显示Error message, 那就一种Exception就 : 够了;如果接受方要根据error code进行不同处理,那inheritance更好,比如: : GoodO, BadO1, BadO2, BadO3, ... all extend from ReceiveO : validator里就是: : if ... return GoodO; : if ... return BadO1; : ... : if ... return BadOn; : Receiver里就是: : ReceiveO obj = validate();
|
g*****g 发帖数: 34805 | 6 Actually, it's not that bad. The design pattern may encourage delegating
the logic to subclass, but in reality it's easier to maintain such code
in one place, unless the logic is very complicated and count on many other
classes.
My experience with this is to use return if possible so you don't have many
else if. Also use function to refactor longer logic. And most important of
all, use a unit test to guard your conditions.
【在 b******y 的大作中提到】 : our code style requires only 1 return xxx at the end of any method... : the reason is this would make code easier to read/maintain : thus I got this awkward situation...
|
F****n 发帖数: 3271 | 7 goodbug is right, you should use switch because it is based on hash table
which is pseudo-constant. A series of if-then-else is linear.
If you want to map functions, you can use a Map to
map the handler, where YourHandler is an interface that encapsulate your
calling function.
That's the best solution to your problem in Java.
【在 b******y 的大作中提到】 : the validation logic in the ifs are not enum ah.. : for example, if (length < 8) --> too short : if (no lower case) --> ...
|