apache / shenyu

Apache ShenYu is a Java native API Gateway for service proxy, protocol conversion and API governance.
https://shenyu.apache.org/
Apache License 2.0
8.41k stars 2.92k forks source link

[Discussion] Discussion on shenyu code suggestions #2033

Closed yu199195 closed 2 years ago

yu199195 commented 3 years ago

Hi community

A project's code habits are very important,

especially for projects like ours that are entirely community-based.

So I'd like to invite everyone to come together and suggest better code to make the shenyu project better.

For example :

Null

Optional.ofNullable(xxx).orElse(xxxx)

Objects.isNull() or Objects.nonNull()

impactCn commented 3 years ago

I think when using the map list, if the length can be determined, specify the length as much as possible. so I think this is a good coding practice.

Use map as a container

qinxu2015 commented 3 years ago

Some tools are available Hutool

qicz commented 3 years ago

Remove unnecessary else

        if (redirectHandle.getRedirectURI().startsWith(ROOT_PATH_PREFIX)) {
            ServerHttpRequest request = exchange.getRequest().mutate()
                    .uri(Objects.requireNonNull(UriUtils.createUri(redirectHandle.getRedirectURI()))).build();
            ServerWebExchange mutated = exchange.mutate().request(request).build();
            return dispatcherHandler.handle(mutated);
        } else {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.PERMANENT_REDIRECT);
            response.getHeaders().add(HttpHeaders.LOCATION, redirectHandle.getRedirectURI());
            return response.setComplete();
        }

Use local var replace more getter (shorter statements)

use "redirectURI" replace more "redirectHandle.getRedirectURI()"

        final String redirectURI = redirectHandle.getRedirectURI();
        if (redirectURI.startsWith(ROOT_PATH_PREFIX)) {
            ServerHttpRequest request = exchange.getRequest().mutate()
                    .uri(Objects.requireNonNull(UriUtils.createUri(redirectURI))).build();
            ServerWebExchange mutated = exchange.mutate().request(request).build();
            return dispatcherHandler.handle(mutated);
        } else {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.PERMANENT_REDIRECT);
            response.getHeaders().add(HttpHeaders.LOCATION, redirectURI);
            return response.setComplete();
        }
SaberSola commented 3 years ago

Constant values ​​are not allowed in the code like this checkEnable = Boolean.parseBoolean(System.getProperty("shenyu.upstream.check.enable", "false")); checkTimeout = Integer.parseInt(System.getProperty("shenyu.upstream.check.timeout", "3000")); healthyThreshold = Integer.parseInt(System.getProperty("shenyu.upstream.check.healthy-threshold", "1")); unhealthyThreshold = Integer.parseInt(System.getProperty("shenyu.upstream.check.unhealthy-threshold", "1")); checkInterval = Integer.parseInt(System.getProperty("shenyu.upstream.check.interval", "5000")); printEnable = Boolean.parseBoolean(System.getProperty("shenyu.upstream.check.print.enable", "true")); printInterval = Integer.parseInt(System.getProperty("shenyu.upstream.check.print.interval", "60000"));

midnight2104 commented 3 years ago

Here is my view:

 private ExecutorSubscriber getType(final List<DataTypeParent> list) {
       // ......
 }

public static class RegisterServerExecutorFactory extends AbstractQueueConsumerFactory {

    // ......
}
    public ShenyuAdminResult applyCreate(final AuthApplyDTO authApplyDTO) {
        if (StringUtils.isBlank(authApplyDTO.getAppName())
                || (authApplyDTO.getOpen() && CollectionUtils.isEmpty(authApplyDTO.getPathList()))) {
            return ShenyuAdminResult.error(ShenyuResultMessage.PARAMETER_ERROR);
        }

        //......
    }
    public static void send(final String message, final DataEventTypeEnum type) {
        if (StringUtils.isNotBlank(message)) {
            if (DataEventTypeEnum.MYSELF == type) {
                Session session = (Session) ThreadLocalUtil.get(SESSION_KEY);
                if (session != null) {
                    sendMessageBySession(session, message);
                }
            } else {
                SESSION_SET.forEach(session -> sendMessageBySession(session, message));
            }
        }
    }
 @Override
    protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) {
    //......
    }
ttttangzhen commented 3 years ago
    public DynamicMessage parse(final InputStream inputStream) {
        try {
            //...
        } catch (IOException e) {
            throw new RuntimeException("Unable to merge from the supplied input stream", e);
        }
    }
li-keguo commented 2 years ago

remove never used filed enviroment

@Configuration
public class HttpServerConfig {

    private final Environment environment;

    @Autowired
    public HttpServerConfig(final Environment environment) {
        this.environment = environment;
    }
// ...
}

I want to fix it

JooKS-me commented 2 years ago

All the unit tests are suggested to be a final class, as it is not likely to extend them.

Unit test class

define unit test class as a final class

public final class AesUtilsTest {
    ...
}
yu199195 commented 2 years ago

General

Object

Optional.ofNullable(xxx).orElse(obj)

Objects.isNull(obj) OR Objects.nonNull(obj)

Objects.equals(obj1, obj2)

Object object = null;
for () {
    object = new Object();
}

Collection

List

CollectionUtils.isEmpty(list) or CollectionUtils.isNotEmpty(data)

Map

Set<Map.Entry<String, String>> entrySet = map.entrySet();
Iterator<Map.Entry<String, String>> iter = entrySet.iterator();
while (iter.hasNext()) {
        Map.Entry<String, String> entry = iter.next();

}

String

StringUtils.isEmpty(list) or StringUtils.isNotEmpty(data)

String join(CharSequence delimiter, CharSequence... elements)

Exception

try {
  for () {
  }
} catch () {

}

Resource