开发者

Getters and Setters, threading and Java

In school they taught us to use getters and setters in Java. Recently I've been reading such things are 开发者_如何学编程bad and not OOP. Ok, so I can make some code which only sets data by using the constructor and returns the required data.

How do you not use getters with threads? When you execute a thread it's type is always void and there are on global variables in java . . .. So how do you go about getting data back from a thread without a getter method?


Recently I've been reading such things are bad and not OOP.

Quite the opposite, getters and setters are one of the cornerstones of OOP (where such side effects are desired).

You can however still pass constructor arguments before starting a thread, e.g.,

new Thread(new MyRunnableObject(args)).start();

If you desire it to return a result without getters, you'd best implement a Callback which the thread executes e.g, on completion.


Getters or setters by themselves are not bad OO design.

What is bad is coding practice which includes a getter AND a setter for EVERY single member automatically, whether that getter/setter is needed or not (coupled with making members public which should not be public) - because this basically exposes class's implementation to outside world violating the information hiding/abstraction. Sometimes this is done automatically by IDE, which means such practice is significantly more widespread than it's hoped for.


Recently I've been reading such things are bad and not OOP Who tells such crap?

Getters and Setters really are a best practice. They provide a layer for property-access so you have a single point of change when the internal workings of an accessor in a class need to be modified. You can override them in child-classes if you need to encapsulate different access strategies.

Concerning the threading:

You should use something like a threadsafe collection, I guess there are classes out there for the communication between threads. Use a threadsafe queue, which one thread writes to and the other reads from. I bet there are some good libraries for that out there. You don't really need globals. Just pass the same reference to both the classes that need to communicate across threads. You can also communicate via pipes or TCP, but that is more for inter-process communication.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜