开发者

Pass object or object attribute

I have 2 Classes, Generator and Processor. The former generates an ArrayList that is stored as a member attribute. The latter processes that ArrayList.

My main Class instantiates one of each object and calls the appropriate methods.

What is better practise?

  1. Pass the Generat开发者_运维问答or object to the Processor object's process method
  2. Pass the Generator object's ArrayList to the Processor object's process method


Does the Processor have any reason to care where the data comes from, or request that any more is generated? If not, just pass the data in as general a way as possible - e.g. Iterable<T>, Collection<T> or List<T>.

That way your code is less tightly coupled, and easier to test - heck you don't even have to write Generator before you test Processor, and if there are problems with your Processor unit tests, they're likely to be caused by a bug in Processor, not in Generator.


I would tend to pass the generator, rather than its attributes (exposed via a method, I assume).

Why ? I prefer to keep interfaces and coupling at a higher abstraction layer. By passing the object rather than the attributes I can change the generator at a later stage, and reduce the code sections I have to refactor.

Imagine - at some stage you may want to pass not just the list attribute, but perhaps something else alongside. By passing the higher level object you can limit your refactorings.

Of course this all depends on how widespread the usage of this object is. If you do decide to pass the attribute list, are you passing the list itself, or an unmodifiable copy.


I would wonder why these aren't one object. If Processor changes Generator's state, why isn't that method part of Generator? Better encapsulation that way. An interface with Generator's method would give you some nice flexibility, too. A Generator could have a Processor interface, and you could pass in a concrete instance to change the implementation as needed.

Objects are state and behavior together. Composition of Processor would let you adhere to that and still give you the flexibility to change what's done to the data. Just a thought...


From design point of view your should create method

List<YourType> getList()

in Generator class then call it in main and pass the result to Processor.

Pay attention that in this case Generator and Processor are independent and do not "know" each other, so they can be modified independently. Moreover method returns List (not ArrayList), so the interface does not depend on list implementation too.

And the last point. The list is parametrized (List<YourType>) that makes it safer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜