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.
Related
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 5 years ago.
Improve this question
So someone tell me if i'm correct or not.
Encapsulation is Data hiding, allowing yourself only to view the
attributes and othering methods in a class privately, while you could you use these methods and abbritures in other classes,
Inheritance is extending a class, like taking some of the methods in the “super class” and pass it in “child class” and modify it or use it there.
Polymorphism is the same thing as inheritance but it's just formatted differently, like if i had an animal class, every animal has a different sound so, from there I would have something like this
Animal cat = new Cat();
overriding & overloading I’m not sure about this one
Abstract classes is taking methods or variables from the super class and pass those methods and variables as “Abstract” so that in the sub class you modify them and edit them.
Does that make sense? Or I misunderstood something?
These things all work together.
An object is something that is self-sufficient, it keeps track of its own state. Encapsulation enforces that separation, the object publishes methods that other objects call, but those methods are responsible for modifying the object's state.
In oo systems that use classes the class is a template for creating objects. Subclassing means creating a new class that is a more specific version of the subclassed class, where subclassed objects inherit the class definitions that specify the methods and fields of the superclasses.
Abstract classes defer some method implementations, leaving them to the subclasses to implement. If the superclass knows something has to happen at some particular point but wants to leave exactly what happens to the discretion of the specific objects, that's what abstract methods are for.
There's a pattern emerging here: objects taking responsibility for themselves, and a hierarchy of types from most abstract/general to most concrete/specific. Polymorphism is about objects' behavior being determined at the time the program runs based on what methods are overridden. Overriding means the subtype has a more specific version of a method that is substituted for the superclass version.
(Overloading otoh is a convenience for allowing a class to have methods with the same name but different parameters.)
The result of this can be a system that at a high level deals with abstract types and lets the objects themselves work out the exact details. The idea is that that way the details can be confined to the subclasses and the program can be modified by creating new subclasses without disrupting the rest of the program. In theory anyway, see Wadler's Expression Problem for where this all goes to hell.
And for examples: read the source that comes with the Jdk. The packages java.lang and java.util have a lot of classes that are examples of OO design.
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
First day using Java. Very basic question: I have three base classes, multiply-inherited by many classes. Each of these base classes has lots of implementation with few abstract methods:
class Consumer { /* lots of stuff */ };
class Producer { /* lots of stuff */ };
class Logger { /* lots of stuff */ };
class A : public Consumer, Producer, Logger {}
...
class Z : public Consumer, Producer, Logger {}
Now I know I can turn two of three base classes into interfaces and multiple-inherit the 2 interfaces and extend one class. Inadequate because of all the implementation in these base classes that doesn't make sense to duplicate into many subclasses.
I'm reading some stuff on delegation or composition, and I don't know how to apply this here. Basically my thought processes have been patterned by my C++ experience. What is the path of least resistance to convert my C++ class structure to Java?
I can fill out the base classes more if needed, but hopefully not necessary.
What is the path of least resistance to convert my C++ class structure to Java?
take a pen and paper, rethink your problem and make a design that's closer to how Java works.
There's no magical rule that will transform any given problem with multiple inheritance into another without it. Given the situation, you may want to separate concerns by creating multiple classes with a reference to each other, whereas you had only one in C++… But then it's up to the specific problem you're dealing with, how you'd build your hierarchy of classes and interfaces and how the resulting different class instances will relate to each other.
you have two options:
Create 3 interfaces for Consumer, Producer and Logger and make the classes A and Z implementing them. Of course for each class you have to provide an implementation. If the implementation is the same make a more generic class (it could be abstract, you probably won't need to instantiate it) implementing the 3 interfaces and then make the classes A and Z extending the abstract class.
As you said in your post it seems this solutions don't fit your needs , so use delegation instead, in the classes A and Z put 3 new fields (as instance variable) of Consumer, Producer and Logger type (you can instantiate them in the constructor) and then put methods which are wrappers for the Consumer, producer and Logger methods.
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 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 9 years ago.
Improve this question
With the time ...lots of utility method are introduced in java project for more complex and simple task.
When using static methods we introduce tight coupling in our code and it make our code more difficult to test, especially if the utility methods are quite complex.
I am just thinking that it now difficult to manage and test these utilities. please guide me in avoiding these utilities methods and how can i organize existing project to remove all STATIC utilities.
Can you help me avoiding static method ?
There is nothing wrong with having lots of static methods.
Static methods are (or should be, read on) stateless, which makes them the easiest methods to test - there's no setup, just call them.
You don't need mocking, because there is no state to deal with.
Regarding being stateless, technically static methods can be stateful if they use static variables to store state. If this is the case, from a good-design perspective they should be converted to instance methods using instance variables to store state, employing the singleton pattern if required.
To contradict the other answers currently available: Static methods are bad!
They do introduce strong coupling. Yes there are cases where it is acceptable. Yes you can make a seam for inside a static method, by making the strategy used inside exchangeable. But as a rule of thumb static are still bad.
To answer the question, how to get rid of static methods. Simple: put them on a proper Object. All statics are gone. Have we improved our code? not much yet. If we replace
callToStaticMethod()
with
new X().callToNoLongerStaticMethod()
we replaced a static call with a constructor call which is essentially just another static method. But now your X is just another dependency, so you can inject it:
class A{
private final X x;
A(X aX){
x = aX;
}
}
Note: there is no need to use Spring or any other framework for this. If you feel like it provide a constructor which uses the default implementation. If you are a purist, introduce an interface for X.
Testing A without relying on the implementation of X becomes trivial and obvious. Same for replacing X in any way.
Static utility methods are not so bad. You can hide a package-private strategy behind the static call. This can be easily tested (and replaced) given that the test case belongs to the same package. Moreover, it makes the code very readable. Of course, the clients of the static utility method can still only use one implementation in their tests. So here is some inflexibility.
Bohemian is right when talking about state. If your static utilities have state you are doing something wrong.
About your question: If you want to avoid static methods you can use the spring framework and define different implementations of utilities that you use and test in different contexts. In this case, however, access to these objects is not so convenient as you must first obtain a reference to the context that knows your utility object.
Nothing wrong with a set of static utility methods that belong together in a class. See for example java.util.Collections. If every method in that class that operates on a List would be specified in the List interface itself, they would have to be implemented by all subclasses. As long as they can be implemented by the public List methods, there is no problem.
Of course, as soon as you start adding methods to the interface (or in case of a class, making methods public) only to be able to put functionality in static methods instead of the class itself, then you're on the wrong path.
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 4 years ago.
Improve this question
As per my understanding we should go for instance methods only when they are dealing with state of object i.e instance variable . If method does deal with state of object they should always be declared as class methods i.e static. But still in most of the projects
i ihave seen the methods which never not operates on instance variables they are also declared as instance methods(basically what these methods are doing they are using some of the method parametrs and doing some processing on that paremets and calling some other classes).Thats it.
Should not these methods should be declared as class method i.e static ?
It's likely the answer is yes: if you have an instance method that doesn't actually take advantage of the instance state, then it should probably be static, and possibly moved to a helper class depending on what it does.
Note that even if you don't access instance variables, accessing instance methods will also disqualify a method from becoming static. Also, if this method is an instance method in order to future-proof it (in anticipation of using the instance state later,) then changing it wouldn't be advisable either.
Also important is that public non-static methods could be inherited and overriden by a subclass, so making them static could actually break the code in possibly unexpected ways.
Here's a [possibly incomplete] list when you must use instance methods over static ones:
you access instance variables / methods from within the method
the method is an abstract method that you implement
the method is an interface method that you implement
you have doubts about the method staying static in the long-term
you declare it synchronized and don't want to lock on the class, rather on the instance
you get warnings when accessing static methods in a non-static way and you really care about them (sometimes you just can't avoid calling in a non-static way, so your only choice is making them methods non-static)
You could probably go static in all other cases.
Static methods have the disadvantage that they tightly couple callers to the implementation. Instance methods can be overridden or can be one of multiple implementations of an interface method.
In other words, instance methods can promote loose coupling, testability, and reuse.
You cannot expect everyone to follow a path all the time whether it is best practice or not. First, we are all humans. We can choose a way over something different sometimes and that shouldn't be fully correct all the time. Even Frameworks and Libraries and Languages are created by humans so an error shouldn't surprise you or bedazzle you.
For everything else, I concur dlev.
Suppose we're designing a new language and we want Sqrt to be an instance method. So we look at the double class and begin designing. It obviously has no inputs (other than the instance) and returns a double. We write and test the code. Perfection.
But taking the square root of an integer is valid, too, and we don't want to force everyone to convert to a double just to take a square root. So we move to int and start designing. What does it return? We could return an int and make it work only for perfect squares, or round the result to the nearest int (ignoring the debate about the proper rounding method for now). But what if someone wants a non-integer result? Should we have two methods - one that returns an int and one that returns a double (which is not possible in some languages without changing the name). So we decide that it should return a double. Now we implement. But the implementation is identical to the one we used for double. Do we copy-and-paste? Do we cast the instance to a double and call that instance method? Why not put the logic in a library method that can be accessed from both classes. We'll call the library Math and the function Math.Sqrt.