I read that there is no package-private (default in Java) in scala and use public access by default.
What are the rationale for this choice? Is it a good practice as the default public access make everything visible, hence part of the API?
This means extra typing to encapsulate the fields and methods (whether it be private, scoped private, protected, access).
In Java it’s far easier to choose ‘package-private’ as the default because it is one out of only three possibilities there.
In Scala you can choose between public access (public), package-private access with inheritance (protected[C]), package-private access without inheritance (private[C]), class-private access (private), object-private access (private[this]), inheritance access (protected), protected[this] access (whatever you may call it) and, additionally, you have some kind of file-private access modifier (sealed).
It’s hard to select a default from that other than public.
(Considering inner methods, one could also add method-private to the list…)
Scala has far more flexibility in choosing the visibility of something than Java, though some of Java visibility rules, related to nested classes are not translatable into Scala.
And, yes, there is package-private in Scala. It is written as private[package] in Scala.
The reason why Scala makes public the default is because it is the most common visibility used. The "extra typing" is actually less typing, because it is far more uncommon to make members private or protected.
One exception to that rule in Java is fields, which should be made private so one may be able to change details of implementation without breaking clients. One practical consequence of this are classes with fields and then getters and setters for each field.
In Scala, because one may be able to replace a val or a var with corresponding def, this is not needed.
This is something that gives a lot of people some trouble. I'd suggest giving this entry (actually the entire series) a read.
Immutability also prevents any of the funnies that generally occur with such access. It might be true that "there is more typing", but looking at IDEs, they are responsible for a lot of fud as any generated method by the IDE is usually public, which is not always valid either.
According to Programming Scala, it seems like the default public is mainly due to the uniform access principle, where operator overloading allow one to define the getter as field = newvalue
Related
Say I am using a Java library that has the following method
public static SomeInterface foo();
The interface SomeInterface has multiple implementations, some of which are protected within the library's package. One of these implementation is TheProtectedClass
What would be the best way to check if the object returned by foo() is an instance of TheProtectedClass?
My current plan is to create an Utils class that lives within my project but in the same package as the protected class. This Utils can refer to TheProtectedClass since it is in the same package and thus it can check if an object is instanceof TheProtectedClass.
Any other ideas?
EDIT: Some people are asking "why" so here is more context.
I am using jOOQ and in some part of my code, I want to know if the Field instance that I have is an instance of Lower.
Currently, I use field.getName().equals("lower") but this isn't as robust as I'd like it to be.
I realize that since Lower is a protected class, it isn't part of the API and that it can change but I am ok with that.
Class.forName("TheProtectedClass").isAssignableFrom(foo())
although it is a bad idea for many reasons. You're breaking the encapsulation and the abstraction here. If it's package-private, you shouldn't have to concern with it outside. If it's protected, you should explicitly inherit from it and use the API provided by class for this case.
The less obvious but more correct solution is to get an instance of TheProtectedClass, and compare it by
guaranteedTPCInstance.getClass().isAssignableFrom(foo())
, while still being kind of hacky, at least is more portable and OOPy IMO.
As to your idea of creating a class in the same package as TheProtectedClass to avoid being package-private - it's a viable solution, but a) it breaks the basic principle of encapsulation and the programming contract of the TPC class; packaging is done by library/class authors for a reason - to prevent irresponsible data access and using private API or undocumented proprietary methods, b) it's not always possible (and shouldn't be possible in case of properly designed library classes), since those classes can be not only package-private, but final or effectively final (anonymous inner classes etc) - for the reasons described by Bloch in EJ 2nd, "favor composition over inheritance" item, see also Good reasons to prohibit inheritance in Java? Use of final class in Java etc c) you can't do it with some Java library classes, as you can't define your class to be and use e.g. java.lang package. As such, the only "portable" solution is through reflection and through what I described.
tl;dr The fact you can piggyback another package by mimicking its package definition is an obvious C-style deficiency of Java's syntax (allowing programmer to do what he shouldn't be able to normally do; same goes with some specific reflection methods); hacks made this way are neither maintainable nor safe.
NOTE: If you you expect to do something in a internal implementation-dependent and, at the same time, portable and maintainable (e.g. impervious to implementation changes/class name changes etc) way, you're obviously expecting the impossible.
It appears that the best solution is to create a package in your project that has the same package as the package-private class and either expose TheProtectedClass.class as a Class<?> or simply add a simple method that checks if your Object is instanceof TheProtectedClass.
This does not require reflection, it is fast and relatively safe (compilation will break if the package-private class changes name).
I have a main class that has a thread pool, which is used by quite a few other classes for performing actions on a database. I currently have a getter method to get the pool which works fine but seems a bit clumsy.
Are there any circumstances where it is acceptable to use a public field instead of getter/setter methods?
Are there any circumstances where it is acceptable to use a public field instead of getter/setter methods?
The main reason that public fields are bad are that they expose the implementation to the outside world. That leads to unwanted coupling; i.e. classes that are overly dependent on the implementation details of other classes. That tends to make code harder to understand and harder to change. And if the field is not final, you need to search the entire code-base to be sure that nothing is "interfering" with the field. (OK, IDE's make this easier ... but contrast a public field with a private field that has no setter.)
A secondary reason is that you cannot override a field. Once you have exposed a field in a superclass, there is nothing you can do in a subclass can do to modify or restrict its meaning. (By contrast, getters and setters can be overridden ...)
The only situation where it is acceptable (from a stylistic perspective) to have "public" fields is when the class which declares the fields is a private nested or inner class. The consequence is that all dependencies on the field are restricted to the source file that contains the declaration ... which negates the problems above.
UPDATE - I forgot public static final ... but we tend not to think of those as fields at all. Anyway, it is normal practice to access public static final fields directly. The idea of a constant is to deliberately expose the name, type and value ... and the override issue doesn't apply because of the nature of static fields.
I currently have a getter method to get the pool which works fine but seems a bit clumsy.
"Clumsy" is a matter of opinion / taste. Personally, I don't think that obj.getInstance() is clumsy compared with obj.instance. It is just the Java way1.
The flipside is that if you didn't have a getInstance() method, all of the classes that used the pool would have to have hard-coded references to the instance field. If (for some reasons) you needed to change something about the way the pool was accessed (e.g. add a security check, add a counter, make pool creation lazy, make sure that access is properly synchronized), then you have to change each and every place where you have coded reference to the field. But with a getter, you just have one place to change.
1 - Obviously, other languages do this differently. But you are not writing those languages. Java is what it is.
There are many reasons for using getter & setter instead of a public field. One I've found in SO is
Because 2 weeks (months, years) from now when you realize that your
setter needs to do more than just set the value, you'll also realize
that the property has been used directly in 238 other classes :-)
You can also have a look at this post, which also quotes that i've give above and provides a few other examples. Read and then you can decide whether to use a public field in your case.
Keeping your class fields private and using getter/setter methods provides a layer of abstraction and makes it easier to maintain in the long run. See this: What's the deal with Java's public fields?
As everybody knows, Java follows the paradigms of object orientation, where data encapsulation says, that fields (attributes) of an object should be hidden for the outer world and only accessed via methods or that methods are the only interface of the class for the outer world. So why is it possible to declare a field in Java as public, which would be against the data encapsulation paradigm?
I think it's possible because every rule has its exception, every best practice can be overridden in certain cases.
For example, I often expose public static final data members as public (e.g., constants). I don't think it's harmful.
I'll point out that this situation is true in other languages besides Java: C++, C#, etc.
Languages need not always protect us from ourselves.
In Oli's example, what's the harm if I write it this way?
public class Point {
public final int x;
public final int y;
public Point(int p, int q) {
this.x = p;
this.y = q;
}
}
It's immutable and thread safe. The data members might be public, but you can't hurt them.
Besides, it's a dirty little secret that "private" isn't really private in Java. You can always use reflection to get around it.
So relax. It's not so bad.
For flexibility. It would be a massive pain if I wasn't able to write:
class Point {
public int x;
public int y;
}
There is precious little advantage to hide this behind getters and setters.
Because rigid "data encapsulation" is not the only paradigm, nor a mandatory feature of object orientation.
And, more to the point, if one has a data attribute that has a public setter method and a public getter method, and the methods do nothing other than actually set/get the attribute, what's the point of keeping it private?
Not all classes follow the encapsulation paradigm (e.g. factory classes). To me, this increases flexibility. And anyway, it's the responsibility of the programmer, not the language, to scope appropriately.
Object Oriented design has no requirement of encapsulation. That is a best practice in languages like Java that has far more to do with the language's design than OO.
It is only a best practice to always encapsulate in Java for one simple reason. If you don't encapsulate, you can't later encapsulate without changing an object's signature. For instance, if your employee has a name, and you make it public, it is employee.name. If you later want to encapsulate it, you end up with employee.getName() and employee.setName(). this will of course break any code using your Employee class. Thus, in Java it is best practice to encapsulate everything, so that you never have to change an object's signature.
Some other OO languages (ActionScript3, C#, etc) support true properties, where adding a getter/setter does not affect the signature. In this case, if you have a getter or setter, it replaces the public property with the same signature, so you can easily switch back and forth without breaking code. In these languages, the practice of always encapsulating is no longer necessary.
Discussing good side of public variables... Like it... :)
There can be many reasons to use public variables. Let's check them one by one:
Performance
Although rare, there will be some situations in which it matters. The overhead of method call will have to be avoided in some cases.
Constants
We may use public variables for constants, which cannot be changed after it is initialized in constructor. It helps performance too. Sometimes these may be static constants, like connection string to the database. For example,
public static final String ACCEPTABLE_PUBLIC = "Acceptable public variable";
Other Cases
There are some cases when public makes no difference or having a getter and setter is unnecessary. A good example with Point is already written as answer.
Java is a branch from the C style-syntax languages. Those languages supported structs which were fixed offset aliases for a block of memory that was generally determined to be considered "one item". In other words, data structures were implemented with structs.
While using a struct directly violates the encapsulation goals of Object Oriented Programming, when Java was first released most people were far more competent in Iterative (procedural) programming. By exposing members as public you can effectively use a Java class the same way you might use a C struct even though the underlying implementations of the two envrionments were drastically different.
There are some scenarios where you can even do this with proper encapsulation. For example, many data structure consist of nodes of two or more pointers, one to point to the "contained" data, and one or more to point to the "other" connections to the rest of the data structure. In such a case, you might create a private class that has not visibility outside of the "data structure" class (like an inner class) and since all of your code to walk the structure is contained within the same .java file, you might remove the .getNext() methods of the inner class as a performance optimization.
To use public or not really depends on whether there is an invariant to maintain. For example, a pure data object does not restrict state transition in any fashion, so it does not make sense to encapsulate the members with a bunch of accessors that offer no more functionality that exposing the data member as public.
If you have both a getter and setter for a particular non-private data member that provides no more functionality than getting and setting, then you might want to reevaluate your design or make the member public.
I believe data encapsulation is offered more like an add-on feature and not a compulsory requirement or rule, so the coder is given the freedom to use his/her wisdom to apply the features and tweak them as per their needs.Hence, flexible it is!
A related example can be one given by #Oli Charlesworth
Accesibility modifiers are an implementation of the concept of encapsulation in OO languages (I see this implementation as a way to relax this concept and allow some flexibility). There are pure OO languages that doesn't have accesibility modifiers i.e. Smalltalk. In this language all the state (instance variables) is private and all the methods are public, the only way you have to modify or query the state of an object is through its instance methods. The absence of accesibility modifiers for methods force the developers to adopt certain conventions, for instance, methods in a private protocol (protocols are a way to organize methods in a class) should not be used outside the class, but no construct of the language will enforce this, if you want to you can call those methods.
I'm just a beginner, but if public statement doesn't exists, the java development will be really complicated to understand. Because we use public, private and others statements to simplify the understanding of code, like jars that we use and others have created. That I wanna say is that we don't need to invent, we need to learn and carry on.
I hope apologize from my english, I'm trying to improve and I hope to write clearly in the future.
I really can't think of a good reason for not using getters and setters outside of laziness. Effective Java, which is widely regarded as one of the best java books ever, says to always use getters and setters.
If you don't need to hear about why you should always use getters and setters skip this paragraph. I disagree with the number 1 answer's example of a Point as a time to not use getters and setters. There are several issues with this. What if you needed to change the type of the number. For example, one time when I was experimenting with graphics I found that I frequently changed my mind as to weather I want to store the location in a java Shape or directly as an int like he demonstrated. If I didn't use getters and setters and I changed this I would have to change all the code that used the location. However, if I didn't I could just change the getter and setter.
Getters and setters are a pain in Java. In Scala you can create public data members and then getters and or setters later with out changing the API. This gives you the best of both worlds! Perhaps, Java will fix this one day.
This question already has answers here:
Is it in an anti-pattern to always use get and set methods to access a class's own member fields? [duplicate]
(11 answers)
Closed 9 years ago.
Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.
So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?
The most obvious answer is side effects:
int getCost()
{
if (cost == null) {
calculateCost();
}
return cost;
}
If you need the cost, use getCost(). If you want to see if cost has been calculated, use cost.
If there is any business logic around those values (or there is the potential for such logic), then there is a benefit to using getters and setters even for internal calls.
For example, your setter might do validation on its inputs, and throw an exception rather than store an invalid value. Having all your code use that setter rather than simply setting values directly means that the error is caught at the time it is made rather than a long time later when that value is used. A similar case for a getter is when there is a logical default value, which should be used in case of a null. By using a getter, you can safely write local methods without needing continuous null checks or default options.
That said, if there's no business logic in those methods, and no side effects caused by them, then it's mostly a stylistic thing. It is essentially the responsibility of the class to be internally consistent, and as long as it remains so then it's mostly personal/professional preference whether you access the variables directly or through wrapping methods.
You want to declare them as public getters and setters, and private fields. This means external classes (not subclasses) who want to modify the variables all do so through the setters, and get them through the getters. The benefit of this is that if you want to control how or what condition they get or set them, or want to add information or even print debug, it means you only have to put it in the getters and setters.
There's a really good explanation of the benefits on stackoverflow actually:
In Java, difference between default, public, protected, and private
Of course, only make methods when they're actually needed, and similarly, only public when needed by external classes.
Hope that helps the defense!
This is part of the general question as to why you use getters and setters. Many developers use them without though, as a matter of practice. Personally, I only put in getters/setters if I need to.
I would suggest you do what is clearest/simplest to you.
In general, if I can easily add a getter/setter later should I need it, I won't add it. If it would be difficult to add later (or you have an immediate use for them), I would include them.
Some of us are web developers so, we resort to creating JavaBeans and JavaBeans has its own specification. In the specification, it clearly states:
The class must have a public default constructor (no-argument).
The class properties must be accessible using get, set, is (used for boolean properties instead of get) and other methods.
The class should be serializable.
The reason being, JavaBeans were designed for Reusability where JavaBeans could travel through any Java technologies (e.g. Servlets, JSPs, RMI, Web Services, etc.).
That's my 2cent worth on why we have getters/setters. I mostly create JavaBeans.
Some people think that they should always encapsulate all fields by using setters/getters.
Others think that this practice should not be used at all.
If your class does not have any logic for the fields and just is used as a holder, you can skip using methods and just declare your fields as public. This concept is also called a Data Transfer Object (or Messenger.) But as a rule you should use final attribute for such fields to make your class immutable:
public class TwoTuple<A,B> {
public final A first;
public final B second;
public TwoTuple(A a, B b) { first = a; second = b; }
}
However you must/or it's strongly recommended to use setters/getters:
in web applications sometimes there are requirements to use setters/getters. See POJO/JavaBean objects.
if your class is going to be used in concurrent environment. See Java Concurrency in Practice, Section 3.2:
"Whether another thread actually does something with a published reference doesn't really matter, because the risk of misuse is still present.[7] Once an object escapes, you have to assume that another class or thread may, maliciously or carelessly, misuse it. This is a compelling reason to use encapsulation: it makes it practical to analyze programs for correctness and harder to violate design constraints accidentally"
if you want to add some extra logic when you set/get values you must use setters/getters. Just read about encapsulation and its advantages.
My own opinion always declare fields as "private final" and only then, if needed change these properties.
I have created an anonymous class in which I declare a few variables and methods. My java teacher tells me to make these private. I don't see how changing the modifier makes any difference since these variables and methods are private to the anonymous class anyway, so I prefer to have no modifier at all. Who is right and what makes more sense? See below for example code where I choose no modifier for 'map' and 'convert' rather than making them private.
Collections.sort(list, new Comparator<String>(){
public int compare(String a, String b){
return convert(a).compareTo(convert(b));
}
Map<String, String> map = new HashMap<String, String>();
String convert(String s) {
String u = map.get(s);
if (u == null)
map.put(s, u = s.toUpperCase());
return u;
}
});
I would be tempted to make them private simply for the fact that if you refactor the code and pull the anonymous class out as a standard class (Intellij, for example, can do this at the click of a button), having private fields is what you really want. You won't have to go and rework your classes to match your standard.
Personally I would make them private (and final where possible) anyway - it's just a good habit to be in in general.
To put it another way: if you had to put an access modifier on (if, say, the keyword package was also used as an access modifier) what would you choose? Private, presumably - after all, you don't actually want to grant any other class access, do you?
Now, having decided that private is the most logically appropriate access modifier, I would make that explicit in the code.
Then again, I'd quite possibly not create an anonymous inner class with a member variable anyway - I'd be tempted to turn that into a named nested class instead.
Your professor is right.
Make all class variable private and expose them via properties (if not anonymous).
The general rule of thumb is to keep member data such as variable including your Map object private.
Default modifier is not the same as the private modifier, there're subtle differences.
However, in your case it's more a religious question whether to make convert() default or private. I don't see any advantage in making it private though.
Anyway, your code has a memory leak as the String Cache is never cleared :-P
Also, for even shorter/less code, use the Comparator String.CASE_INSENSITIVE_ORDER:
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
It really doesn't matter, but it's probably a good idea to keep your teacher happy as he/she will be grading you.
I'd say it's a matter of style. You can't access the member map outside out of the anonymous class, but it might be best to define them as private for consistency with other classes.
If this were my code, I would say that if a class is complicated enough to need data members, it might be worth pulling it out into a separate class, in which case I'd certainly make the data members private.
The key point is when you say "I don't see how changing the modifier makes any difference since these variables and methods are private to the anonymous class anyway"... you're assuming a lot about how your class is going to be used. Treat every class like it will be passed around and used in a variety of ways, in other words, use modifiers as appropriate. Besides, it makes the intent of class clear. It's not like Java is a terse language anyway, so you might as well be clear.
I don't see much benefit to marking things private just for the hell of it. It won't really gain you anything and someone reading the code might attach some significance to the choice when there really isn't any.
I would question the need for all this complexity. Take a look at: String.compareToIgnoreCase()
You want these fields to be private, so mark them private.If a member is marked neither public not private then something suspicious is going on. Also mark fields that shouldn't change final. Keeping things standardised means less thinking, or at least less thinking on the irrelevant, and less to change when modifying code.
From a language point of view, the only real difference is that if you have extended a base class in the same package, you have now hidden fields or overridden "package-private" (default access) methods. The members can also be accessed via reflection (without setAccessible) by code in the same package (this can have mobile-code security implications).
difference between default and protected.
protected:
object/method is accessible to all classes that are in the same package, and also accessible to sub/extension classes.
default:
object/method is accessible to all classes that are in the same package.
What is your intention of your object/method and code modifier accordingly.
Do not allow yourself to be confused when you come back to the code after six months because in huge projects you want to know that that object/method is or is not accessed anywhere else.
In three weeks, not just months, you would forget what the intended accessibility of those objects, 101% guaranteed. Then if you had a huge project and you had a hundred modifiers that were not specific and you desperately wanted to update the code, you would be frustrated by the compulsion to run reference check on those 100 objects/methods. May be someone took your jar and found the hidden cookies in them and used them, then you changed your code and broke someone's code.
Code your modifiers according to your intention unless you are either one or more of these:
you have no further desire to work
in large java projects.
you are a
extremely intelligent high
functioning autistic person who has
an indexed memory of every event of
your life and can write a completely functional peer-peer file sharing service
within two weeks on a lap top in a
coffee shop.
you deliberately use it
as another tool to obfuscate your
code.