Value of Optional.of("xxxx") in Java Programming [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Please consider the following java code:
Optional.of("some.constant.value")
How is using Optional.of() of any value when the parameter is a constant?

Optional is generally used as return value of a function that may or may not return a value. It's a technique to avoid dealing with null-values.
E.g. assuming you have a function that returns an Optional<Integer>, you can use it to provide a default value:
int x = person.getAge().orElse(42);
The factory function you are refering to is how an Optional is constructed in the called function:
public Optional<Integer> getAge(){
if(this.age == null)
return Optional.empty();
return Optional.of(this.age);
}

This is entirely contextual, and without that context it's impossible for anyone to really say.
But... As a couple of times I've seen things like this be useful (maybe you can identify which one is relevant to your given circumstance:
An interface where some method is an Optional.
interface PotentiallyLimited {
OptionalInt getLimit();
}
class LimitedToTen implements PotentiallyLimited {
private static final OptionalInt LIMIT = OptionalInt.of(10);
#Override
public final OptionalInt getLimit() {
return LIMIT;
}
}
In this case, having the variable stored as a constant stops it having to generate a new instance every time.
A class where some dependency would return an Optional, but may not be present.
class Thing {
private static final Optional<String> DEFAULT_PREFERENCE = Optional.of("blue");
private final #Nullable PreferenceProvider provider;
public void useDependency() {
final Optional<String> preference;
if (dependency != null) {
preference = provider.getPreference();
} else {
preference = DEFAULT;
}
// Use the preference here...
}
}
Again, having it as a constant means you don't need to create a new instance on every invocation.
One final case I've seen, say you have some interface which has a sort of boolean isError(); and an additional Optional<String> getErrorReason();. It's perfectly reasonably to have an implementation which always represents an error, then explicitly setting the Optional from a known constant String again helps avoiding creating lots of instances.
I'm sure there's plenty of other times it might be useful to do this.

Related

Java class has only one constructor, no parameter for constructor, all instances of that class will point to the same object in the heap? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Have the following case:
class Bond {
private static int price = 5;
public boolean sell() {
if(price<10) {
price++;
return true;
} else if(price>=10) {
return false;
}
return false;
}
public static void main(String[] cash) {
new Bond().sell();
new Bond().sell();
new Bond().sell();
System.out.print(price);
Bond bond1=new Bond();
System.out.print(price);
}
}
It will print: 8 9.
Will all instances that will be made, will point to the same object in the heap?
There's a very simple rule in Java: new SomethingOrOther() will always create a new object (unless it somehow produces an exception).
So the answer is obviously: no, the main method you posted will create 4 instances of Bond.
Those instances happen to not have any fields that makes them different in any interesting way, but they are distinct instances.
The reason it "looks like" only one instance exists is that your price field is static, which means it belongs to the class Bond itself and not to an individual instance, which also means there's only one price ever, no matter how many instances you have (yes, even if there are no instances at all).
Remove static keyword of "price" to answer it yourself.
static variables hold the same value across all the object instances.

Setting the Value to an Object by using Void or return type approach [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have Employee class and I am trying to set a value to employee name property:
public class Employee {
private String name;
private String id;
// setters and getters
}
I have got two options: by using void or using a return type.
public class EmpClient {
public static void main(String[] args) {
Employee emp = new Employee();
EmpClient emp_client = new EmpClient();
emp_client.setNameToEmployee(emp);
System.out.println(emp.getName());
}
public void setNameUsingVoid(Employee emp) {
emp.setName("Mark");
}
public Employee setNameToEmployee(Employee emp) {
emp.setName("Taylor");
return emp;
}
}
This is my code and through both the approaches, it works.
Please let me know what is the preferred and more efficient way? What are the pros and cons of using each of the methods, and under what circumstances should they be used?
It depends on what you want the method to do. For most cases setNameUsingVoid() method would be suitable. You want to assign a name to the employee and this method achieves that.
When instead you have this statement in your main method.
setNameToEmployee(emp);
The desired assignment is done and additionally, a reference is also returned. Here you are not using the returned value, so it is just unnecessary extra work. So if you are going to use the statement in the above fashion, use setNameUsingVoid() instead.
Note: According to the Java Language Specification, the above statement is a valid statement though the returned value is not being used. For more info on the validity of such statements
If instead you were to use setNameToEmployee() in this way:
Employee e1 = setNameToEmployee(emp);
You should opt for using this function over the other one. However in this specific use case the statement makes no sense at all because you are idly making a second copy of your Employee object. Summing up:
In this case (or any case where you pass a reference at return the same thing), it is best to use setNameUsingVoid(), as it is very difficult to think of a case where setNameToEmployee() might actually be beneficial.

Name for this type of programming construct/design/pattern? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Please don't chalk this up as a dumb question. This may seem very obvious to some, but it is not to me.
I am working on a very, very large codebase.
I continually see, in numerous classes, this pattern:
public class myClass {
public myClass[] doGetMyClassList(final String someParam) {
// some code
}
}
The class contains a method that returns an array or a list of itself.
Is there a name for this? I would like to know if this belongs to some kind of programming practice.
The type signature alone doesn't tell you what pattern it is, you also need to know what it collaborates with and how it's used.
It seems like it might be attempting to do the repository pattern, in which a repository class fetches collections of some other class according to parameters passed in. However, you would typically make the repository a separate class from the class it is fetching for you. It's kind of hard to switch out to another repository for testing or other reasons when the class just returns it's own type.
Though I could not find an explicit design pattern or a well defined interface. I find a parallel here
listFiles() method of java.io.File which returns an array of File objects if its a directory.
Also any other usecase where objects of same class are related could be a parallel. ex: Person class with friends method which returns an array of Person objects.
Generics as a programming construct is a great tool to express these relations(i.e. methods). Self-bound Generics are feasible and are often seen in many places ex:
import java.util.Arrays;
public class Grade < T extends Grade >{
private static final int MAX = 5 ;
private int grade;
public Grade(int grade) {
this.grade = grade;
}
public T[] getGradesBelow() {
Grade[] lower = new Grade[this.grade];
for (int i = 0; i < this.grade; i++) {
lower[i] = new Grade(i);
}
return (T[]) lower;
}
public String toString(){
return grade + "";
}
public static void main(String[] args){
Grade grade = new Grade(Grade.MAX);
System.out.println(Arrays.toString(grade.getGradesBelow()));
}
}

How to compare user input to an instance variable of all objects from a class [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So, I'm trying to compare a string to an instance variable of another class, and I can't think of a way to do this for all objects of the said class.
I know for sure that if the method where this occurs is running, I have 4 objects of the class that contains the instance variable.
The goal is to compare the string the user gives me, and if it is equal to the one of a previously defined object, change another instance variable in that object.
In sudo-code it would be something like this:
if (colourInput == colourofAnyObjectOfTheClass)
sizeOfThatObject = sizeInput;
else
new Object(colourInput, sizeInput);
And I've previously defined what colourInput and sizeInput are.
How can I go about implementing this in Java?
When comparing Strings, you should use the String#equals() method, not the == operator.
if (colourofAnyObjectOfTheClass.equals(colourInput)) {
sizeOfThatObject = sizeInput;
} else {
new SomeObject(colourInput, sizeInput);
}
You should consider creating some sort of repository of instances of your class that is class which will manage creation of object so it can keep track of them.
class MyEntityRepository {
private List<MyEntity> entities;
public MyEntity createOrUpdate(String color, Integer size) {
MyEntity entity = findByColor(color);
if (entity != null) {
entity.setSize(size);
} else {
entity = new MyEntity(color, size);
entities.add(entity);
}
return entity;
}
private MyEntity findByColor(String color) { ... }
}
If you have a lot of entities you may create some sort of index, for example store Map<String, MyEntity> which maps keys to entities and use it to speed up search.

How to add multiple values to an Object ArrayList? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The problem should be on the createClass() method... is it wrong to use classes.add(this)?
private static ArrayList<VirtualClass> classes = new ArrayList<VirtualClass>();
private boolean isPrivate;
private String className;
private String methodName;
public void setVirtualClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
}
public void createClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
classes.add(this);
}
More details on the problem: Failed to store values in ArrayList of class object. (CODE EDITED)
I suppose you want to keep a record of all created classes?
It is generally bad practice to pass out this in a constructor because, by definition, this hasn't been constructed yet. In this instance I don't think it will cause problems but it certainly doesn't smell right.
I would consider using a static factory method or another form of factory pattern so that you can split up object creation and the storing of instances.
No one can tell you whether it is right or wrong unless you tell what you are trying to do.
If what you are doing is something like : (assume your class is called Foo)
Foo foo = new Foo();
foo.createClass("Blablabla", "method1", true);
foo.createClass("AnotherClass", "method2", true);
something like that, then yes, you are probably wrong. Because what you are doing is simply changing the only Foo instance with different attribute, and adding the same object to the list.

Categories