OO设计:在设计对象时如何决定方法参数与实例变量之间的关系 [英] OO Design: how to decide between method parameter vs instance variable while designing an object

查看:93
本文介绍了OO设计:在设计对象时如何决定方法参数与实例变量之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个系统,在那里我得到一堆输入,这些输入被处理以产生一些持续的输出。



说我需要做一些验证请求,我应该如



选项1:

 验证器validator = new Validator(); 
validator.validate(request);



选项2: p>

 验证器验证器=新的验证器(请求); 
validator.validate();

我目前正在使用Option 1,因为它更容易将Validator实例注入到我的请求处理程序类中。
让我们说,我需要从Validator中调用多个方法,那么使用相同的参数多次调用验证器(对于不同的方法)来说,它感觉更为程序化。



在考虑决定这些之间时,我还提出了第三个选项。

 验证器验证器= Factory.createValidator(请求); 
validator.validate();

在此工厂注入我的课程。



在这些选项中进行决定时,应该是我的指导因素。

解决方案

p> I vote for validator.Validate(request)。我的理由是,这在语义上更有意义,并且是自我记录的。



对我来说,请求是正在验证的。所以验证器验证请求。这个代码几乎说明了这一点。如果验证器验证一些不同的请求,这种方法变得更加合适。然而,可以认为,如果请求在验证器的生命周期内没有更改,则构造函数注入可能是更好的方法。



它也是可测试的。 >

I am designing a system where I get a bunch of inputs which are processed to generate some outputs which are persisted.

Say I need to do some validation on the request, should I do it as

Option 1:

Validator validator = new Validator();
validator.validate(request);

or

Option 2:

Validator validator = new Validator(request);
validator.validate();

I am currently using Option 1 as it makes it easier to inject the Validator instance into my request handler class. Let us say I need to call more than one method from the Validator, then it feels more procedural to call the validator multiple times(for different methods) with the same parameter.

While thinking about deciding between these, I also came up with a 3rd option

Validator validator = Factory.createValidator(request);
validator.validate();

In this the Factory is injected into my class.

What should be my guiding factor when deciding among these options.

解决方案

I vote for validator.Validate(request). My reason is that this makes more sense semantically and is self-documenting.

To me, the request is what's being validated. So the validator validates requests. The code pretty much spells this out. This approach becomes even more appropriate if the validator will validate a number of different requests. Whereas, it could be argued that constructor injection might be a better approach if the request doesn't change during the lifetime of the validator.

It's also testable.

这篇关于OO设计:在设计对象时如何决定方法参数与实例变量之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆