When not all your functions are polymorphic [closed] - java

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.

Related

parameterized constructor in Java [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 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.

Return types analysis of a method updating an object [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 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

Interfaces in Java 8 [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 7 years ago.
Improve this question
J. Bloch in his Effective Java written for Java 6 mentioned the following (Item 17):
If you feel that you must allow inheritance from such a class, one
reasonable approach is to ensure that the class never invokes any of
its overridable methods and to document this fact. In other words,
eliminate the class’s self-use of overridable methods entirely.
Item 18:
If you use abstract classes to define types, you leave the programmer
who wants to add functionality with no alternative but to use
inheritance. The resulting classes are less powerful and more fragile
than wrapper classes.
While interfaces are not permitted to contain method implementations,
using interfaces to define types does not prevent you from providing
implementation assistance to programmers.
Now in Java 8 with its default method's implementation (using the other methods in the interface) interfaces are dangerous for inheritance.
For instance:
public inteface MyInterface{
public void compute(Object o);
public default void computeAll(List<Object> oo){
for(Object o: oo)
compute(o); //self-use
}
}
So, according to J. Bloch, it may introduce some problems when we try to implement the interface, because:
Overriding the methods like this (similar to what J.Bloch provided):
public class MyInterfaceCounter implements MyInterface{
private int count = 0;
#Override
public void compute(Object o) {
count++;
}
#Override
public void computeAll(List<Object> oo){
count += oo.size(); //Damn!!
MyInterface.super.computeAll(oo);
}
}
The client access the interfaces's internals, i.e. they have to know about the default implementation.
What to do with it in Java 8? Are the rules from Effective Java apply still applicable?
Moreover, we can't declare the default method as final (as we can do for classes, it would make the self-use not too dangerous for overriders).
Okay, take the answer from your previous question and look what we can apply here:
You could simply avoid self-use.
In this case you can't. While implementing that interface your only choice to rely on (if you want to give a default implementation) is the method compute. You have to use it or not give an implementation at all.
You could make one of the methods involved final, so it can't be overridden.
That won't work in an interface as well.
You could make the class final, so it can't be extended.
That won't work in an interface.
You could describe the class's self-use patterns in its Javadoc comment (meeting the requirement of letting other people know).
That is the only choice left here. Either document it or don't give a default implementation.
So yes, the basic idea of it still applies, however your choices are somewhat limited.

Can I create a java object with specific methods ignored? [closed]

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

Appropriate methods to put into a util class? [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 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.

Categories