Is a public setter necessary for private static variable? - java

/* Atleast is it needed in this case?*/
public class Service
{
private static List<String> subscribedFields;
private static List<String> unsubscribedFields;
//---------------------------------
// is this necessary?
//---------------------------------
public static void setFields(List<String> subscribedFields, List<String> unsubscribedFields)
{
Service.subscribedFields = subscribedFields;
Service.unsubscribedFields = unsubscribedFields;
}
public static List<String> getSubscribedFields()
{
return subscribedFields;
}
public static List<String> getUnsubscribedFields()
{
return unsubscribedFields;
}
}
// some other class
public class User{
// Is this not enough to change the lists? Isn't the setter redundant?
Change(Service.getSubscribedFields());
Change(Service.getUnsubscribedFields());
}

No, a public setter is not always needed for a private variable. The idea of providing public setters (and getters, for that matter) is based on - what external entities such as classes need access to the insides of the particular piece of code you are writing. Getters and setters provide that public interface for that to happen. However, you don't necessarily NEED to provide a public getter or setter to every private variable you create as that private variable may only exist for internal, private use to the class.
You'll have to decide if you specifically need to give access to your private variables based on the particular needs of your code.
Update Based on ada's Question in Comments
You could give the user access to your lists directly (yes - they can use the getter and then edit the list). This may work if you trust the users of your code. However, for various reasons, you may not want to give them direct access to your list like that (especially because it gives them free reign to do what they want to do, it can create problems if you have threading within your application, etc). In that case, you should provide interfaces into the underlying list. For example, in your class, instead of providing a getSubscribedFields(), you may want to provide methods like:
// Pseudocode
public String getSubscribedField(int i) {
return subscribedFields.Get(i);
}
public String addSubscribedField(String field) {
subscribedFields.Add(field);
}
Hopefully that helps clarify things a bit for you.

The more popular choice in this case is to use a Singleton which you initialize once with the fields. However, not even Singleton is really a good idea, but to do otherwise requires that we know a bit more about what you're trying to do. In most cases you can get around using static instances by making it a member of a class with a long lifetime. For example, if these fields were related to database fields, you'd associate it with a table class which holds information pertaining to a database table for instance.
Really it depends on what you're trying to accomplish.

No you shouldn't. And even more you should avoid static state.

Your class seems to be very prone to thread safety problems. I also question the relevance of your need to put your List as static variables.
Another thing, your setter isn't in line with JavaBeans setters & getters standards, you might have problem if you want to integrate with some common frameworks.
I suggest you a variation of your class. I refactored it in order to keep the responsibility of the class is to hold the subscriptions.
If you use a dependency injection framework like Spring or Guice, you could simply make a class like this one, and inject it to the classes that need this object.
public class SubscriptionServiceUsingDependencyInjection {
private final Set<String> subscribedFields = new CopyOnWriteArraySet<String>();
public boolean isSubscribed(String field_) {
return subscribedFields.contains(field_);
}
public void subscribe(String field_) {
subscribedFields.add(field_);
}
}
Otherwise If you really need a Singleton, you may use an enum to achieve the same goal :
public enum SubscriptionServiceUsingASingleton {
INSTANCE;
private final Set<String> subscribedFields = new CopyOnWriteArraySet<String>();
public boolean isSubscribed(String field) {
return subscribedFields.contains(field);
}
public void subscribe(String field) {
subscribedFields.add(field);
}
}
The CopyOnWriteArraySet will prevent concurrency problem if you are running this in a multithreaded environment.

Related

Is it bad practice to use Consumers as setters and Suppliers as getters in Java?

I have a Java class that has some private variable that I don't intend to create setters and getters for; I want these variables to remain inaccessible. But there is one class that needs access to these variables. This class is a visitor in a different package (and I'd prefer to keep it in a different package). Is it bad practice to allow this class to provide the visitor with Consumers and Suppliers, that act as setters and getters, so that the visitor could read and modify these variables? If yes, please state the reasons.
Example:
A.java
public class A {
private int x;
private Consumer<Integer> setter;
private Supplier<Integer> getter;
public A(int v) {
x = v;
setter = new Consumer<Integer>() {
#Override
public void accept(Integer t) {
x = t;
}
};
getter = new Supplier<Integer>() {
#Override
public Integer get() {
return x;
}
};
}
public void accept(SomeVisitor visitor) {
visitor.setSetter(setter);
visitor.setGetter(getter);
visitor.visit(this);
}
}
SomeVisitor.java
public class SomeVisitor extends ParentVisitor {
private Consumer<Integer> setter;
private Supplier<Integer> getter;
public SomeVisitor() {
setter = null;
getter = null;
}
public void setSetter(Consumer<Integer> setter) {
this.setter = setter;
}
public void setGetter(Supplier<Integer> getter) {
this.getter = getter;
}
#Override
public void visit(A a) {
// Code that will, possibly, read and modify A.x
...
}
}
This way the variable A.x remains inaccessible to every class except the visitor.
More Details:
I have some classes that will make use of the visitors. These classes have private variables that are dependent on one another. If these variables had setters, inconsistencies could arise as users change these variables, that should be dependent on one another, without respecting these dependecies.
Some of these variables will have getters, others won't as they will only be used internally and shouldn't be accessed elsewhere. The reason the visitors are an exception and should get read/write access to these variables is that the functionality the visitors are intended to implement were meant to be implemented within methods in these classes. But I thought it will be cleaner if I used visitors. And these functionalities do need read/write access to these variables.
The intention behind this approach was to emulate the friend feature in C++. I could place the visitors within the same package as these classes (which I would do if I didn't find a neat solution to this problem); But I think the package will look messy if it had the visitors as well (and there will be many visitors).
The functionality the visitors will implement will also have something to do with these classes relations to one another.
I tried to squeeze it into a comment, as it technically does not answer the question about whether this is a "Bad Practiceâ„¢", but this term is hard to define, and thus, it is nearly impossible to give an answer anyhow...
This eventually seems to boil down to the question of how to Make java methods visible to only specific classes (and there are similar questions). The getter/setter should only be available to one particular class - namely, to the visitor.
You used very generic names and descriptions in the question, and it's hard to say whether this makes sense in general.
But some points to consider:
One could argue that this defeats the encapsulation in general. Everybody could write such a visitor and obtain access to the get/set methods. And even though this would be a ridiculous hack: If people want to achieve a goal, they will do things like that! (sketeched in Appendix 1 below)
More generally, one could argue: Why is only the visitor allowed to access the setter/getter, and other classes are not?
One convincing reason to hide getter/setter methods behind Supplier/Consumer instances could be related to visibility and the specificness of classes (elaborated in Appendix 2). But since the visitor always has the dependency to the visited class, this is not directly applicable here.
One could argue that the approach is more error prone. Imagine the case that either the setter or the getter are null, or that they belong to different instances. Debugging this could be awfully hard.
As seen in the comments and other answer: One could argue that the proposed approach only complicates things, and "hides" the fact that these are actually setter/getter methods. I wouldn't go so far to say that having setter/getter methods in general already is a problem. But your approach is now to have setter-setters and getter-setters in a visitor. This extends the state space of the visitor in a way that is hard to wrap the head around.
To summarize:
Despite the arguments mentioned above, I would not call it a "bad practice" - also because it is not a common practice at all, but a very specific solution approach. There may be reasons and arguments to do this, but as long as you don't provide more details, it's hard to say whether this is true in your particular case, or whether there are more elegant solutions.
Update
For the added details: You said that
inconsistencies could arise as users change these variables
It is usually the responsibility of a class to manage its own state space in a way that makes sure that it is always "consistent". And, in some sense, this is the main purpose of having classes and encapsulation in the first place. One of the reasons of why getters+setters are sometimes considered as "evil" is not only the mutability (that should usually be minimized). But also because people tend to expose properties of a class with getters+setters, without thinking about a proper abstraction.
So specifically: If you have two variables x and y that depend on one another, then the class should simply not have methods
public void setX(int x) { ... }
public void setY(int y) { ... }
Instead, there should (at best, and roughly) be one method like
public void setState(int x, int y) {
if (inconsistent(x,y)) throw new IllegalArgumentException("...");
...
}
that makes sure that the state is always consistent.
I don't think that there is a way of cleanly emulating a C++ friend function. The Consumer/Supplier approach that you suggested may be reasonable as a workaround. Some (not all) of the problems that it may cause could be avoided with a slightly different approach:
The package org.example contains your main class
class A {
private int v;
private int w;
public void accept(SomeVisitor visitor) {
// See below...
}
}
And the package org.example also contains an interface. This interface exposes the internal state of A with getter+setter methods:
public interface InnerA {
void setV(int v);
int getV();
void setW(int w);
int getW();
}
But note that the main class does not implement this interface!
Now, the visitors could reside in a different packakge, like org.example.visitors. And the visitor could have a dedicated method for visiting the InnerA object:
public class SomeVisitor extends ParentVisitor {
#Override
public void visit(A a) {
...
}
#Override
public void visit(InnerA a) {
// Code that will, possibly, read and modify A.x
...
}
The implementation of the accept method in A could then do the following:
public void accept(SomeVisitor visitor) {
visitor.accept(this);
visitor.accept(new InnerA() {
#Override
public void setX(int theX) {
x = theX;
}
#Override
public int getX() {
return x;
}
// Same for y....
});
}
So the class would dedicatedly pass a newly created InnerA instance to the visitor. This InnerA would only exist for the time of visiting, and would only be used for modifying the specific instance that created it.
An in-between solution could be to not define this interface, but introduce methods like
#Override
public void visit(Consumer<Integer> setter, Supplier<Integer> getter) {
...
}
or
#Override
public void visit(A a, Consumer<Integer> setter, Supplier<Integer> getter) {
...
}
One would have to analyze this further depending on the real application case.
But again: None of these approaches will circumvent the general problem that when you provide access to someone outside of your package, then you will provide access to everyone outside of your package....
Appendix 1: A class that is an A, but with public getter/setter methods. Goodbye, encapsulation:
class AccessibleA extends A {
private Consumer<Integer> setter;
...
AccessibleA() {
EvilVisitor e = new EvilVisitor();
e.accept(this);
}
void setSetter(Consumer<Integer> setter) { this.setter = setter; }
...
// Here's our public setter now:
void setValue(int i) { setter.accept(i); }
}
class EvilVisitor {
private AccessibleA accessibleA;
...
public void setSetter(Consumer<Integer> setter) {
accessibleA.setSetter(setter);
}
...
}
Appendix 2:
Imagine you had a class like this
class Manipulator {
private A a;
Manipulator(A a) {
this.a = a;
}
void manipulate() {
int value = a.getValue();
a.setValue(value + 42);
}
}
And now imagine that you wanted to remove the compile-time dependency of this class to the class A. Then you could change it to not accept an instance of A in the constructor, but a Supplier/Consumer pair instead. But for a visitor, this does not make sense.
As getters and setters are evil anyway, you'll be better off making things not more complicated than ordinary getters and setters.

OO design and Initializing Static members in Asbtract Super class

There are 7-8 class (implements callable) which have some similar behaviour i.e. these have some similar functions with similar implementations. And also all of these makes use of a HashMap (only for reading purpose) which is same for all these classes.
So I decided to make a abstract superclass containing all the similar methods plus this hashMap as a static member.
And I will be making subclasses for these 7-8 callable classes (hence those will also be callable by inheritance), so that performance of app can be improved.
Now I have 3 queries :
1.) Is there any flaw in this design and can I even further improve it ?
2.) Can there occur any concurrency issues as it's a three level hierarchy with callable classes at bottom two levels?
3.) Is initializing static member(hashmap) inside static block wrong ? As my boss is obsessively against using static members and blocks. So what possible problems can occur if I initialize this map inside static block ?
public abstract class AbSuper {
private static HashMap hmap;
private static CompletionService<String> service;
private static int maxThreads = 10;
static{
initializeMap();
}
public static void initializeMap(){
//load from file
}
public HashMap getmap(){
return hmap;
}
public void commonMethodOne(){
//do something
}
public static CompletionService<String> getService(){
ExecutorService executor = Executors.newFixedThreadPool(maxThreads);
service = new ExecutorCompletionService<String>(executor);
return service;
}
}
public class CallableOne extends AbSuper implements Callable<String>{
private List<String[]> taskList;
protected HashMap resultMap;
public List<String[]> getTaskList(){
return taskList;
}
public String call(){
for(String[] task : getTaskList()){
getService().submit(new SubCallableOne(task));
}
return "done with Callable One";
}
}
public class SubCallableOne extends CallableOne {
String[] task;
public SubCallableOne(String[] task) {
this.task = task;
}
public String call(){
//do what you are suppose to do
//and then access and populate "resultMap" fom superclass
return "done with subCallableOne";
}
}
There will be 7-8 CallableOne/two/three and thier corresponding SubCallableOne/two/three.
1) Do you really need to use static members? If so, maybe you should encapsulate that in a separate class and use it through encapsulation instead of inheritance. I'd still keep a superclass with the common methods.
But in any case, your current code has issues. Namely:
You are exposing the map via the public method AbSuper.getMap and it is mutable. Any code could add, delete or overwrite entries. Should it really be public? It looks like only subclasses are using it. If so, you could make it protected and return them a read only map, or a copy, or create a protected function readFromMap(key) instead.
Same for the AbSuper.getService method: it is public and static. Any code in any class could submit tasks or shutdown it. Except that you are creating a new executor each time. This is probably a bug, as each call to getService will override the service variable. Looks like you were trying to implement a singleton here but failed.
2) Callable classes might be the ones at the bottom, but you are exposing functionality in the base class to every other class in your program due to public static methods, and to anyone holding an instance due to public methods. And even if these methods didn't exist, the fact that all your instances use a shared map and executor service could result in accidental side effects. Execution order of submitted tasks, for instance.
3) It is not wrong per se, but statics are well known code smells. It makes classes hard to test. And cannot be overriden. In pure OO design there should be no need for statics. In your case, the map will be initialized the first time the class is loaded, so any call to AbSuper.getMap will get the map populated. But there are two problems with your map. The first one is that this is usually no place for long operations like populating a map from file. You should make long operations explicit, don't hide them in constructors or static initializers. The second is that the map is mutable.

How to create a class with a package private constructor?

I'm working on a library where I want to return an object representing a real world object. I want to expose this class to developers to manipulate the real world object, but I don't want to allow them to construct these objects themselves.
Example
public class World {
public static List<RealObject> getAllObjects() {
// How to create RealObject with physicalID?
}
}
public class RealObject {
private int physicalID;
public RealObject(int physicalID) {
// Undesirable, user has no knowledge of IDs
}
public void setState(int state) {
// Code using physicalID to change state
}
}
These objects currently have no constructor and have a private id field that I set with reflection from within my library. This works perfectly, but I can't help but think there must be a better solution. Perhaps a useful constraint in my situation is that it only needs to be possible to construct this object from one other class.
Is there a better solution? And is it still possible to have the class in a separate file in that case for organizational purposes?
If you put default access level on constructor (or any other method), then can be accessed only by classes from same package.
To concretely answer the question in the title:
public class RealObject {
RealObject(int physicalID) {
// Package-private constructor
}
}

Java - Restricting by what a method can be called

I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:
if(trace.length<2){
throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}
Is there something else I should be doing, or should I just not forget how my program works?
You should be using visibility to restrict calling - making a method public (or for that matter, javadocing it) is not going to work unless you have dicipline (and you control the callers too). From your description, you are neither.
What you can do is make the class package private, and put it in the same package as the two callers of that class. As long as you have a proper package structure, this can work. E.g.:
Your class that should only be called by A and B:
package thepackage.of.a.and.b;
//imports here
class CallableByAB {
public void methodA(){}
public void methodB(){}
}
A:
package thepackage.of.a.and.b;
public class A {
/*...other code here */
new CallableByAB().methodA();
/*...other code here */
}
B:
package thepackage.of.a.and.b;
public class B {
/*...other code here */
new CallableByAB().methodB();
/*...other code here */
}
other classes cannot call new CallableByAB() or import it. hence, safety.
This seems like a very brittle solution to a problem you should not need to solve.
In this particular case you may not suffer too greatly in future maintenance, just a couple of methods with these kind of special guards. But imagine trying to apply such logic to many methods across a large code base - it's just not a tenable thing to do. Even in your case you are effectivley writing code that cannot be reused in other contexts.
The fact that you need to do this surely reflects some kind of mis-design.
I infer that you have some kind of stateful interface whose state gets fouled up if called unexpectedly. Ideally I would want to make the interface more robust, but if that just cannot be done: If there are particular methods that should use this interface can you move those methods to a specific class - maybe an inner class of the current objtec you have - and have a handle visible only in this class?
private Class TheLegalCaller {
private RestrictedCallee myCallee = new RestricatedCallee() ; // or other creation
public void doOneThing() { myCallee.doOne(); }
public void doOtherThing() } myCallee.doOther(); }
}
Now the downside with this is that it only pushes the problem up a level, if you randomly use TheLegalCaller in the wrong places then I guess you still have an issue. But maybe by making the restriction very visible it aids your memory?
Try using access rules.
http://groups.google.com/group/google-web-toolkit/browse_thread/thread/90c424dc44db523e
I found a very simple way to do that, but requires some coding methodology:
class AllowedCaller {
private Object key;
public boolean getKey(){
return key;
}
public void allowedCallingMethod(RestrictedAccessClass rac){
this.key = rac;
rac.restrictedMethod();
this.key = null;
}
}
class RestrictedAccessClass{
public void restrictedMethod(){
if(allowedCallerInstance.getKey() != this){
throw new NullPointerException("forbidden!");
}
// do restricted stuff
}
}
I think it could be improved to prevent multithread simultaneous access to restrictedMethod().
Also, the key could be on another class other than AllowedCaller (so RestrictedAccessClass would not need to know about AllowedClass), and such control could be centralized, so instead of a single key, it could be an ArrayList with several object keys allowed at the same time.

Use of private constructor to prevent instantiation of class?

Right now I'm thinking about adding a private constructor to a class that only holds some String constants.
public class MyStrings {
// I want to add this:
private MyString() {}
public static final String ONE = "something";
public static final String TWO = "another";
...
}
Is there any performance or memory overhead if I add a private constructor to this class to prevent someone to instantiate it?
Do you think it's necessary at all or that private constructors for this purpose are a waste of time and code clutter?
UPDATE
I'm going for a final class with private constructor and a descriptive javadoc for the class. I can't use a ENUM (which I'd prefer) because I'm stuck on Java 1.4 for now. This would be my modification:
/**
* Only for static access, do not instantiate this class.
*/
public final class MyStrings {
private MyString() {}
public static final String ONE = "something";
public static final String TWO = "another";
...
}
Use of private constructor to prevent instantiation of class?
There are several ways you can think of users preventing from the Instantiations for the purpose of creating the Constants
As you have mentioned a class with the private Constructors and has all the string constants, is one way, even there is an overhead, that can be negligible
Else you can create a Class with Final Modifier and Define your string constants
You can use the Abstract Class with the String Constants
You can define the string constants in the properties files and can access from that, this will definitely reduce the memory and increase the flexibility of your code.
For me the best explanation is in Effective Java book: Item 4: Enforce noninstantiability with a private constructor (See more)
In Summary:
Private constructor is due utility classes were not designed to be instantiated, so is a design decision. (NO performance or memory overhead)
Making a class abstract doesn't work because can be subclassed and then instantiated.
With an abstract class the user may think the class is for inheritance.
The only way to ensure no instantiation is to add a private constructor which ensures the default constructor is not generated.
Private constructor prevents inheritance because the super constructor cannot be called (so it is not need the declare the class as final)
Throw an error in the private constructor avoids call it within the class.
Definetively, the best way would be something like next:
public class MyStrings {
private MyStrings () {
throw new AssertionError();
}
...
}
You could add a private constructor, but there are two other options.
In the same situation I would use an enumerator. If it makes sense to your implementation, you could use that instead, if it's public or private depends on where you need to use it:
public enum MyStrings {
ONE ("something"),
TWO ("something else");
private String value;
private MyStrings(String str) {
this.value = str;
}
}
Another option would be to put it in an abstract class, those can not be instantiated:
public abstract MyStrings {
public static final String STUFF = "stuff";
public static final String OTHER = "other stuff";
}
Access for both enumerator and abstract class works just like with the implementation you presented:
MyStrings.STUFF
If you don't won't anyone to make an object of the class you could make it abstract like this
public abstract class MyStrings {
public static final String ONE = "something";
public static final String TWO = "another";
}
and access your static variables like this
String val1 = MyStrings.ONE;
String val2 = MyStrings.TWO;
I think this would be a nicer solution.
I would rather use an enum to hold that Strings. This would ensure that wherever you use that Strings, you only get passed in one of the allowed Strings.
There is no performance or memory overhead if you add a private constructor in this case. As well, it is not needed since your public static variables are shared among all instances of your object.
If your class has only static members, then there is no need to have a private or public constructor. All members are accessible even without an object. In fact I find it confusing to have a constructor in such a case.
A synthetic public constructor would have been generated any way. So no.
Really a few bytes out of hundreds of millions at runtime isn't going to make much difference.
I also suggest making the class final and just for completeness have the constructor throw an exception.
If you want terse source code, you could create an enum with no values. Might cause some confusion with beginner programmers though.
That's the right way to store some constants, as also suggested in Effective Java (2nd Ed.), item 19.

Categories