Private method invoking conventions - java

I just recently started learning Java. I have a question which is more about conventions used in Java...
So suppose I have class A:
public class A {
public void methodA{
methodB();
}
private void methodB{
}
}
Sometimes I see some people calling private methods inside the class using this (e.g. this.methodB(); ) even if there is no ambiguity. Is it convention to explicitly show people that they are invoking private method or is it just someone's 'style'.

In and of itself, using this does not clarify much. It can point to:
An instance field (or method) or an inner class of this, whatever its visibility.
A static field or method or a nested class, of one of the classes inherited by this's class. (there is usually a warning in that case, but it is only a warning).
What it does prevent is:
static imports
local variables
class imports (if you have a nested class with the same name as an imported class)
I'll emphasize that it does not guarantee at all that the method called is private.
It is the first time I hear of this rule - I suspect that, at most, it is a (not that helpful) style rule of a company.

That's just style. Personally, I somehow like being overly explicit when accessing members, but I can also understand that people find it ugly, particularly if you're using methods or properties of the outer class from an inner class:
public class Outer {
private SomeType member;
private class Inner {
public void innerMethod() {
Outer.this.member.someFunction();
}
}
}
It may help in rare cases where you introduce a name shadowing problem later without noticing - all of a sudden you're calling the wrong function or accessing the wrong variable. Still, qualifying with this is verbose, and it's not a general rule.

Slightly off-topic in that we're not addressing a private method, rather a private class variable, but it's worth mentioning that sometimes this is necessary to prevent ambiguity:
public class Example {
private RowMapper rowMapper;
public void setRowMapper(RowMapper rowMapper) {
this.rowMapper = rowMapper;
}
}
On the whole, where there is no ambiguity then this is redundant syntax.

Related

`public` modifier in package-private classes

Recently, I was writing a class that I decided to be package-private (that is, no access modifier, or the default one). It has an inner class and some private helper methods, and one method intended to be used by a class in the same package. All of these class members are static. But then I had a thought: should this one method have the public access modifier or no access modifier, like the class containing it?
On one hand, since the class itself is package-private, it can only be accessed and used within its package, so there is no practical reason to make the method public. But at the same time, semantically, this method is intended to be a public feature of the class, that is, a feature of the class intended to be used externally, so it would make sense to modify its access as such.
For those that like to see code,
final class DummyRemover {
private DummyRemover() {
}
public static int remove(Map<String, ClassNode> classMap) {
return 0;
}
// ...
}
or,
final class DummyRemover {
private DummyRemover() {
}
// Notice the modifier.
static int remove(Map<String, ClassNode> classMap) {
return 0;
}
// ...
}
What is the best choice here? Is there a rule of thumb for deciding what access modifiers to use in a case like this?
There are two reasons why a method should have a higher visibility than its enclosing class:
1. The enclosing class is a base class
... which is intended for extension by subclasses, which might eventually be public, and the method at hand is supposed to be publicly available. E.g.
abstract class Base {
public void x() {}
}
public class Sub extends Base {
}
// Now, everyone can call:
new Sub().x();
usually, however, if this is your intention, you will declare your method x() in an interface anyway. Even if you don't declare x() in an interface, design-wise, it's probably better to keep the base method at the same visibility level as its class, and "open up" the method in the subclass, as that will communicate intent more clearly:
abstract class Base {
void x() {}
}
public class Sub extends Base {
/** public Javadoc here */
#Override
public void x() {
super.x();
}
}
I don't see any reason why this approach should be applied to static methods as in your case.
2. The method must be public
... because it implements a method from an interface. Unfortunately, Java doesn't offer package-private or private interface methods. So the following is usual, even without any subclasses, and even if the interface itself might be package-private (or even nested private):
final class Y implements X {
#Override
public void x() {}
}
This (unfortunately) also applies to static classes on interfaces, which can only be public:
interface I {
/* implicitly public */ static void x() {}
}
There are two schools of thought on this:
One group prefers adding unnecessary modifiers (e.g. public in this case, private in private classes) as a form of "documentation in code". For example, this is the viewpoint Eric Lippert espouses in his answer on this related C# question.
The other group prefers to never add source code that has no functional effect: if public isn't doing anything then it doesn't belong in your source code.
I think I am now firmly in the second camp, but I understand the arguments from the first camp and I think it's not nearly as cut and dried as it might first appear. Reasonable people can disagree, which is why (like braces and whitespace) this is something you should decide once in a project style guide and then never debate again. :-)
I personally think that making the method public might be misleading to the reader.
On the other hand, it supports extensibility (If the class should ever be made public, the change is easier).
Whenever I need to choose between readability and extensibility, I go for the YAGNI principle and choose readability.
See wiki for more about YAGNI: https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it

Java final abstract class

I have a quite simple question:
I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to have everything important within one separate class)...
This class should neither be instantiated, nor being extended. That made me write:
final abstract class MyClass {
static void myMethod() {
...
}
... // More private methods and fields...
}
(though I knew, it is forbidden).
I also know, that I can make this class solely final and override the standard constructor while making it private.
But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...
And I hate workarounds. So just for my own interest: Is there another, better way?
You can't get much simpler than using an enum with no instances.
public enum MyLib {;
public static void myHelperMethod() { }
}
This class is final, with explicitly no instances and a private constructor.
This is detected by the compiler rather than as a runtime error. (unlike throwing an exception)
Reference: Effective Java 2nd Edition Item 4 "Enforce noninstantiability with a private constructor"
public final class MyClass { //final not required but clearly states intention
//private default constructor ==> can't be instantiated
//side effect: class is final because it can't be subclassed:
//super() can't be called from subclasses
private MyClass() {
throw new AssertionError()
}
//...
public static void doSomething() {}
}
No, what you should do is create a private empty constructor that throws an exception in it's body. Java is an Object-Oriented language and a class that is never to be instantiated is itself a work-around! :)
final class MyLib{
private MyLib(){
throw new IllegalStateException( "Do not instantiate this class." );
}
// static methods go here
}
No, abstract classes are meant to be extended. Use private constructor, it is not a workaround - it is the way to do it!
Declare the constructor of the class to be private. That ensure noninstantiability and prevents subclassing.
The suggestions of assylias (all Java versions) and Peter Lawrey (>= Java5) are the standard way to go in this case.
However I'd like to bring to your attention that preventing a extension of a static utility class is a very final decision that may come to haunt you later, when you find that you have related functionality in a different project and you'd in fact want to extend it.
I suggest the following:
public abstract MyClass {
protected MyClass() {
}
abstract void noInstancesPlease();
void myMethod() {
...
}
... // More private methods and fields...
}
This goes against established practice since it allows extension of the class when needed, it still prevents accidental instantiation (you can't even create an anonymous subclass instance without getting a very clear compiler error).
It always pisses me that the JDK's utility classes (eg. java.util.Arrays) were in fact made final. If you want to have you own Arrays class with methods for lets say comparison, you can't, you have to make a separate class. This will distribute functionality that (IMO) belongs together and should be available through one class. That leaves you either with wildly distributed utility methods, or you'd have to duplicate every one of the methods to your own class.
I recommend to never make such utility classes final. The advantages do not outweight the disadvantages in my opinion.
You can't mark a class as both abstract and final. They have nearly opposite
meanings. An abstract class must be subclassed, whereas a final class must not be
subclassed. If you see this combination of abstract and final modifiers, used for a class or method declaration, the code will not compile.
This is very simple explanation in plain English.An abstract class cannot be instantiated and can only be extended.A final class cannot be extended.Now if you create an abstract class as a final class, how do you think you're gonna ever use that class, and what is,in reality, the rationale to put yourself in such a trap in the first place?
Check this Reference Site..
Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.
Thanks..

Is it a good or bad practice to call instance methods from a java constructor?

There are several different ways I can initialize complex objects (with injected dependencies and required set-up of injected members), are all seem reasonable, but have various advantages and disadvantages. I'll give a concrete example:
final class MyClass {
private final Dependency dependency;
#Inject public MyClass(Dependency dependency) {
this.dependency = dependency;
dependency.addHandler(new Handler() {
#Override void handle(int foo) { MyClass.this.doSomething(foo); }
});
doSomething(0);
}
private void doSomething(int foo) { dependency.doSomethingElse(foo+1); }
}
As you can see, the constructor does 3 things, including calling an instance method. I've been told that calling instance methods from a constructor is unsafe because it circumvents the compiler's checks for uninitialized members. I.e. I could have called doSomething(0) before setting this.dependency, which would have compiled but not worked. What is the best way to refactor this?
Make doSomething static and pass in the dependency explicitly? In my actual case I have three instance methods and three member fields that all depend on one another, so this seems like a lot of extra boilerplate to make all three of these static.
Move the addHandler and doSomething into an #Inject public void init() method. While use with Guice will be transparent, it requires any manual construction to be sure to call init() or else the object won't be fully-functional if someone forgets. Also, this exposes more of the API, both of which seem like bad ideas.
Wrap a nested class to keep the dependency to make sure it behaves properly without exposing additional API:class DependencyManager {
private final Dependency dependency;
public DependecyManager(Dependency dependency) { ... }
public doSomething(int foo) { ... }
}
#Inject public MyClass(Dependency dependency) {
DependencyManager manager = new DependencyManager(dependency);
manager.doSomething(0);
}
This pulls instance methods out of all constructors, but generates an extra layer of classes, and when I already had inner and anonymous classes (e.g. that handler) it can become confusing - when I tried this I was told to move the DependencyManager to a separate file, which is also distasteful because it's now multiple files to do a single thing.
So what is the preferred way to deal with this sort of situation?
Josh Bloch in Effective Java recommends using a static factory method, although I can't find any argument for cases like this. There is, however, a similar case in Java Concurrency in Practice, specifically meant to prevent leaking out a reference to this from the constructor. Applied to this case, it would look like:
final class MyClass {
private final Dependency dependency;
private MyClass(Dependency dependency) {
this.dependency = dependency;
}
public static createInstance(Dependency dependency) {
MyClass instance = new MyClass(dependency);
dependency.addHandler(new Handler() {
#Override void handle(int foo) { instance.doSomething(foo); }
});
instance.doSomething(0);
return instance;
}
...
}
However, this may not work well with the DI annotation you use.
It also messes badly with inheritance. If your constructor is being called in the chain to instantiate a subclass of your class, you may call a method which is overridden in the subclass and relies on an invariant that is not established until the subclass constructor has been run.
You'd want to be careful about using instance methods from within the constructor, as the class has not been fully constructed yet. If a called method uses a member that has not yet been initialized, well, bad things will happen.
You could use a static method that takes the dependency and constructs and return a new instance, and mark the constructor Friend. I'm not sure Friend exists in java though (is it package protected.) This might not be the best way though. You could also use another class that is a Factory for creating MyClass.
Edit: Wow another posted just suggested this same exact thing. Looks like you can make constructors private in Java. You can't do that in VB.NET (not sure about C#)... very cool...
Yeah, it's actually illegal, It really shouldn't even compile (but I believe it does)
Consider the builder pattern instead (and lean towards immutable which in builder pattern terms means that you can't call any setter twice and can't call any setter after the object has been "used"--calling a setter at that point should probably throw a runtime exception).
You can find the slides by Joshua Bloch on the (new) Builder pattern in a slide presentation called "Effective Java Reloaded: This Time It's for Real", for example here:
http://docs.huihoo.com/javaone/2007/java-se/

Private Member Access Java

Is the private member access at the class level or at the object level. If it is at the object level, then the following code should not compile
class PrivateMember {
private int i;
public PrivateMember() {
i = 2;
}
public void printI() {
System.out.println("i is: "+i);
}
public void messWithI(PrivateMember t) {
t.i *= 2;
}
public static void main (String args[]) {
PrivateMember sub = new PrivateMember();
PrivateMember obj = new PrivateMember();
obj.printI();
sub.messWithI(obj);
obj.printI();
}
}
Please clarify if accessing the member i of obj within the messWithI() method of sub is valid
As DevSolar has said, it's at the (top level) class level.
From section 6.6 of the Java Language Specification:
Otherwise, if the member or
constructor is declared private, then
access is permitted if and only if it
occurs within the body of the top
level class (ยง7.6) that encloses the
declaration of the member or
constructor.
Note that there's no indication that it's restricted to members for a particular object.
As of Java 7, the compiler no longer allows access to private members of type variables. So if the method had a signature like public <T extends PrivateMember> void messWithI(T t) then it would be a compiler error to access t.i. That wouldn't change your particular scenario, however.
Note that you don't even need source level access to mess with private fields. By using java.lang.reflect.AccessibleObject.setAccessibe(), all code can access all private members of all other code unless you specify a security policy that disallows it.
private is not by itself a security feature! It is merely a strong hint to other developers that something is an internal implementation detail that other parts on the code should not depend on.
Neither. Private access is scoped to the enclosing top-level class, so you can access private members of different class in the same top-level class:
class PrivateAccess {
static class InnerOne {
private int value;
}
static class InnerTwo {
int getOne ( InnerOne other ) {
return other.value;
}
}
}
The usual meaning of class access means that you have access to privates of other instances of the same type. In Java, private access is determined lexically, not by type.
Class level. The idea is that the code of a class (but nothing else) knows how to handle objects of that class.
If you have access to the class source code anyway, there is little sense in "hiding" anything from you.
As others have stated, private, default access ("package private"), protected and perhaps in JDK 7 module are class based (there are very strange rules for nested classes inheritance that I can't remember). But why?
Primarily it's down to methods that act as binary (or more) operators. For efficient implementation they often require or are easier to write without having to use or modify the public API. Have a look through at implementations of equals - in good code you'll find direct access of fields with few method calls to this. (The performance aspect of this is now mostly irrelevant with modern JVMs inlining common calls, but the code quality issue is still there.)
Just to add to DevSolar's answer, I would expect messWithI to be declared static as such:
public static void messWithI(PrivateMember t) {
t.i *= 2;
}
I had a hard time even reading what it is that you were trying to do without the 'static' hint... And it also makes it easier to answer your original question -- which is that private members are not limited in scope to just the instance in question.
The same page says, in sub-section 6.6.8, you can also find the following statement:
A private class member or constructor is accessible only within the body of the top level class that encloses the declaration of the member or constructor. It is not inherited by subclasses.
The private class member whose access we evaluate here is i.
public void messWithI() is a method that exists within the body of the top level class where i has been declared, which is, precisely, PrivateMember.
Your construct meets the statement above, and that is why it runs without problems.
Thas is another way to say the same as Jon and Devsolar.
Access modifiers for class members are related to where the code is written, (in which package, and in which class), regardless of what kind of member the access gets granted: a class member or an instance member.
Logically, you cannot use an instance member of a class if you do not have an instance of the class, but that is a different issue, related to the life-cycle of the member.

Should Helper/Utility Classes be abstract?

I commonly find myself extracting common behavior out of classes into helper/utility classes that contain nothing but a set of static methods. I've often wondered if I should be declaring these classes as abstract, since I can't really think of a valid reason to ever instantiate these?
What would the Pros and Cons be to declaring such a class as abstract.
public [abstract] class Utilities{
public static String getSomeData(){
return "someData";
}
public static void doSomethingToObject(Object arg0){
}
}
You could just declare a private constructor that does nothing.
The problem with declaring the class "abstract" is that the abstract keyword usually means that class is intended to be subclassed and extended. That's definitely not what you want here.
Don't bother making them abstract, but include a private parameterless constructor to prevent them from ever being instantiated.
Point of comparison for those interested: in C# you would declare the class to be static, making it abstract and sealed (Java's final) in the compiled form, and without any instance constructor at all. That also makes it a compile-time error to declare a parameter, variable, array etc of that type. Handy.
I don't declare utility classes abstract, I declare them final and make the constructor private. That way they can't be subclassed and they can't be instantiated.
public final class Utility
{
private Utility(){}
public static void doSomethingUseful()
{
...
}
}
I would add more step beyond the private constructor:
public class Foo {
// non-instantiable class
private Foo() { throw new AssertionError(); }
}
Throwing the AssertionError prevents methods in the same class from instantiating the class (well, they can try). This isn't normally a problem but in a team environment you never know what someone will do.
As regards the "abstract" keyword, I have noticed utilities classes subclassed in numerous instances:
public class CoreUtils { ... }
public class WebUtils extends CoreUtils { ... }
public class Foo { ... WebUtils.someMethodInCoreUtils() ... }
I believe this is done so that people don't have to remember which utility class to include. Are there any downsides to this? Is this an anti-pattern?
Regards,
LES
By declaring them as abstract, you are in effect indicating to other coders that you intended for these classes to be derived from. Really, you're right, that there's not much difference, but the semantics here are really more about the interpretation of other people who look at your code.
As others stated, make a private parameter-less constructor. No-one can create an instance of it, apart from the class itself.
As others have shown how it is done with other languages, here comes how you do it in the next C++ version, how to make a class non-instantiable:
struct Utility {
static void doSomething() { /* ... */ }
Utility() = delete;
};
I think it's better to declare utility classes final with a private no-args constructor. Moreover all members of this class should be static.
An easy way to do all this in one statement is to use the #UtilityClass annotation of Lombok:
#UtilityClass
public class Utilities{
public String getSomeData() {
return "someData";
}
public void doSomethingToObject(Object arg0) {
}
}
If you use the #UtilityClass annotation you can skip the static keywords as in the example above since Lombok adds them automatically during compilation.
No, but if your language supports it, there's a strong argument to be made that in most cases they should (can) be declared as 'static'... Static tells the compiler that they cannot be instantiated, and that all methods in them must be static.
Abstract is for classes that DO have instance-based implementation details, which WILL be used by instances of derived classes...
someone mentioned that in C# 3.0 you could accomplish this via extension methods. I'm not a C# guy, did some back in the 1.5/2.0 days, but have not used it since then. Based on a very cursory understanding I think something similar can be accomplished in java with static imports. I realize its not at all the same thing, but if the goal is to just make these utility methods seem a bit more "native"(for lack of a better term) to the calling class, I think it will do the trick. Assuming the Utilities class I declared in my original question.
import static Utilities.getSomeData;
public class Consumer {
public void doSomething(){
String data = getSomeData();
}
}
Might I offer some constructive advice?
If you are doing a lot of this, there are two problems you will run into.
First of all, a static method that takes a parameter should often be a part of the object that is that parameter. I realize this doesn't help for objects like String, but if it takes objects you've defined, you could almost certainly improve the object by including your helper as a method of that object.
If it takes all native values, you probably could define an object that it's a method of. See if you can find any grouping of those native values and group them as an object. If you just try that, you'll find a lot of other uses for that little mini-object, and before you know it it will be amazingly useful.
Another thing, if you have a utility class with a bunch of semi-related static methods and static variables, you almost always want it to be a singleton. I found this out by trial and error, but when you find out you need more than 1 (eventually you will), it's MUCH easier to make a singleton into a multipleton(?) then to try to change a static class into a multipleton(okay, so I'm making words up now).
Good luck. This stuff was mostly trial and error for me--figured it out like 5 years ago though, and I've never found an instance where I regretted not having static class/methods.
Helper / Utility methods are just fine. Don't worry about adding them to a library inside your application or Framework. Most frameworks that I have seen use them in many varieties.
That being said, if you want to get really crafty about them you should look into extension methods in C# 3.0. Using extension method will make your Utilities a little more of a "holistic" part of your framework which it seems like what you're trying to do by considering to make them abstract. Not to mention extension method are a lot of fun to write!

Categories