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 6 years ago.
Improve this question
I just had a discussion about parameterized constructors with my exercise instructor. He said it is bad practice having two or more constructors, especially parameterized constructors. Instead of constructors I should use only one empty constructor and for initialisation the factory method pattern.
So this is the first time, I've ever heard something like this. I did some research, but I could not find anything related. The only bad practices I've found are:
too many parameters inside constructor
using public/protected method inside constructor (because a child class can override the methods)
wild calculations
So my question is, what is best practice? Is it fine to set instance variables inside constructor or should I follow the advice and use the factory method pattern?
Whether you use a factory method or multiple constructors is really just personal preference, especially with Java 8 where you can easily use a constructor reference as a factory (That's all a constructor really is - a factory for making instances of the object). It's perfectly fine to have multiple constructors for a class, and if you have too many constructors in a class, that's a sign of a class that is doing too much, not that you need to switch to a factory. Constructors very much should be parameterized when a class requires specific input to be valid and null / 0 is not a sane default value.
What you should avoid, however, is allowing an object to exist in an invalid state. For example, consider the following class and factory:
public class MyList {
private Object[] backingArray;
public void setBackingArray(Object[] backingArray) {
this.backingArray = backingArray;
}
}
public class MyListFactory() {
MyList newMyList(int initialSize) {
MyList list = new MyList();
list.setBackingArray(new Object[initialSize]);
return list;
}
MyList newMyList() {
MyList list = new MyList();
list.setBackingArray(new Object[defaultSize]);
return list;
}
}
This is an example of bad design because I can ignore the factory and call new MyList() directly and the object is essentially invalid until I also call setBackingArray(). When using a factory pattern, you have to be very careful to make sure that other code can't create the object directly without going through the factory. (The above classes are also bad for a host of other reasons, but they're not relevant to the point I'm trying to make).
Best practice is up to you and up to you alone.
I suggest to use Project Lombok (https://projectlombok.org).
You can use annotation on class #AllArgsConstructor and it will be created automatically. Also you can use #RequiredArgsConstructor for final fields. There are many possibilities for auto-creating getters and setters. So your code will be shorter and more readable.
Related
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 5 years ago.
Improve this question
Let say we have some Bean (which is POJO)
public class Bean {
}
And we have BeanWrapper which is a wrapper over Bean and represents DTO for the Bean class. Also supports adapter to and from Bean.
public class BeanWrapper {
public Bean toBean() {}
public static BeanWrapper fromBean(Bean bean) {}
}
The question is on the method fromBean.
What should be the correct design pattern for this method - should it be static method?
In other words what is better:
BeanWrapper wrapper = BeanWrapper.fromBean(bean);
Or just non-static method and use it like following:
BeanWrapper wrapper = new BeanWrapper().populateBean(bean);
Edit from comments:
Or go with a constructor:
BeanWrapper wrapper = new BeanWrapper(Bean bean);
Which one is better and preferred way over other? And why is it like that?
That depends - so opinion based. If you are using CDI (Content Dependency Injection) it might be better to use the first option by first injecting the wrapper and refrain from making the methods static. This is in a CDI environment preferable as it stays closer to the OO paradigm.
My opinion is to only use public static methods only when absolutely necessary. e.g. factory methods.
For the rest all of the options are a matter of what you decide with your team. Be consistent though.
Why I think static methods are evil (in most cases):
OO principles like polymorphism are just thrown away with static methods.
A static method indicates a method that does not know where it belongs. OO promotes the "Who is responsible" and every method should belong to something
Testability is a problem. Every piece of code that calls a static method needs to test this static method in its entirety as the compiler "copies" that static method as-is into the calling method. This makes for unmaintainable tests.
They can be viewed as kinda global methods / procedures. So the class it is written in is actually only there for its name not for its state or responsibility
Code becomes more complex as it is difficult to say what it is for and why it should be used and in what context. Misuse is easy.
As Java is an OO language it is good practice to use it in that context. With that in mind IMHO it is only good to use public static methods in these cases:
Factory methods
Unit tests
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 6 years ago.
Improve this question
What is the difference between the following 2 approaches to defining a return type for a method which updates an object? (void vs Foo)
The first one:
void updateSomeFields(final Foo foo){
foo.setBar(fancyProcessing(foo.getBar())); // and more
}
And the second one:
Foo updateSomeFields(final Foo foo){
foo.setBar(fancyProcessing(foo.getBar())); // and more
return foo;
}
None of these methods be defined inside Foo.
Is one of the differences related to procedural vs OOP style (1 vs 2)?
Java allows the values of the object's fields to be changed in the method (i.e. allows 1. to work). But should they be changed in such a case?
Does it ever make sense to define a local Foo in approach 2?
Update
Based on lead from Andy Turner on fluent interfaces (object oriented API that aims to provide more readable code) it has answered:
Does it ever make sense to define a local Foo in approach 2?
Local variable declarations are syntactic sugar because of the difficulty humans have with deeply nested method calls.
It is useful for method cascading (concretely method chaining) to relay the instruction context of a subsequent call , however in the scope of this question having the methods outside Foo itself perhaps the return type would be neither Foo nor void but the containing helper class.
Your approach No.2 makes it easier to set multiple attributes in single statement
like Bar.setFoo(foo).setFoo1(foo1) and so on
I prefer Approach2 just because it offers extra flexibility
Update:
This principle violates Java Bean spec so JSP's and other Spring stuff could break
Also see Fluent Interface
A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Consider that I have a class named Validation with five methods. All the methods are very complex and large. In a certain part of my application, I need to create a Validation object, but I'll only be using one method from that object. I could make the method static to fulfill my purpose, but for the rest of the application to keep working, those methods should be non-static.
So is there a way that I can create an object of a class containing only one of the non-static methods?
No.
About the best you can do (to answer the question as asked) is make the method protected and have a subclass of Validation which extends it. Then, if all the other methods are private, that object will only have the one protected one.
It's kind of a bad situation, though. More than likely, if you're trying to do this, you're either trying to optimize for no reason or you have a bad design somewhere.
e.g.,
public class Validation {
private void method1() {}
private void method2() {}
protected void method3() {}
private void method4() {}
}
...
public class RestrictedValidation extends Validation { }
...
public static void main(String[] args) {
RestrictedValidation validation = new RestrictedValidation();
validation.method1(); //compiler error
validation.method2(); //compiler error
validation.method3(); //success
validation.method4(); //compiler error
}
But yeah. I can't think of a single valid use-case for this.
You can solve this by way of inheritance where ValidationA would contain common methods used by most clients (here your one particular method), and a ValidationB class which extends ValidationA and add more specialized methods.
Or depending of the situation, it could be 2 completely different objects.
No there is no such way. An object consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.
what you is saying is create a person object(whose has already defined behaviour of walking and running) but he should only walk and not run. It does not make sense.
Jeff Gohlke provided a good solution to it
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
From an old exam with no solutions:
Given this code....
import java.util.*;
public class AClass {
private int f(List<Integer> list){
int i = 0;
//Something useful
return i;
}
public int g() {
List<Integer> myList = new LinkedList<Integer>();
return f(myList);
}
}
Note that the method f is polymorphic, i.e. it can be passed any implementation of the interface List. On the other hand, the method g is not. As it constructs the object myList, it cannot do this without knowing its type. Consequently, it cannot be polymorphic. Our code contains many methods suffering from the same problem. We aim to make our code polymorphic.
What is the name of the standard solution to this problem?
Describe it in this case
Loose coupling There are many ways to solve that problem among them: program to interfaces and apply Dependency Injection
Method g() is tightly coupled to LinkedList because the method is explicitly instantiating that object hence tight to that class. If you want to for example use an ArrayList you need to open the class and explicitly modify the method and potentially introduce bugs. Additionally, you will probably need to retest and document. On the other hand method f() is way more flexible because you can just pass the collection you need and the method has no notion about the concrete implementation you are passing keeping in that way your method closed.
Consequently, it cannot be polymorphic. Our code contains many methods suffering from the same problem. We aim to make our code polymorphic.
What do you mean by that? Please provide an examples. The only way to make this code more generic is to use Collection or Iterable instead of List, but I'd say that's an overkill in terms of loose coupling.
Apparently, the solution in this case would be to create an Abstract Factory Pattern.
For example, we'd create a new class called AClassCreator and have a method createAClass(List<?> list) where the parameter is a subclass of list.
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 9 years ago.
Improve this question
I am working on a java class for parsing HTML and generating RDF (which I think I will eventually split into two classes - one for parsing and one for generating RDF).
At the moment I am creating a lot of methods for checking HTML data and converting it into a more uniform representation. Some of the methods I have created so far are:
public boolean isInteger(String str) { }
public boolean isTime(String str) { }
public boolean isDate(String str) { }
public String dateConverter(String[] date) { } //Converts a Norwegian date into mmddYYYY
Should I put methods like these into a util class? At the moment they are only being used by this specific class, but I think that they might need to be use them by more than this one class at a later point in time.
Well, yes, the methods you listed look like good candidates for public static methods in a util class. (The last 2 or 3 would fit nicely in a class called "DateUtils", for example.)
Of course, if you only use them in one place, they can just as well remain "private helpers" there, but as soon as you have multiple places using them, a util class makes sense.
(Edit: overuse of static methods can be problematic, but I think these methods could well be static utils because they are pure functions.)
They seem generic enough to be appropriate to put in a util class. I would, at the very least. Basically any class that parses String in your code would need to use those methods. I would make them static before adding them to the class though to avoid unnecessary construction.
Decomposition is a good habit to get into. If you are unsure about whether or not you need to use them, then go ahead and do so. It will give you practice with using utility classes.
It is a good practice to collect such methods in a utility class. Even if they are called from a single class at the moment, these kind of methods will be potentially reused by other clients in a near feature.
However, you must pay attention to make this utility class easy to be reused. To do this, the method signatures, actually their arguments, must be as generic as possible. They should not take inputs specific to a class.
Another advice of mine is dividing this utility class into more than one classes, if it begins to contain many incoherent methods. You can do this by grouping the relevant methods in a separate class. For example, methods you wrote can be moved to TypeUtils class and you can collect conversion related methods in Html2RdfUtils class for instance.
Finally, if you feel that these utility classes can be benefical to your other projects, you can collect them in a distinct library.
if you eventually want to split them into two classes, you may want to define the baseclass as interface or abstract class.
Base on your requirement, abstract class should be the right choose.
Put something in common from the child class to the abstract class.(You can implement method in the abstract class)
from another answer, I want to ask a question?
the answer suggest putting static in front of the method to avoid unnecessary construction, it very make sense.
I know the abstract class does not require to be instantiated to call its method.
it also can avoid construction.
There is the question?
Which way is more legit? or better? or just same.