gpt4 book ai didi

java - 如何拆分此函数以降低认知复杂度?

转载 作者:行者123 更新时间:2023-12-02 02:36:26 25 4
gpt4 key购买 nike

我是 Java 新手,这个菜鸟功能一直困扰着我。我已经下载了 sonarLint 并发现它把这个问题抛在了我的脸上方法的认知复杂性不应该太高。我知道它看起来很难看,但任何人都可以指出我如何重新格式化以具有干燥的概念,并且不具有 SonarLint 提到的高复杂性。

@PostMapping("/adduser")
// @PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<MessageResponse> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
/*
* This controller Creates new user based on all the entities for the user
*
*/
if(dbValue)
{
if (repository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}

if (repository.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}

// Create new user's account
User2 user = new User2(signUpRequest.getUsername(),
signUpRequest.getEmail(),
signUpRequest.getCustomername(),
signUpRequest.getCustomerid(),
signUpRequest.getDescription(),
encoder.encode(signUpRequest.getPassword()));

Set<String> strRoles = signUpRequest.getRoles();
Set<Role2> roles = new HashSet<>();
Role2 e = new Role2();
e.setName("ROLE_ADMIN");
roles.add(e);
user.setRoles(roles);
repository.save(user);

}

else {

if (repository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}

if (repository.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}

// Create new user's account
User1 user = new User1(signUpRequest.getUsername(),
signUpRequest.getEmail(),
signUpRequest.getCustomername(),
signUpRequest.getCustomerid(),
signUpRequest.getDescription(),
encoder.encode(signUpRequest.getPassword()));


Set<String> strRoles = signUpRequest.getRoles();
Set<Role> roles = new HashSet<>();

if (strRoles == null) {
Role userRole = roleRepository1.findByName(URole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository1.findByName(URole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);

break;

default:
Role userRole = roleRepository1.findByName(URole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
}
});
}
user.setRoles(roles);
repository.save(user);
}
return ResponseEntity.ok(new MessageResponse("User Added successfully!"));
}

感谢批评和任何帮助。提前致谢。

最佳答案

  1. 在 Controller 中,您需要使用服务,而不是存储库。在那里创建用户创建方法。
  2. 使用方法创建 UserValidator 接口(interface)(existsByUsername、existsByEmail 实现谓词)可选检查(谓词条件、字符串消息)或者将此方法委托(delegate)给新的验证实用程序类。
  3. 您有重复,可以将其移出条件
if (repository.existsByUsername(signUpRequest.getUsername())) 
return ResponseEntity
.badRequest() // below, you always create a new string and a new message response, use a constant as not to clog the memory
.body(new MessageResponse("Error: Username is already taken!"));
if (repository.existsByEmail(signUpRequest.getEmail()))
return ResponseEntity
.badRequest() // here too
.body(new MessageResponse("Error: Email is already in use!"));
  • signUpRequest.getRoles() 可能会返回一个可选值,或者 Collections.emptyList()(如果为空,而不是 null)
  • 通过 .valueOf() 获取角色,它会使 .forEach() 条件不被使用,并且也会切换情况。
  • 替换这个
  • Role userRole = roleRepository1.findByName(URole.ROLE_USER)
    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
    roles.add(userRole);

    roleRepository1.findByName(URole.ROLE_USER).ifPresent(roles::add);

    关于java - 如何拆分此函数以降低认知复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64254318/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com