[英]How to avoid null implementation of interface methods
我的设计也可能存在一些问题。 这是我的问题:
我首先有AbstractCustomAuthHandler;
所以在设计的开始;
但现在有一些实现,一些IUser的实现不应该有IRole对象。 所以现在我为这个实现返回null,我不喜欢它。 我想过拆分接口但是找不到AbstractCustomAuthHandler满足的解决方案。 这是一个图表和代码:
这是AbstractCustomAuthHandler的一部分
IUser userAuth= this.getUserAuth();
final Response userResponse= userAuth.findUser();
// ...
Map<String, Object> attributes= userAuth.getMappedAttributes();
// ...
IRole roleAuth= userAuth.getRoleAuth();
if (roleAuth!= null)
{
final Response rolesResponse = roleAuth.findRolesBy();
}
// ....
这是AuthMethodWithoutRole,我有关于返回null的问题
public class AuthMethodWithoutRole implements IUser
{
@Override public Response findUserBy( )
{
// some logic
}
@Override public IRole getRoleAuth( )
{
return null;
}
}
这是IUser界面
public interface IUser extends IAuth
{
Response findUserBy();
IRole getRoleAuth();
}
这是IRole接口
public interface IRole
{
Response findRolesBy( );
}
为什么你不只是创建一个类NullRole实现IRole? 所以你不需要AuthMethodWithoutRole。 您可以使用默认的AuthMethod处理“NullRole”。
如果您想从AbstractCustomAuthHandler
删除角色检查,则应重新考虑您的设计。 您可以移动在IUser类/子类中使用该角色的逻辑。
这样,每个IUser实现都会在需要时使用它。
这种方法听起来像DDD方法。 使对象根据其性质/定义进行协作,不要让人工对象执行整个逻辑( AbstractCustomAuthHandler
)。
这个逻辑:
IUser userAuth= this.getUserAuth();
final Response userResponse= userAuth.findUser();
// ...
Map<String, Object> attributes= userAuth.getMappedAttributes();
// ...
IRole roleAuth= userAuth.getRoleAuth();
if (roleAuth!= null)
{
final Response rolesResponse = roleAuth.findRolesBy();
}
将在IUser
完成:
IUser userAuth= this.getUserAuth();
Response response = userAuth.computeResponse(...);
或者可能 :
ResponsePart responsePart = userAuth.computeSomePartOfTheResponse(...);
// and use responsePart to complete the logic.
当然, IUser
子类可以依赖于超类或接口中定义的一些基本方法来执行公共逻辑。
如果你不想改变你的方法,那就是你想继续检索IUser对象的角色信息,以便让另一个类( AbstractCustomAuthHandler
)使用它,你需要为操作它们的类操作统一的IUser 。
因此,即使对于没有这些角色的子类,也需要提供空或空角色的实现。
如果你采用这种方法,我不认为这是一个设计问题。 作为改进,您可以考虑:
在返回null的接口中定义默认实现。
或者将返回类型更改为Optional<Role>
并在接口中定义一个返回empty
Optional的默认实现。
这会给:
public interface IUser extends IAuth
{
Response findUserBy();
default Optional<IRole> getRoleAuth(){return Optional.empty()}
}
现在只在需要时才覆盖该方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.