Is this line in the official Java tutorials inaccurate? [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm looking here at a summary of "interfaces" in Java: http://docs.oracle.com/javase/tutorial/java/IandI/summary-interface.html
The first line states, "An interface defines a protocol of communication between two objects."
Is that really accurate? From my understanding, an interface is just a contract promising to offer some set of members/methods, which could be used by any arbitrary number of clients (so long as they have proper access per the access modifiers). Am I missing some "other side" of the contract which would make an interface "between two objects"?
EDIT: From the answers/comments (and the votes to close! :-[ ), I think I have it figured out. I think I was just getting hooked on the "between two objects" and assuming it meant "between ONLY two objects", which was apparently a wrong assumption. Thanks!

From my understanding, an interface is just a contract promising to
offer some set of members/methods
That's pretty close to the definition of a protocol.

I wouldn't call it inaccurate. If anything, it's just an oversimplification.
You're right that any number of clients can use the object implementing an interface. And for that matter, you would be right to say that the client doesn't have to be an object (it could be a static method in a class, meaning it's hard to say that the client is an object). But the point about defining a protocol for communication is not wrong, even if requires thinking through a different paradigm.

Whenever you use an object you use it always from another object. You don't call a method from more than an object at the same time.
So if A offers an interface, then B relies on it and C too but A is still offering an interface to B and C separately.

The method signatures defined in the Interface are the enforcement. You have the implementer of the interface on one side, and the client on the other who calls the implementer.

Related

Is it preferable to use runnable instead of callable in java, in terms of performance? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I just started learning a functional language (Scala) and one of the claims/recommendations made is, "you should try to use react instead of recieve" method while doing multithreading. To make it clear, react doesn't return any value but recieve does. They have their own reasons to support this recommendation. As Scala works on the JVM. It is making me curious to think if using Callable is a more costly affair than using Runnable in Java?
Does anyone has any experience with the same or comments on this?
Runnable and Callback have the same "performance" as they are just Interfaces.
The two interfaces have slight API differences - a type compatible with the consuming API must be used; that is all.
This has nothing to do with Scala or react vs. recieve in Actors; the question boxes itself into the wrong corner.
Wellll, you're really mixing different concepts here.
The reason to use react instead of receive is that each actor with a receive requires its own thread. So you've got one thread per actor. react on the other hand is handled by a pool of threads that will run that message on that actor and then go on to the next actor and message. (This really only permits you to be reactive--you can't wait for a certain amount of time.)
On the other hand, the Runnable and Callable interfaces are just ways to package up code in Java depending on whether you just want it to do stuff (Runnable) or return a value (Callable). The interfaces themselves don't have any difference in performance, but in order to get a Callable return value back to you there is additional stuff that needs to happen, so if you could write it either way you'd possibly be better off using something that only requires a Runnable. (In practice, this means starting a thread instead of a future, probably.) But the implementation details matter so much that you can't really make any general recommendations on the basis of the interface alone. You need to know how the interface is actually being used in the actual class you're calling.

What is the use of a ForwardingMap in Guava? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am scratching my head over understanding the use of a ForwardingMap?
What are the cases that one might use it?
ForwardingXxx classes provide decorator pattern implementations for all JDK and Guava collections, including Map.
Read more on Guava's wiki and in Effective Java 2nd Edition, Item 16: Favor composition over inheritance:
To summarize, inheritance is powerful, but it is problematic because
it violates encapsulation. It is appropriate only when a genuine
subtype relationship exists between the subclass and the superclass.
Even then, inheritance may lead to fragility if the subclass is in a
different package from the superclass and the superclass is not
designed for inheritance. To avoid this fragility, use composition and
forwarding instead of inheritance, especially if an appropriate
interface to implement a wrapper class exists. Not only are wrapper
classes more robust than subclasses, they are also more powerful.
Basically it lets you customize possibly non-extendable Maps without adding dependencies on actual Map implementation.
The default Map classes are all final. That means you can't extend them. When you want to create a map with some special behavior, you need to write your own class which implements the whole Map interface and forwards all methods to an internal Map.
The ForwardingMap makes this simpler for you by already being an extendable class which implements Map and forwards everything to an internal map. That means you can create your own Map implementation by extending it. When you do that, you only need to implement selected methods and not all of them.
One use-case might be a map which automatically validates all entries you put into it or one which automatically updates a database when it's changed.

What will be the most descriptive name for my method that returns a list of chess pieces attacking a square [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Edit:
Once again, thanks to those who commented and answered. Agreed, not the best question in the world, but I needed a little push to get past this obstacle in my mind. What I have taken with me in particular is that the return type is an important part of the method signature.
One of the important aspects of clean coding is picking good names for your classes, variables and methods.
Following what I have read in literature and online, I would try and pick names that are, firstly, as descriptive (and therefore unambiguous) as possible, and secondly, as concise as possible.
I am for my own amusement and learning writing a chess game in java, and I have stumbled upon a method that I simply can't figure out how to name in a satisfactory way. The method lives on my ISquare interface and is intended to bring me back a list of pieces that are currently attacking that square.
To be fully descriptive the name should indicate that the method returns a collection of pieces, arguably even a list, and that the pieces are attacking this square instance. One could argue that the latter is implied by where the method lives, but I'm not too sure about that.
The most descriptive name I can think of is probably in violation of every single other naming convention, and obviously won't do:
List<IPiece> giveMeTheListOfPiecesThatThisSquareIsUnderAttackBy();
These two alternatives show that the method relates to the current instance, but seem to hint that the result is of a boolean nature:
List<IPiece> isUnderAttackByPieces();
List<IPiece> underAttackByPieces();
The next one is descriptive about the return type, but not explicit about what the pieces are attacking:
List<IPiece> getAttackingPieces();
This one might satisfy my criteria, but intuitively I would say that using the words "This" and "Square" doesn't look very good:
List<IPiece> piecesAttackingThisSquare();
Currently I have settled with underAttackByPieces(), but as described above that doesn't quite nail it.
Any help you can offer will be most appreciated!
I would settle with getAttackingPieces. Since it's a method of ISquare, I think it is clear enough what is under attack. You can be more explicit in the method's Javadoc comment.

Should I #Deprecate a Superclass Method? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Let's say I'm extending JFileChooser and making an easy-to-use version, which I'm calling SimpleFileChooser.
It is structured such that it can either be DIALOG_TYPE_OPEN or DIALOG_TYPE_SAVE — hence, JFileChooser's showOpenDialog() and showSaveDialog() methods are superfluous. I replace them with a method called showDialog() which returns a boolean, but this is where I find myself in a dilemma:
Should I override the open/save methods and add #Deprecated tags to
them so that the API user knows they've been superseded? Would that
violate the annotation's original purpose?
Or would a notice in the documentation be enough? If so, where should
this notice be placed: in the class summary or above the overridden
methods? Should I even override the methods in the first place?
Thanks in advance.
I think you are actually building a facade, a simplified version of already existing API. Thus instead of inheritance you should use composition. Hide the original JFileChooser inside your new class and provide simpler API.
As a last resort you can provide public JFileChooser getRaw() method to access wrapped object if some other code needs it.
#Deprecated means you should not use that particular class or method anymore as it will be removed in the future. That annotation is designed for that.
So to answer shortly, if you dont want API users to use the method anymore you should use #Deprecated. Because else you will end up with users that still use methods/classes that you remove in future builds and their projects will be broken when they update.

Circumstances to make a class final? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Are there any general guidelines as to when to make a class final?
I thought it was if you did not want people extending your class, but that seems slightly.... naive??
Making a class final only prevents it from being extended as you note. Why would you want to do that?
One typical use case is to guarantee immutability. If you design an immutable class but don't make it final, it can be extended in a mutable way. This can in turn lead to a subclass corrupting a class invariant or creating concurrency issues.
You could also simply mark a class as final to document the fact that it is not designed to be extended. See for example Effective Java #17: "Design and document for inheritance or else prohibit it".
Ideally, you have read Josh Bloch and designed your class for perfectly working inheritance. But, in practice, my (IMHO) answer to making a class final is
Do you trust (or want) others to extend it?
If it is a super-critical class like String or some security related class, yes, definitely make it final.
If you are doing real fancy stuff and the class would be difficult to extend properly, consider making it final, depending on the skills you expect those using the class to have. Also depends on whether this is a general purpose library or some company/project specific code, and whether is it for a website with Squirrel videos or a heart pacemaker - i.e., how badly will a poor subclass break things???
If you aren't doing anything all that fancy, don't annoy users by making it final. I have often cursed Java for making classes like Double final.
It is well established that inheritance breaks encapsulation. Allan Snyder in his paper Encapsulation and inheritance in object-oriented programming languages demonstrates the care you must exercise with inheritance.
Josua Bloch in his book Effective Java recommends that you design and document your classes to be inherited or else you prohibit it, precisely referring to the problems already known to Snyder.
If at some point you are not sure how your classes can be extended in the future or if you have no intention whatsoever that they actually be extended, then you are probably better off making them final. You can always open them for extension later, but the contrary (above all if you are building an open system) can be a real cause of pain, if not impossible depending of the circumstances.
The researches Mikhajlov and Sekerinski in their paper A Study of the Fragile Base Class demonstrate the array of problems you may have when improperly using inheritance which may give you a broader idea of why this could be important.

Categories

Resources