Java - is better to directly access other object components or through method?
this is more theoretical question. I have written simple chat with my friend. We have开发者_如何转开发 few classes, but most important are Client (handles network stuff) and GUI (self-explanatory :)).
Now, I write messages into JTextArea. And I want to ask, from the OOP theory, is it better to send to Client reference to JTextArea and directly append text to it, OR is better to create function in GUI which makes the same and call it from Client? When message comes from server of course.
I know the most efficient way is the first, but I believe its not the proper OOP way. I have found that OOP is less efficient than procedural, not becouse its more complex on abstraction, but becouse many OOP standarts just seems ineficient. Thanks.
You should encapsulate the functionality of the GUI. The client shouldn't have any knowledge of its inner workings whatsoever. Instead, you should provide a semantically meaningful public method that describes the task it will perform - in this case updating the display.
Ideally you should have an interface that represents your GUI actions also - this will decouple the client from the GUI and will mean you can have multiple UIs implement the interface and the client doesn't care which UI it is using.
Desktop applications usually consist of a business layer and a presentation layer. The GUI belongs to the presentation layer. I presume Client belongs to the business layer.
The business layer should not know anything about the presentation layer.
In this case, the Client can introduce an interface. Something like:
interface MessageListener {
void handleNewMessage();
}
And then, we can have an observer pattern. The client invoke registered MessageListener. And the GUI implements MessageListener and registry to the Client.
Regarding this:
I know the most efficient way is the first, but I believe its not the proper OOP way. I have found that OOP is less efficient than procedural, not becouse its more complex on abstraction, but becouse many OOP standarts just seems ineficient. Thanks.
For about 99% of all code you'll ever write, efficiency is totally and utterly irrelevant because it won't run often enough to notice any inefficiencies. And that's certainly the case here: GUI event handling code is about the most performance-uncritical code there is because user's can't even notice delays of less than 1/100th of a second, and on modern hardware that's an eternity.
Furthermore, for 100% of all code you'll ever write, being complete and correct matters more than efficiency. Nobody cares how efficient your code does the wrong thing. And producing correct and complete code is much easier when it's maintainable, clean, decoupled. Which is exactly what OO and its conventions try to (and generally do) make easier.
精彩评论