r/javahelp • u/lppedd • Dec 19 '20
Representing "terminated/disconnected" state
Let's say we have a Connection object
interface Connection {
void connect();
void doSomething();
void disconnect();
}After disconnet-ing, a user could still potentially doSomething.
How do you guys prefer to handle this situation?
Internally checking the object state at every method invocation is what I usually see, but I've always seen this as bad practice. Imagine having dozens of such doSomething methods.
5
u/codereign fallible moderator Dec 19 '20
Checkout the io and nio packages. Also instead of disconnect consider implementing the closable interface. Generally cloasables have a very well defined usage pattern and it's understood it'll throw and exception of you violate that pattern.
2
u/lppedd Dec 19 '20
Yep, NIO is the first thing I checked since I'm working over socket now. Each relevant method does check the internal state and throws an appropriate exception. But still, reading about what others do is interesting.
3
u/msx Dec 19 '20
It's not that bad, but it's a little verbose. Pretty diffused. I don't think it's common to have a lot of methods to guard,or maybe they all call internal methods that are guarded.
Maybe a different solution could be one you have a private object on which to delegate all calls. When you disconnect, replace it with something that always throws exception or something.
1
u/lppedd Dec 19 '20
Yeah, the wrapping object could check the delegated one's state. So the delegate doesn't include checking code. Delegation via compile time class (bytecode) generation is what I'd call a win. But it's a pretty custom solution.
Btw, think about a
Chatobject. Each call has to check the chat state. And a chat can expose many features.3
u/HecknChonker Extreme Brewer Dec 19 '20
What you are talking about here is really an implementation detail of the Connection. The encapsulation principle says that a Connection needs to handle it's own state and should guarantee to it's callers that it cannot get into a incorrect state.
Trying to handle this logic outside of the Connection is going to lead to messier and more confusing code overall. Someone looking at the Connection might not be aware that an important implementation detail was left out of the class, and it might lead to them using the object incorrectly.
/u/codereign has a great point here. Making the object Closable is the correct answer. Any method that necessarily requires the connection to be open should verify that before proceeding.
As an example, a java socket will throw an IOException if you try to access the InputStream or OutputStream when the socket is closed. https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#getOutputStream()
Internally checking the object state at every method invocation is what I usually see, but I've always seen this as bad practice. Imagine having dozens of such doSomething methods.
Imagine calling doSomething in dozens of places. It's better to check inside doSomething than to check every time it's called.
2
2
u/msx Dec 19 '20
I'm not a fan of those kind of tricks as they hinder readability and understandability of code. Also it would be pretty overkill to call in bytecode generation for this issue. In that spirit, a proxy implementation could suffice. You could centralize the check while routing each method separately.
2
u/lppedd Dec 19 '20
Sounds fair. Thanks!
My question mostly arises from the fact writing checks is an error prone activity. One can forget to add them, or one can copy-paste irrelevant pieces.2
5
u/LiteratureStriking Dec 20 '20
This is a violation of the Interface Segregation Principle, because you are coupling connection control with connection utilization. Ideally, doSomething shouldn't be in the same interface as connect and disconnect.
For example, the JDBC Connection interface doesn't have any doSomething type operations in it. If you want to execute SQL, you use the Connection interface to create an object implementing another interface Statement, and Statement has an executeQuery method, which actually executes the SQL query.
1
Dec 20 '20
It’s not pretty, but could make a Boolean isOn method. Everytime disconnected set to false, and before performing an action put an if statement with isOn as condition.
•
u/AutoModerator Dec 19 '20
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.