Zero instance enum vs private constructors for preventing instantiation [closed] - java

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 8 years ago.
Improve this question
Some utility classes (think java.lang.Math) declares only a private constructor in order to prevent instantiation of the class.
Is there any particular reason for why such classes are not implemented in terms of a 0-instance enum? It seems to me like enums is a more direct way of controlling instantiation than access modifiers on constructors. It also prevents the class itself from creating instances which both prevent the programmer from shooting himself in the foot and convey a guarantee outwards of no instances.
Joshua Bloch advocates the use of enums for singletons. Shouldn't the same benefits apply to 0-instance utility classes?
My question: What are the pros/cons of 0-instance enums vs private constructors. (I personally see no drawbacks of using an enum, though private constructors seems to be the more prevalent approach.)
(I know java.lang.Math predates enum. I'm talking 1.5+ code here.)

The fact that enums cannot be instantiated is a side-effect. When you declare something as an enum, people would expect it to be an enum; it will appear as enum in the IDE, code analysis tools, whatever.
Following the principle of least astonishment, and given that the user doesn't care of how you internally achieve that, I think it's better to use a private constructor, and also throw an Error from that constructor, provided someone tries to instantiate it with reflection.

So, to summarize the answers and comments so far:
Arguments supporting 0-instance enums:
Enum solves the problem of controlling instantiation of classes which is precisely what a 0-instance utility class needs.
Weekday has 7 instances, Month have 12, MySingleton has 1 (and should according to Joshua Bloch be implemented by means of an enum) and MyUtilityClass has 0 instances. There is no conceptual difference between the last case and the former ones.
A 0-instance enum guarantees that no instance will be created, not even from within the class itself.
Arguments against 0-instance enums:
Does not follow the principle of least astonishment; when people see an enum, they expect it to follow the text-book examples of non-empty enums such as weekdays, status codes etc.
The 0-instance enum is an idiom not widely used and thus not something other programmers recognize easily. I.e. it's less readable than using private constructors.
Enums are cluttered with implicit synthetic methods, which means that those names are not allowed for custom-defined methods. Furthermore, the fact that a public API exposes methods which should not be used can range from awkward to broken.
Other notes
Related question and answer.
Blog post on the subject by Peter Lawrey.

I don't know of any technical drawbacks with either approach.
As for elegance, that is a matter of opinion, and (IMO) not particularly relevant to the real purpose(s) of most computer programs.
By contrast, readability, maintainability and correctness are properties that are relevant to purpose. And one aspect that helps to make a program readable is the use of idioms that other programmers can readily recognize. Zero-instance enum types are an interesting idea ... but private constructors are the established idiom for preventing instantiation.

Related

Is it meaningful to have abstract classes just for purpose of layering structure? [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 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.

Java: place of constructors, static methods, public methods, private? [duplicate]

This question already has answers here:
Are there any Java method ordering conventions? [closed]
(8 answers)
Closed 7 years ago.
I have come to the question: what is the most preferred way of placing methods? I mean, should first declare static methods, then constructors, then public methods, then protected, then private, etc? Is there some kind of convention, like I guess everyone places fields (instance variables) on top of the code. Is there the same policy about methods?
I guess it depends on the language you use. What about Java?
This is somewhat opinion based, but the Google Java Style doc puts it nicely:
The ordering of the members of a class can have a great effect on learnability, but there is no single correct recipe for how to do it. Different classes may order their members differently.
What is important is that each class order its members in some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield "chronological by date added" ordering, which is not a logical ordering.
https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s3.4.2-class-member-ordering
Most of the code I see in the open source world uses some variation of
static fields
instance fields
constructors
methods (instance and static)
anonymous classes
It comes down to team preference, but it is always good to follow convention
Talking about execution, JVM guarantees the order which we cannot change.manage.
But from code readability point of view , YES ordering does looks good. Following coding standards is what should do.
Static fields -> instance fields/variables
As we know, Static Block is always called once class is loaded, so we should have it.
Then constructors, for object creation, there is no point of writing constructor at the end.
also a good read here as suggested above.

Java: Include "this" parameter or let it be implied [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 8 years ago.
Improve this question
Is there a Java recommendation or industry best-practice suggestion for including, or not including, the this parameter when it isn't explicitly necessary?
For instance, assuming there are no naming clashes between instance variables and local variables, is it preferential to use
this.someParam
or simply
someParam
and when calling methods that are in the same class is it preferential to use
this.someMethod()
or
someMethod()
The argument in favor of the former is that it makes the code more explicit. The argument in favor of the latter is that it makes the code cleaner.
I'm curious if there is any documentation out there that recommends one way or another (I can't find any, google searches with the word this are obviously tricky) or if it is simply a matter of preference.
On the merits of explicit versus cleaner: Excluding "this." is no doubt less text character "noise" (albeit small) in source file. The "this." explicitness would be helpful for example if using a small text viewer when looking at a method with many lines of code (should that be the case anyway?). So at best the explicitness has limited usefulness - especially as modern IDEs highlight instance variables. I am of the opinion of excluding "this." as code style.
I don't know that there is a "wrong" answer here. However, in my 15+ years writing Java, the convention that I have seen is to NOT include "this" unless it is necessary.
You can minimize confusion by naming variables in a consistent way. There are several good convention documents out there. Pick one and follow it. Some examples:
http://google-styleguide.googlecode.com/svn/trunk/javaguide.html
https://source.android.com/source/code-style.html
http://www.javaranch.com/style.jsp
There is no reason to prefer one or the other. It's a matter of opinion.
My opinion is that you should only use this if needed. There are some situations when you have to use this, such as if a local variable has the same name as an instance variable. It happens a lot in my constructors:
public MyClass(String s, int i) {
this.s = s;
this.i = i;
}
If you are working on a team, I recommend coming up with a strategy you all agree with, so you don't waste too much time reformatting each others code. Also, for me, it's pretty annoying to look at code that uses this too much (such as that generated by JD).
As for:
parameters/attributes - I always suggest using consistent approach throughout the code. In most cases all automatically generated getters and setters of Java classes need to use this to distinguish parameter name from actual object attribute. Consistency is then a good reason to use this for instance variables throughout the code. Sample setter which uses this to avoid ambiguity:
public void setName(String name) {
this.name = name;
}
methods - this.someMethod() is just longer than someMethod() and does not provide any benefit over the shorter someMethod(). If we call the latter, it is already known that we are in fact calling this.someMethod(). There is no ambiguity in calling just someMethod() like it is for parameters, so I would discourage the use of this.someMethod().
In my opinion, there is no common guidelines for all Java developers in the world defining good practices for using this. I'd rather follow the guidelines used in your company/project, or, if there are none, your own ways of writing well-read code.
There isn't a best-practice suggestion. Most teams simply have their own coding style.
Personally, I try to use use this for all my instance variables, but tend to avoid it for methods.

Interface or Class for a list of static finals? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am maintaining some Java code that utilizes an interface (let's call it BunchOfConstants) to simply store an abundance of public static final Strings. Occasionally these string names change or string names are added / removed. (which causes a bit of a headache for maintanance)
The only current use for this interface is to compare to input later in a big ugly if/then construct like this:
if(BunchOfConstants.CONSTANT1.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT2.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT3.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}
...
I thought it would be more elegant to create a class that implements Iterable or even a class that stores this data in a hashMap.
I can not figure out why the original developers decided to use an interface for this design as the interface is never actually implemented anywhere. Does anyone have any input?
Would you agree that an iterable class with these members as constants would be more appropriate?
Use enums. Then get myenum.values() and then apply a for-each loop over the values.
I would consider using enums instead as constants are not type safe (e.g., they are just ints, or strings, etc.).
This (having dedicated interface for storing constants) was a fairly common way of storing constants before the era of enums. (Pre Java 5 times.) It saved you the hassle of prefixing your constants with the containing class name. I personally never really liked this practice, but this is the reason people did it.
As for what it can be replaced with:
An enum and a switch/case construct. This requires the least modification but only has modest benefits in readability. It does give you type and value safety, plus you can get warnings out of your IDE if you forget to handle a possible value (no case for it and no default block either).
A properties file. This obviously only works if you don't want to branch based on your constant values. (I.e. if your constants don't have to appear in your source code.) This is important, otherwise you'd end up with a secondary set of constants and a properties file, which is as bad as it gets.
A doSomeStuff() factory. For this you have to wrap your doSomeStuff() implementations in separate operation classes and you can configure your factory either statically or from a properties file. (via a constant value->operation class mapping). This is the most "enterprisey" solution, which means that although it looks nice and is very flexible, a lot of the time it is an overkill.
I think this is a good candidate for enum
Well, this looks like the Constant Interface antipattern and maybe should not be used. Using an enum might be a way as suggested, or at least using a final class with private constructor.
If you want to have different implementations for doSomeStuff based on the input string, you might also consider using the strategy pattern, i.e. have a Map<String, Strategy> and then lookup the strategy for whatImLookingFor. If you found the strategy, execute its doSomeStuff, otherwise handle the "not found" case.
I would suggest you to use a property file to store all your constants. This way you can load your properties into a HashMap as you suggest in your question.
Note that property support is brought natively with java: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Properties.html
Well, enums are the way to go ... but if the 'dosomestuff' is semantically dependent upon the specific value then why not add a 'dosomestuff' method to the enum itself. That is one that this is really great about Java enums - they are not merely data but as all good objects they have semantics. Then you just loop over the enums invoking dosomestuff(whatIamLookingFor) and whatever happens happens.
Hard to say.
Yes, I agree, that it will be more elegant - at least for you. But think, what the next programmer will think about it. It will be even more complicated.
Previously mentioned strategy pattern and java's enum are definitely better solution, but since you are maintaining this code, I'm not sure if your boss will be happy with time consuming refactoring. My advice would be to use enums - not so big code change.

Would syntax for composition be a useful addition to 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 5 years ago.
Improve this question
First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:
a: why it sucks
b: how language x has had that for years
c: how my mind sucks
d: all of the above
The idea would give composition the same ease of code reuse that extends does.
So if you had a class like this:
public interface A {
public void methodInA();
}
And then you had a class like this:
public class B {
private composed A;
public B() {
// construct A within constructor
}
}
You would then be able to do this:
B myB = new B();
myB.methodInA();
Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie:
#Overrides
public void methodInA(){
// B's own delegation method
}
Disadvantages include:
methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with extends
if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)
if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to
probably 100 other things I've not thought of
Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.
It sounds cool but I think it makes for some horrible language constructs. Obviously there is a problem if you declare more than one 'composition' of the same class, but even if you forbid that what about the case where a call matches a method in more than one of the (different) composed classes? You would have to specify which one was called in the main class, and you would need extra syntax for that. The situation becomes even worse if there are public members in the classes.
Composition is used to prevent problems with multiple inheritance. Allowing composition like this is effectively permitting multiple inheritance, at least in terms of resolving which method to call. Since a key design decision with Java was to disallow multiple inheritance (for good reasons) I think it unlikely that this would ever be introduced to Java.
I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed.
Personally I hate inheritance of concrete classes. I'm a big proponent of Item 14 from Bloch's Effective Java, Favor composition over inheritence. I think that something like this would make it a little easier to implement the idiom he recommends in that item.
Honestly, if you really knew what you were doing I'll bet you could write a compiler annotation that would handle this. So assuming you had a class Bar that implemented the interface IBar, your class would look like this:
public class Foo {
#Delegate(IBar.class)
private Bar bar;
// initialize bar via constructor or setter
}
Then during compilation Foo could be made to implement IBar and any of the methods on that interface that weren't already implemented by Foo would end up being generated to look like this:
public Baz method1(Qux val) {
return bar.method1(val);
}
As mentioned above you would want to make the restriction that only one field per class could use this annotation. If multiple fields had this annotation you'd probably want to throw a compilation error. Alternatively you could figure out a way to encode some sort of precedence model into the parameters passed to it.
Now that I've written this out that seems kinda cool. Maybe I'll play around with it next week. I'll update this if I manage to figure anything out.
I'm not sure that I see a clear advantage to doing this though. I understand the point you are making. At the moment to call a method on A you have to myB.getAInstance().methodInA(), but you want to make that myB.methodInA().
But, what happens if you have multiple instances of A? How would the method call be resolved? Many times composition implies a one to many association so B has many A instances. What happens then?
I agree with your disadvantages listed. It may simply cause too much confusion than it is worth.
Check out what is called "Mixins" in some languages, and "Roles" in the Perl 5 Moose OO system.
There's also the difference between composition and aggregation to consider. How does the compiler know whether you mean 'is-a' or 'has-a' relationships?
Does the whole object graph become eligible for garbage collection or only the head of the graph?
A couple of the ORM mapping tools and frameworks over/around them provide for belongsTo or has-many relationships between persistent objects and some also provide for the cascading delete (for composition). I don't know of one off hand that provides the simple syntactic sugar you're looking for.
Actually, on second thought, Groovy's MetaClass and MetaProgramming idiom(s) may provide something very similar, with 'auto-magic' delegation.
Multiple inheritance is allowed in C++, I know that different but it is along the same thought process. Java was designed to not allow multiple inheritance so that there would be less confusion, therefore bugs and exploits.
What you have suggested is in direct conflict with the principles of java.
Having said that, it would be cool (not necessarily useful). I'm a java programmer who switched from C++. I like being able to make my own mistakes.

Categories

Resources