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
What's the difference in Java between a utility class (a class with static methods) and a Service class (a class with public methods that provides a "service"). For example, one can argue that a cryptographic object (providing methods to encrypt, decrypt, hash or get a salt value) is a Service provider, but many group this functionality into a Utility class with static methods, like CryptoUtil.encrypt(...). I'm trying to figure out which way follows better "design". Thoughts?
Different behaviors can be obtained by using different service objects. Static methods in a utility class can't be swapped out. This is extremely useful for testing, changing implementations, and other purposes.
For example, you mention a CryptoUtil with an encrypt method. It would extremely useful to have different objects that could support different encryption strategies, different message recipients, etc.
The difference is that service classes might have state. And by state I mean conversational state. Consider a notional ordering system.
interface OrderSystem {
void login(String username, String password);
List<Item> search(String criteria);
void order(Item item);
void order(Item item, int quantity);
void update(Item item, int quantity);
void remove(Item item);
void checkout();
Map<Item, Integer> getCart();
void logout();
}
Such a thing could be done with stateful session beans (as one example), although in that case authentication would probably be covered more traditional EJB mechanisms.
The point here is that there is conversational state in that the results of one call affects subsequent calls. You could view static methods as a bunch of simple stateless services that execute locally.
A service has a much broader meaning that includes, but is not limited to, being:
stateful;
remote; and
implementation dependent (ie through an interface).
Best practice I think is to simply use static methods as convenience methods (especially given Java's lack of extension methods). Services are much richer than that.
You cannot override static method, which can be a huge problem in case you'd like to implement your service in two different ways and switch between them. For this reason, I would limit the use of static utility classes to simple things which will "never" (for sufficiently long value of "never" :)) need to be done in more than one way.
I think there are no hard and fast rules.
I typically use static methods for functionality that requires few parameters, and can be accomplished in a single method call. Example:
calculate a hash value for a string
convert a date to standard representation
If a functionality requires many parameters, and if there are several related results being created, then it's more practical to have a classe that can accept the shared parameters in its constructor, with several methods that perform the actual action.
Typical example: A database connection, which you first connect, then use to do a query, then use to get the result...
I answered this question here somewhere before, but what I found was that it was very easy to change the behavior of a Service--to refactor it into multiple services--where it takes a pretty significant refactor if you use a static class.
If that is the only difference (and I believe it is), then it never makes any sense to use static classes.
Any time someone says "There will never ever ever be more than 1 of these", code for n of them.
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 3 years ago.
Improve this question
Assume a Java class (e.g. a helper class), which has a great bundle of methods that could be separated into different layers. By layers, I mean the design of clearer responsibilities for each class and a reduction of complexity. Is it meaningful in this case, by using abstract class, to achieve the goal, in the sense of clean code and software design?
I encountered the situation in a project where there is a helper class having too much complexity and simply too many rows. The class is somehow playing vital roles, acting as a kind of type helper assisting other objects to fetch and manipulate type information. Each time a new/existing type would need extra type info, this class comes into help, therefore becomes heavier and more complicated in implementing methods. Though I can surely categorize and separate those methods into many classes. I found there be a structural correlation between those methods. Please see the code example below:
Assume a Type can have some TypeProperty:s. Assume also in code that there are a Type class and a TypeProperty class, both with essential getters and setters, meanwhile a Helper class Helper.
public class Helper{
static final T CONSTANT_A = new A(...);
static final T CONSTANT_B = new B(...);
final Type theType;
//constructor etc.
Type getType(){
return theType;
}
Type getTypeByKey(Key typeKey){
//...
}
Collection<TypeProperty> getPropertiesByType(Type t){
//...
}
Collection<TypeProperty> getProperties(){
return theType.getProperties();
}
TypeProperty findSpecificPropertyInTypeByKey(Key propertyKey){
Set<TypeProperty> properties= theType.getProperties();
//loop through the properties and get the property,
//else return null or cast exception if not found
}
boolean isTypeChangeable(){
return findSpecificPropertyInTypeByKey().isChangeable();
}
//many more methods
}
I expect to refactor the Helper class so that the code is easier to maintain and expand, as well as, to be less complex. I think it is possible to separate the methods into different classes, however, this might lead to too many classes and the responsibilities are not straight-forward as they are not in a helper class(es). While in the meantime, the idea of utilizing abstract classes comes into my mind. Would it be meaningful then? Say that after refactoring, there would be
a TopLevelHelper having methods revolving the type itself, e.g. isTypeChangeable & getType(), as well as, all Constants;
a SecondLevelHelper extending TopLevelHelper, which bears the logics as middleware, e.g. getProperties and getPropertiesByType;
a LastLevelHelper extending SecondLevelHelper, which does the concrete and detailed works, e.g. findSpecificPropertyInTypeByKey.
Though none of these classes would have abstract methods but concrete implementations since none of the methods in higher-level helpers would be overridden. It does not seem that such a design is appropriate usage of abstract classes, still, I feel it separates responsibilities into three layers. Should it be done like this or should other techniques be used in this situation?
There's no definite answer of course, but I think you should stick with what you have. Abstract classes are mostly meaningful for implementing template methods and similar patterns. Splitting a class on different hierarchy levels does feel weird in your case, because the methods do seem to belong to different groups, rather than different levels. If java allowed multiple inheritance, traits, or something similar, you could make the mixin classes.
However, a class with multiple methods is fine. Although OOP design guidelines often say you should limit your class to eg 5 method, you class seems more of a smart data structure than a class, and your methods are mostly accessors and properties. So, since they are simple and conceptually similar, there's no real problem having many of them. Java itself does it all the time (for example, see string & collection classes reference).
I would say that layering is not a good approach.
From what you are saying about that 3 layers, they have different responsibilities. If all this 3 responsibilities are coded in the same class, it breaks the Single Responsibility Principle. So the solution that naturally follows is to split each one in its own class and use composition. By doing this you also adhere to the principle that says composition is preferable to inheritance.
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
Why would any one define a static method in an interface in JAVA 1.8?
I need to know the different examples/usecases/requirements where static method would come handy.
How can a static method in an interface would be beneficial for a developer?
There are many use cases for static methods in interfaces. The most common by far, though, is factory methods that have made it easy to create instances of their respective interfaces.
Consider these examples:
Comparator.comparing
List.of
Set.of
Stream.of, Stream.generate
Without these factory methods in interfaces, there would be too many constructor calls in disparate implementation classes.
Some of these examples were only added with version 9 of Java, but the feature opened many possibilities.
These static methods are also used for different purposes. It's now possible to have a method like Collections.sort implemented in the right place, Collection.sort, thus avoiding unnecessary extra classes.
Most commonly, factory and utility classes.
In addition to the factory examples in the other answer, consider the Collections class - this has been in the JDK for over a decade, but would never have been needed if the static methods could just have been defined on the Collection interface from day 1.
Here I found nice explanation why we have static methods in interfaces:
http://www.baeldung.com/java-static-default-methods
The idea behind static interface methods is to provide a simple
mechanism that allows us to increase the degree of cohesion of a
design by putting together related methods in one single place without
having to create an object.
Pretty much the same can be done with abstract classes. The main
difference lies in the fact that abstract classes can have
constructors, state, and behavior.
Furthermore, static methods in interfaces make possible to group
related utility methods, without having to create artificial utility
classes that are simply placeholders for static methods.
So yes, the one of the examples is that instead of creating utility classes for some behavior, calculation related to your interface, you can choose to define related static methods directly in the interface. So you group functionality on the right place. You avoid additional classes
public interface Vehicle {
static int getHorsePower(int rpm, int torque) {
return (rpm * torque) / 5252;
}
}
Vehicle.getHorsePower(2500, 480));
public interface Cube {
static double volume(double a){
return a * a * a;
}
static double surface(double a){
return 6*a*a;
}
}
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 7 years ago.
Improve this question
If you are creating a library to be re-used does it make sense (or in general usage), to create a class over a single dataype/variable. So for instance,
class DataSet
{
private HashMap<String,String> mapping;
public String getKey();
public String getValue(String key);
}
Let's say I have a method DataSet getDataSet(), Does it make sense to have this method in my API that returns HashMap or should it return DataSet?
Some benefits of returning DataSet over java collection type are -
Code is easy to very verbose and easy to read.
Writing unit tests at class level.
Finer control on internal storage structure - user cannot directly modify that collection.
Are there are disadvantages to this approach? Or is it always recommended especially when creating APIs/libraries to use own classes instead of known java datatypes?
Wrappers in general
As for the general question on whether to use wrappers or not that depends on the reasons and it may vary between use cases.
Some advantages of wrappers
Type safety: you could wrap a primitive to provide some sematic safety by the compiler. As an example you could use a class Key which contains a single string instead of just a String to point out that the string inside is meant to be a key. This might help you in cases where multiple strings might get confused.
Access control: like you described, allow read/write access etc.
"Manual" AOP: wrap setters/getters with logic.
Some disadvantages:
Code is more verbose and might get harder to understand/handle.
More effort is needed to write all those wrappers (and ideally documentation).
Existing/common datatypes like collections, strings etc. are more widely understood thus easing the learing curve.
Returning HashMap
If you'd return a map then I'd not return HashMap<String,String> but rather Map<String, String>.
Wrapper vs. Map
Besides that it depends on what you're trying to achieve. Of course using a wrapper object gives you more control of the API at the cost of more code to be maintained.
Delegation
Besides using DataSet as you described it delegation might be an option, i.e. a class that looks like a map but just delegates calls to an internal map. That way you could add functionality in the methods like preventing write access, validation in a transparent way (for read-only maps there are already delegate wrappers in the Collections class).
Unit tests
As for the "Writing unit tests at class level." point I'd say that also depends on what the wrapper would do. If it just resembles a map then creating a test for that wrapper only might be somewhat wasted time (you could just use an existing and already tested map implementation). Additionally you'd probably test the functionality that operates on/returns that wrapper/map and those tests would be mostly independent of whether you use a wrapper or a map.
That's just my 2 50 cents ;)
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
Thanks for your objectivity, especially where C# is your language of choice. Angry downvoters, I think I've asked a legitimate question here? Otherwise leave a constructive comment, please.
To the question...
C++ allows passing of (generic) function pointers simply, as follows: How to pass a generic function pointer as parameter
Java uses interfaces for this - also elegant from an OO perspective, we use nothing more than what the basic language already supplies.
However, I have never seen any real advantage to making delegate an explicit concept / keyword, as opposed to just managing the concept of callbacks the way that for example C++ or Java do -- by treating function pointers as just another circumstance under existing type system. (P.S. yes, C# generics are not the same as C++ generics, while Java has runtime rather than compile-time generics, but you get my drift).
(All hubris and dogma aside) Why did the designers of C# see fit to give a new name to a common, existing programming concept that could have been called a generic function pointer / callback? Could delegates not have been more simply represented in C#, without such a concept?
DISCLAIMER I've looked at quite a number of answers on stackoverflow and not one of them has satisfactorily answered why the designers saw fit to include another keyword for something so fundamental as callback handling.
C++ had "official" (non-Boost) "full" delegates from C++11 (std::function)... Before that, getting a pointer to a member function was always a little hackish... So I wouldn't consider C++ to be a good comparison :-) And C++ can overload the round parenthesis, so it is more easy to "hide" the hacks that need to be done and give to the programmer a "simple" way of using the std::function.
Now... Java... To "correct" (but let's say it wasn't an omission, but a calculated decision, so they didn't have anything to correct) the missing delegate concept they first had to introduce anonymous classes in Java 1.1 and then in Java 8 they introduced functional interfaces (as a non-Java programmer, I consider the last thing to be a little hackish... meta-describing that an interface has a single method and then enforcing it at compile time... I don't like it very much...). This because otherwise the boilerplate code that is needed is quite much...
Let's start simple... The IComparer<> interface... It is an interface with a single method, so it is very similar to a delegate...
a simple implementation:
public class MyComparer : IComparer<int>
{
public int Compare(int x, int y)
{
return x.CompareTo(y);
}
}
There is a boilerplate row here, the first one (public class MyComparer : IComparer<int>). By introducing the C# delegate you already gained one row for each use of a delegate... But wait! Let's say that your "delegate" needs a reference to the class that "contains" it...
public class MyComparer : IComparer<int>
{
public MyClass Target;
public int Compare(int x, int y)
{
return Target.Ascending ? x.CompareTo(y) : y.CompareTo(x);
}
}
And now this class needs to be a nested class of MyClass. Note that I don't have anything against nested classes...
We have added a new line (public MyClass Target)... But this code is normally wrong to write... You shouldn't have public non-readonly fields. You could use an auto-property public MyClass Target { get; set; } but that too is synctactic sugar introduced in C# 3.0... without them the boilerplate code would grow... And I would prefer to have a private readonly MyClass Target.. But then I would have to add four lines for the constructor... How many lines do you want me to write for a delegate? :-)
And still C#/.NET delegates give more flexibility: the function you use can have any name, so you can have multiple of them in the same class... The MyComparer could have been implemented as two methods:
public int CompareAscending(int x, int y) {}
and
public int CompareDescending(int x, int y) {}
without adding too much code, or splitting everything in multiple (nested) classes.
Delegates are more than a simple callback. First, it works both for static methods and instance methods and the caller doesn't have to take care of the differences. Second, delegate is not a single method pointer. It can be a "pointer chain", so the caller can call many callbacks with a single call - and again, the caller doesn't have to bother wheter it is a single or multiple call.
Yes, one can implement the same mechanism from scratch - but one can build everything using machine code - what need for high level languages.
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
To clarify, this is what I mean:
public Image getRespectiveImage(int temp) {
switch(temp){
case 1:return one;
case 2:return two;
case 3:return three;
case 4:return four;
case 5:return five;
}
return null;
}
compared to
public Image getOne(){return one;}
public Image getTwo(){return two;}
public Image getThree(){return three;}
public Image getFour(){return four;}
public Image getFive(){return five;}
I tend to prefer the former because it just seems simpler for some reason, but everyone seems to use the latter. Is there a reason why someone would use the bunch of getter methods?
It's not really about "which is better or worse" -- If the properties you are writing getters for are not, by nature, indexed, then it would make no sense to write an indexed getter for them. If your properties are not of the same type, that is a good clue that an indexed representation isn't generally going to be helpful.
If the properties you are using do make sense to store as an indexed list, then sure, by all means -- but then I would also use an array for the field (consider: If an array type is not appropriate for that field, then perhaps an indexed getter is not actually appropriate either).
You generally want your getters and setters to reflect the fields you have declared. You would use a getter/setter that takes an int index parameter when your field is an array type (which conforms to the JavaBeans spec, section 8.3.3).
You want to do this for two reasons. First, on a conceptual level, if your fields are significantly different from your getters/setters, while there are tons of valid reasons for this, you may want to take a look at how you've organized your fields to see if you can refactor to something that more accurately represents the purpose of your object (it is assumed that public getters/setters are good representations of this purpose). It may be an indication of bigger design issues.
Secondly, and this is more just about being aware of what you are doing, your getters and setters will affect interaction with APIs that operate on beans, and will also affect interaction with APIs that use reflection. For example, Hibernate can be configured to persist objects to a database using getter/setter properties, or direct field access. So depending on the configuration there, you have to at least be aware of your getter/setter vs. field setup.
The take home point here is: Don't try to come at this with the idea that there is a set of rules defining when one way is better or worse. Just consider the nature of the objects you are working with, and what their properties actually mean (semantics), and write a public interface that makes sense.
It's good practice to have getters and setters for all private variables that you want the user to interact with.
While your above solution simplifies, it will confuse other people that work with your code because it is not common practice.
It depends on the problem you're facing. There's nothing wrong with the first approach, even more if you use an "enum" to restrict and document the options:
enum ImageCategory {
Unchecked,
Checked,
Disabled;
}
Image getRespectiveImage(ImageCategory category);
Just be sure that every "category" represents an instance of the same nature.
On the other side, it's clearly not a good thing to have a method like this:
Object get(String property);
Unless you're writing your own Dictionary/Map class.
Using a bunch of getter methods has two noticable advantages over the first approach.
The getter methods, when named properly, self document what it is that you're getting from the object.
In the first case, you would need to provide the user with some kind of documentation that tells them which input corresponds to return. This is not necessary when you have separate getters. (It places a greater burden on the clients)