Java 8:在一个对象上应用方法列表

huangapple go评论95阅读模式
英文:

Java 8: Applying a list of methods on one object

问题

  1. 我在代码中有一个特定的部分我想做的就是下面这样但我不知道如何编写以避免代码重复是否有一种方法我可以声明一个方法列表然后将其应用于`productFeatureValidationDto`我目前的方法很新手
  2. public ValidateProductFeatureResponse validateProductFeatureAgainstAllCriteria(ProductFeatureValidationDto productFeatureValidationDto) throws
  3. ApplicationException, ParseException {
  4. ValidateProductFeatureResponse response;
  5. List<Function<ProductFeatureValidationDto, ValidateProductFeatureResponse>> validationMethods = new ArrayList<>();
  6. validationMethods.add(this::validateProductFeatureA);
  7. validationMethods.add(this::validateProductFeatureB);
  8. validationMethods.add(this::validateProductFeatureC);
  9. validationMethods.add(this::validateProductFeatureD);
  10. validationMethods.add(this::validateProductFeatureE);
  11. validationMethods.add(this::validateProductFeatureF);
  12. for (Function<ProductFeatureValidationDto, ValidateProductFeatureResponse> method : validationMethods) {
  13. response = method.apply(productFeatureValidationDto);
  14. if (response.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name())) {
  15. return response;
  16. }
  17. }
  18. return getResponseOnValidationSuccess(productFeatureValidationDto);
  19. }
英文:

I have a particular part in code where all I want to do is the below, but I am at a loss to write in a way that doesn't involve code repetition. Is there a way that I can declare a list of methods, which can be then applied to productFeatureValidationDto. My current approach is noob-ish.

  1. public ValidateProductFeatureResponse validateProductFeatureAgainstAllCriteria(ProductFeatureValidationDto productFeatureValidationDto) throws
  2. ApplicationException, ParseException {
  3. ValidateProductFeatureResponse response;
  4. response = this.validateProductFeatureA(productFeatureValidationDto);
  5. if(response.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name())){
  6. return response;
  7. }
  8. response = this.validateProductFeatureB(productFeatureValidationDto);
  9. if(response.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name())){
  10. return response;
  11. }
  12. response = this.validateProductFeatureA(productFeatureValidationDto);
  13. if(response.getStatus().equalsIgnoreCase(MPResponseStatus.FAILURE.name())){
  14. return response;
  15. }
  16. response = this.validateProductFeatureC(productFeatureValidationDto);
  17. if(response.getStatus().equalsIgnoreCase(MPResponseStatus.FAILURE.name())){
  18. return response;
  19. }
  20. response = this.validateProductFeatureD(productFeatureValidationDto);
  21. if(response.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name())){
  22. return response;
  23. }
  24. response = this.validateProductFeatureE(productFeatureValidationDto);
  25. if(response.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name())){
  26. return response;
  27. }
  28. response = this.validateProductFeatureF(productFeatureValidationDto);
  29. if(response.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name())){
  30. return response;
  31. }
  32. return getResponseOnValidationSuccess(productFeatureValidationDto);
  33. }

Thanks in advance.

答案1

得分: 0

  1. 如果您能够使用Spring框架
  2. 首先您可以定义一个类似这样的接口
  3. ```java
  4. public interface ValidateProduct{
  5. ValidateProductFeatureResponse validate(ProductFeatureValidationDto dto);
  6. }

您的具体验证类实现了这个接口并注册到Spring上下文中。

  1. public ValidateProductFeatureResponse validateProductFeatureAgainstAllCriteria(ProductFeatureValidationDto productFeatureValidationDto) throws
  2. ApplicationException, ParseException {
  3. ValidateProductFeatureResponse response;
  4. Map<String, ValidateProduct> beansOfType = applicationContext.getBeansOfType(ValidateProduct.class);
  5. for (ValidateProduct value : beansOfType.values()) {
  6. response = value.validate(productFeatureValidationDto);
  7. if(response.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name())){
  8. return response;
  9. }
  10. }
  11. return getResponseOnValidationSuccess(productFeatureValidationDto);
  12. }
  1. <details>
  2. <summary>英文:</summary>
  3. if you can use spring framework.
  4. at first you can define an interface like this.
  5. ```java
  6. public interface ValidateProduct{
  7. ValidateProductFeatureResponse validate(ProductFeatureValidationDto dto);
  8. }

Your specific verification class implements this interface and register to srpingcontext

  1. public ValidateProductFeatureResponse validateProductFeatureAgainstAllCriteria(ProductFeatureValidationDto productFeatureValidationDto) throws
  2. ApplicationException, ParseException {
  3. ValidateProductFeatureResponse response;
  4. Map&lt;String, ValidateProduct&gt; beansOfType = applicationContext.getBeansOfType(ValidateProduct.class);
  5. for (ValidateProduct value : beansOfType.values()) {
  6. response = value.validate(productFeatureValidationDto);
  7. if(response.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name())){
  8. return response;
  9. }
  10. }
  11. return getResponseOnValidationSuccess(productFeatureValidationDto);
  12. }

答案2

得分: 0

我建议采取以下方法(示意图):

  1. /**
  2. * 验证函数列表
  3. */
  4. private final static List<Function<ProductFeatureValidationDto, ProductFeatureValidationDto>> VALIDATIONS = new LinkedList<>();
  5. /**
  6. * 填充验证列表
  7. */
  8. static {
  9. VALIDATIONS.add((source) -> {
  10. // 针对特性 A 的测试
  11. return source;
  12. });
  13. VALIDATIONS.add((source) -> {
  14. // 针对特性 B 的测试
  15. return source;
  16. });
  17. VALIDATIONS.add((source) -> {
  18. // 针对特性 C 的测试
  19. return source;
  20. });
  21. }
  22. /**
  23. * 失败判定的断言
  24. */
  25. private final Predicate<ProductFeatureValidationDto> IS_FAILURE = (dto) ->
  26. dto.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name());
  27. /**
  28. * 验证方法
  29. */
  30. public ValidateProductFeatureResponse validateProductFeatureAgainstAllCriteria(
  31. ProductFeatureValidationDto dto
  32. ) throws ApplicationException, ParseException {
  33. // 遍历验证函数并在 dto 实例上调用它们
  34. // 根据失败的验证筛选流
  35. // 在第一个匹配时停止
  36. Optional<ProductFeatureValidationDto> dtoOptional = VALIDATIONS.stream()
  37. .map(action -> action.apply(dto))
  38. .filter(IS_FAILURE)
  39. .findFirst();
  40. // 根据结果应用失败/成功映射
  41. return dtoOptional.isPresent()
  42. ? getResponseOnValidationFailure(dto)
  43. : getResponseOnValidationSuccess(dto);
  44. }
英文:

I would suggest following approach (schematic):

  1. /**
  2. * List of validation functions
  3. */
  4. private final static List&lt;Function&lt;ProductFeatureValidationDto, ProductFeatureValidationDto&gt;&gt; VALIDATIONS = new LinkedList&lt;&gt;();
  5. /**
  6. * Fill validations list
  7. */
  8. static {
  9. VALIDATIONS.add((source) -&gt; {
  10. // test for feature A
  11. return source;
  12. });
  13. VALIDATIONS.add((source) -&gt; {
  14. // test for feature B
  15. return source;
  16. });
  17. VALIDATIONS.add((source) -&gt; {
  18. // test for feature C
  19. return source;
  20. });
  21. }
  22. /**
  23. * Predicate for failure determination
  24. */
  25. private final Predicate&lt;ProductFeatureValidationDto&gt; IS_FAILURE = (dto) -&gt;
  26. dto.getStatus().equalsIgnoreCase(ResponseStatus.FAILURE.name());
  27. /**
  28. * Validation method
  29. */
  30. public ValidateProductFeatureResponse validateProductFeatureAgainstAllCriteria(
  31. ProductFeatureValidationDto dto
  32. ) throws ApplicationException, ParseException {
  33. // iterate over validation functions and invoke them on dto instance
  34. // filter stream by failed validations
  35. // stop on first match
  36. Optional&lt;ProductFeatureValidationDto&gt; dtoOptional = VALIDATIONS.stream()
  37. .map(action -&gt; action.apply(dto))
  38. .filter(IS_FAILURE)
  39. .findFirst();
  40. // apply fuilure / success maping depending on result
  41. return dtoOptional.isPresent()
  42. ? getResponseOnValidationFailure(dto)
  43. : getResponseOnValidationSuccess(dto);
  44. }

答案3

得分: 0

以下是翻译好的内容:

我最终是根据 @Eiden 和 @Alexandra Dudkina 给出的答案来组合我的解决方案的。非常感谢他们。以下是我整个解决方案的要点。

所以,我有两个接口:

  1. IProductFeature:这是一个功能接口,只有一个方法 validate。每个约束都需要实现这个接口。
  2. IProductValidationService:这是一个约定,指定了需要实现的核心方法。方法 validateProductFeatureAgainstAllCriteria 是约定的一部分。

有一个配置文件,将所有的功能导入并按照不同类型的产品进行了组织成列表。这个列表已经被保存在一个以产品类型为键的映射中。因此,这就像一个工厂,根据给定的产品类型提供了一个约束列表。

实现 IProductValidationService 的具体类从配置中获取列表,然后将列表中的所有约束应用于给定的数据传输对象(dto)。通过这种方式,我将所有关注点分离到了不同的部分。
这种方法的实际优势包括:

  • 您可以为单个功能编写广泛的测试用例和文档。
  • 如果将来在 ProductFeatureB(例如)中有政策变更,我只需要创建一个新的具体类,称其为 ProductFeatureBV2,并仅更改配置文件。政策变更可以作为类注释的一部分进行记录。这样,在不改变核心验证方法的情况下,我可以废弃 ProductFeatureB。这使得代码变得非常灵活。

非常感谢社区帮助我正确地完成这个任务。如果还有进一步的改进建议,请提出。

英文:

I ended up composing my solution from the answers given by @Eiden and @Alexandra Dudkina. A big shoutout to them. Below is the crux of my whole solution.

So, I have two interfaces

  1. IProductFeature : This is a functional interface which has only one method validate. Every constraint needs to implement this.
  2. IProductValidationService: This is a contract specifying the core methods needed to be implemented. The method validateProductFeatureAgainstAllCriteria is part of the contract.

There is a config file where all the features have been imported and organised into lists as required for different kinds of products. This list has been kept in a map with the product type as key. So this is acting like a factory which is giving a list of constraint based on a given product type.

The concrete class implementing IProductValidationService gets the list from the config and then applies all the constraints in the list to the given dto.
This way, I have separated all the concerns into separate portions.
The practical advantages to this approach are:

  • You can write extensive test cases and documentation for individual features.
  • If in the future, there is a policy change in ProductFeatureB(for e.g.),all I have to do is create a new concrete class, call it ProductFeatureBV2 and change only config file. The policy changes can be documented as part of the class javadoc. This way without changing core validation method, I can deprecate ProductFeatureB. This makes the code extremely flexible.

Thanks a lot to the community for helping me getting this right. If there are further improvements to be made here, please suggest them.

huangapple
  • 本文由 发表于 2020年9月15日 07:39:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63893132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定