Say I have a following function in java, may be not good example but just came in mind ;)
public StudentEntity updateStudent(StudentEntity studentEntity)
{
studentEntity.setName(...);
studentEntity.setAddress(...);
return studentEntity;
}
Is above approach valid?
Can we store a studentEntity in separate variable and update and return it.
For example
public StudentEntity updateStudent(StudentEntity studentEntity)
{
StudentEntity _studentEntity = studentEntity;
_studentEntity.setName(...);
_studentEntity.setAddress(...);
return _studentEntity;
}
Is this correct ? How mutator methods should be? Please make me correct if wrong!
There is no reason to write
StudentEntity _studentEntity = studentEntity;
It's just redundant.
If you are just updating and return prefer first way. The second way creates unnecessary confusion while reading the code aswell.
Related
This might sound like a dumb question, because it might be no other way to do this. After designing my own list, this sort of "issue" came up in multiple occasions. To clarify, I have a problem with returning a cached variable after assigning new value to the original variable. Here's an example:
public T next() {
final Node<T> thisNode = posNode;
posNode = posNode.getNext();
return thisNode.getData();
}
This might seem like a non-issue, but occasionally multiple variables has to be cached before returning a valid value. I do not really like it, because personally I think it reduces the code's readability, especially when caching multiple variables.
Is there another way to write this code while maintaining its functionality? Basically a way to assign a new value to a variable after the return statement:
public T next() {
return posNode.getData();
posNode = posNode.getNext();
}
Thanks! :)
The second way is not possible as the code is not reachable after return. And your first way is the best way far you to achieve what you are looking for and it is not code smell. Often they refer as temp variables. Use them and better convey a message to the code reader by better naming convention. For ex tempPosNode
An elegant (but with some cognitive dissonance) option is a dummy method.
public static <T> T first(T first, Object... theRest) {
return first;
}
public T next() {
return first(posNode.getData(), posNode = posNode.getNext());
}
You can use a finally block to execute it, but it will execute even after exceptions:
public T next() {
try {
return posNode.getData();
} finally {
posNode = posNode.getNext();
}
}
I have a method that returns all the names of people in a LinkedList for a plane.
However even though there is a return statement in the method, I'm still getting told there is a missing return statement.
How can I work around this without putting another return statement in? Why isn't it considered valid? Does putting another return statement in change what is returned?
Any feedback is greatly appreciated.
public String check() {
for (Person person: passengers)
{
return person.getName();
}
}
Because if passengers is empty, the loop will never be entered.
If the loop is never entered, assuming the only return statement is in it, we have a serious problem, don't you think ? It's like if there were no return at all.
You need to add another return statement outside of the loop.
Also note that the return will automatically exit the method, so I don't think this is exactly what you wanted as per this sentence in your question :
I have a method that returns all the names of people in a LinkedList
for a plane.
Edit
As per your edit, here how you can return a list containing all names :
return passengers.
.stream()
.map(Person::getName)
.collect(Collectors.toList());
Note that you will need to change the signature of your method to
public List<String> check()
In answer to your question in the comments. You can only return a single object from a function. You could take another container and populate it with the names and return that. For example,
public LinkedList<String> check() {
LinkedList<String> names = new LinkedList<String>();
for (Person person: passengers) {
names.add( person.getName() );
}
return names;
}
What exactly are you trying to accomplish, here?
Currently, check will only ever return the name of the first passenger. Think about how your program flows and what you want it to do.
To answer your question, you need to have an 'escape' for every possible path in your code. Even if a certain block should always catch and return (not by definition, but just by how you think the code should flow), you need to handle the case such that that block doesn't catch and return. This can be done by either fixing the first block so that it really is a catch-all, or by simply returning or throwing an error if the first block doesn't catch.
i.e.
public boolean check() {
...
if (shouldAlwaysBeTrue) return false;
}
doesn't work because shouldAlwaysBeTrue is not true by definition.
public boolean check() {
...
if (shouldAlwaysBeTrue) return false;
return true;
}
Is there any language which has a keyword such as delayedreturn which allows you to save a value and only return it when a method completes?
For example, something like this (Java syntax):
public Integer nullify(Node<Integer> node){
delayedreturn node.getValue();
node.setValue(null);
}
I know that it's not that much of a space saver. Just curious if anyone deemed it worthy of implementing.
There are no languages like that that I know of. Such a keyword would most likely cause the return value to be stored in a temporary location, which you can already accomplish:
public Integer nullify (Node<Integer> node) {
Integer delayedReturn = node.getValue();
node.setValue(null);
return delayedReturn;
}
It's essentially the same as what you are asking, just a different syntax than you proposed.
Java actually does have something which accomplishes just what you are asking for, and I've even seen some legitimate uses of it (by Doug Lea, if I'm not mistaken):
try { return node.getValue(); }
finally { node.setValue(null); }
In general this is dangerous because an exception thrown from try can be masked by another one thrown from finally.
Never seen one. But when you can do this, it doesn't matter much:
public Integer nullify(Node<Integer> node){
Integer delayedreturn = node.getValue();
node.setValue(null);
return delayedreturn;
}
How can I delay returning a varaible from a method in Java, or how should I do it if it is something unwanted to do?
Consider this:
public class Transaction {
public int addInsert() {
...
return insertId;
}
public boolean addUpdate() {
...
return updateSuccesful;
}
public void commit() {
/* Calls everything that is inserted via addInsert or addUpdate. */
}
}
Now assume you use the code as:
Transaction transaction = new Transaction();
int insertedId = transaction.addInsert();
boolean updateSuccesful = transaction.addUpdate();
//insertId, updateSuccesful cannot be known yet
transaction.commit();
//now insertId, updateSuccesful should be filled in
So the return may only happen if transaction.commit() has been called.
Any thoughts?
You can achieve this functionality by multithreading and making the threads that are running those two methods .wait() until the commit() method calls .notify() to let them know that they can finish.
However, a better way to structure this is to re-organize your your methods, perhaps by making commit return the insertedID and make it return -1 if it is unsuccessful. That way you can check the boolean by seeing if it is -1 or not, and you can read the ID by reading the return of commit.
You're example looks like the Unit of Work Pattern: http://martinfowler.com/eaaCatalog/unitOfWork.html
Which also shows the answer to your question.
You can't actually call method a, and have it's return value delayed until you call method b without getting into threading, and that's still going to be an overly complicated and very brittle solution to the problem.
Instead call method a, method b etc. However don't actually do the work until the commit happens. Then the commit returns, or you can call a getMethodAStatus() etc.
I'm writing a plug-in for Jira and I need to add custom calculated column to issue navigator. That's column should show last comment to issue. But in issue navigator values in this column are something like "ClassName#123456", not comment's body. What should I do to return comment's body to this column?
Code so far:
public class LastCommentField extends CalculatedCFType {
private CommentManager commentManager = null;
public LastCommentField(CommentManager commentManager) {
this.commentManager=commentManager;
}
public Object getValueFromIssue(CustomField field, Issue issue) {
Comment lastComment=null;
List<Comment> comments = commentManager.getComments(issue);
if(comments != null && !comments.isEmpty()) {
lastComment = (Comment)comments.get(comments.size() - 1);
}
return lastComment;
}
public String getStringFromSingularObject (Object object) {
return object.toString();
}
public Object getSingularObjectFromString(String value) {
return value;
}
}
This functionality already exists in at least two plugins, e.g. https://marketplace.atlassian.com/plugins/net.customware.jira.utils.customware-jira-utilities
But in the code above, the singular object being used is a Comment object as documented at http://docs.atlassian.com/jira/4.4/com/atlassian/jira/issue/comments/Comment.html
but you probably just want a String, so try
return lastComment.getBody();
Unfortunately I don't know JIRA from the coding side of things, but from the Java side, that sounds a hell of a lot like the object behind the column doesn't have ToString() overriden. What you are seeing is the name of the class followed by the address in memory.
If you could show us the code behind the column, I might be able to make a little more sense of it.