Can I create a java object with specific methods ignored? [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 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

Related

What is the best way to implement helper functions inside an abstract class 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 2 years ago.
Improve this question
Let's assume that we have an abstract class (let's just call it X) that is inherited by a number of classes (we'll call them A and B for now). Each class that inherits from X does similar, but slightly different things, so while the implementation of each of their public methods might be slightly different, they can all use the same helper functions to avoid duplicating code. However, it makes no sense for any of these helper functions to be accessed by any class that is not a subclass of X.
Furthermore, what if there are a number of helper functions which are only meant to be used inside of classes that extend X, but need to have a slightly different implementation in each class?
Here's an example:
public abstract class X {
public abstract void doStuff();
int helperFunction(int a, int b) {
return a + b;
}
abstract void secondHelperFunction(int x);
}
public class A extends X {
#Override
public void doStuff() {
//do some stuff
helperFunction(a, b);
//so some other stuff
}
#Override
void secondHelperFunction(int x) {
//implementation A
}
}
public class B extends X {
#Override
public void doStuff() {
//do some different stuff
helperFunction(b, a);
//do other stuff
}
#Override
void secondHelperFunction(int x) {
//implementation B
}
}
(This example is obviously very simple, I'm just trying to get my point across)
My question is, what would be the best way to do this? For example, what access modifier should be used for the helper functions? Obviously private isn't an option, since then subclasses wouldn't be able to use it. Default and protected sound like a better choice, but they still allow non-subclasses to use these functions, as long as they are in the same package as X. Would the best solution to this issue then be to enclose X and all classes that inherit from it in their own package, separate from the rest of the program? Or should one perhaps look into another form of abstraction, e.g. interfaces? (Although I cannot think of a way to deal with this using interfaces in particular)
A couple of options for you to consider:
Use protected. You are correct that this does not prevent other classes within the same package from calling the method. But is that really a problem? The idea of a package is to gather related classes together and control the interface through which they are called. Access modifiers are a relatively coarse control mechanism that are designed primarily to help humans avoid errors when coding.
Put the helper functions in a separate class and use composition rather than inheritance. You could still override methods to provide different behaviours. The downside is you will need to pass in any values required. But this isn't necessarily a bad thing as it makes the dependencies clear.

private static throughout code [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
I am on a new project, and the legacy java code is filled with classes that are using a mix of private static methods, and public static methods.
It's very hard to follow.
For example:
public Car {
private static checkGas(){
..
}
public static startCar(){
checkGas();
}
}
Is there some design pattern I never heard of that would make this applicable?
I've always used public static methods on "helper" classes that do not need Util.caculate(..), and in the above "Car" example I wouldn't have use any private static or public static methods... just private and public methods.
You generally want to limit access as tightly as possible, so if you have a utility class with some public static methods and some static helper methods that they call, those helper methods should be private.
This is not fundamentally different than writing non-static private helper methods to support non-static public methods.
I wouldn't call this a design pattern, so much as a good general practice.
Don't make things public unless you have to. Once a method is public, you can't modify its signature without breaking everything that uses it.
Edit
Regarding the best place to put static methods, I'd rather put them on the class they're designed to help, rather than aggregate random static methods in a "Util" class.
A good example of this would be the Integer class, which can be instantiated to represent a numerical value, but also has many static helper methods like compare, max, parseInt, etc.
Utility classes should be for things that are truly generic, such as the Math class.

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.

Java - merge two classes in Eclipse [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 6 years ago.
Improve this question
I have two similar classes. I would like to merge it into one. Objects of these classes are used in many different places. Is it possible to do it safely in Eclipse?
If you have two classes that are similar in some ways (but possibly not in others), you could create an Interface that describes the methods that are common to both of them. Then, you would have your two classes implement that Interface. Elsewhere in your application, you could reference the Interface as the formal parameters to your methods. Here's an example (see code below).
There is no automatic way to do this in an IDE-- you've got to take the time to design your object hierarchy (the relationships between your classes, and the API that your application will use to interact with them) manually.
public Interface Automobile{
//define an interface that describes the methods common to your two classes
public void drive();
}
//this is one of your two classes
public class Sedan implements Automobile{
public void drive(){
//Sedan-specific implementation here
}
}
//here's the other one. It's similar in that it has a drive method, but different
//in that it's implementation for drive() is different, and there might be
//other stuff in this class that is different from Sedan. However, it still is-an
//Automoblie
public class RaceCar implements Automobile{
public void drive(){
//RaceCar-specific implementation here
}
}
public class YourApplication{
//some method that accepts either one of the two classes you
//described as being "similar"
public void someMethod(Automobile automobile){
//you could pass in either a Sedan or a RaceCar, and
//the corresponding drive() method would get called
automobile.drive();
}
public static void main(String args[]){
Automobile car1 = new Sedan();
Automobile car2 = new RaceCar();
someMethod(car1);
//call the same method, but with car2!
someMethod(car2);
}
}
Eclipse can't do that automatically, You will have to go to one class, press control+a then control+c then go to the other class and press control+v.
Use Refactor->Extract Interface for each class to create two new interfaces and change the sources to use them instead of the classes.
Now create a new class implementing both these interfaces and remove the old classes. This should only cause your factory methods for the interfaces to break.
Change your factory methods to return this new class and leave all the interface usages in place.

When not all your functions are polymorphic [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 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.

Categories