Accessing non-public methods through patterns - java

Which pattern can be used, or what is the way, if I have some classes where some of the interface are protected, but I want to use it outside the package and out of the hierarchy?
I don't want to change the access modifier of those old (legacy) classes.

The following code shows how to access such a field:
Field privateStringField = PrivateObject.class.
getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
The same thing could be done in a method as well. But as a pattern, you better pack it in a static utility method such as ReflectionAccessor.accessField(Class class, Object object, String fieldName).

If the part of the classes that you need access to is protected, you can access it via inheritance.
You may also be able to access the protected parts via those classes that do have access to the protected code.
A design pattern that can probably be used is Proxy.
In this case, the Proxy could inherit from the class you're interested in, and make the methods you're interested in available locally.
Before all this, however, consider carefully why these parts of the interface did not have public scope. There may have been good reasons not to expose them.

You can use a class Adapter. The Class adapter will derive from the Legacy classes and expose public interface methods which will internally call your protected methods. Your client will call the public methods of the class adapter which will internally call your legacy classes.

The whole point of a protected method is to make it inaccessible from the outside, and making methods protected is often some important point of a design pattern.
You want to break the encapsulation of the classes, and there is no design pattern that will help you do that. Only dirty reflection calls.

Faster than reflection, but equally dirty (or possibly more so): define a class in the same package as the legacy classes. Give it all the public methods you want. Have these public methods delegate to protected methods of the legacy classes.
I think I need to wash my hands after typing that.

Related

Java Abstract classes good practices

I am just now learning about Abstract classes in Java and I was wondering.
Would having package private fields be considered bad practices?
For example:
abstract class Parent {
String testField;
public void method() {
System.out.println(testField);
}
}
Then on the children class I would do
public final class Children extends Parent {
#Override
public void method() {
logger.log(testField);
}
}
In this example would it be bad practice?
Or should I make them private and instead use getters and setters for them like normally?
It depends on what you want to do. However, in many cases encapsulation or information hiding can be a useful principle. In your case, this would mean making the member variable protected or private and exposing it only through getters/setters or not at all. This yield some advantages:
You can change the implementation of your class (e.g. changing the type of testField) without breaking the code of other programmers
The code is more clear to other programmers as they only need to consider the public methods
It makes the code easier to test
It discourages feature envy and tight coupling
There's lots of advice. Prefer composition to inheritance. Prefer interfaces to base classes. Keep type hierarchies flat. Class should tend be either leaf (could be marked final) or abstract.
The most important practice here is avoiding protected. It's a mistake in the language. Also avoid default/package private access on anything but top level types.
In general (meaning exceptions are allowed under well defined circumstances), a field of a class should be private, and any access to it will require the use of a getter or a setter (or, more general, an 'accessor' or a 'mutator').
One (well known) exception is for static final fields of an immutable or primitive type – sometimes referred to as a constant.
When you can make sure (really sure) that your code is the only one that will access that field (for now and all overseeable future), you may consider to make it public (rarely), package private or protected. You will find this pattern quite often in classes from the java and javax packages; it works there because you cannot place your new classes to one of these packages, and therefore the code in your class cannot access the package private and protected fields – and because the (abstract) base classes in these packages that have protected fields are itself not public, inheritance would not help.
It will not work in most other cases (although things are changing since Jigsaw …), so you are limited to private internal classes in these cases.
Of course, when you write only disposable code, considerations like these are obsolete. Otherwise, you should always completely encapsulate all data, so that you/your code has complete control over any access/modification of it.
We can make methods protected in base abstract classes so that only sub classes override it.
protected void method() {
System.out.println(testField);
}

Is it mandatory utility class should be final and private constructor?

By making private constructor, we can avoid instantiating class from anywhere outside. and by making class final, no other class can extend it. Why is it necessary for Util class to have private constructor and final class ?
This is not a mandate from a functional point of view or java complication or runtime. However, it's a coding standard accepted by the wider community. Even most static code review tools, like checkstyle, check that such classes have this convention followed.
Why this convention is followed is already explained in other answers and even OP covered that, but I'd like to explain it a little further.
Mostly utility classes are a collection of methods/functions which are independent of an object instance. Those are kind of like aggregate functions as they depend only on parameters for return values and are not associated with class variables of the utility class. So, these functions/methods are mostly kept static. As a result, utility classes are, ideally, classes with only static methods. Therefore, any programmer calling these methods doesn't need to instantiate the class. However, some robo-coders (maybe with less experience or interest) will tend to create the object as they believe they need to before calling its method. To avoid that, we have 3 options:
Keep educating people to not instantiate it. (No sane person can keep doing it.)
Mark the utility class as abstract: Now robo-coders will not create the object. However, reviewers and the wider java community will argue that marking the class as abstract means you want someone to extend it. So, this is also not a good option.
Private constructor: Not protected because it'll allow a child class to instantiate the object.
Now, if someone wants to add a new method for some functionality to the utility class, they don't need to extend it: they can add a new method as each method is independent and has no chance of breaking other functionalities. So, no need to override it. Also, you are not going to instantiate it, so no need to subclass it. Better to mark it final.
In summary, instantiating a utility class (new MyUtilityClass()) does not make sense. Hence the constructors should be private. And you never want to override or extend it, so mark it final.
It's not necessary, but it is convenient. A utility class is just a namespace holder of related functions and is not meant to be instantiated or subclassed. So preventing instantiation and extension sends a correct message to the user of the class.
There is an important distinction between the Java Language, and the Java Runtime.
When the java class is compiled to bytecode, there is no concept of access restriction, public, package, protected, private are equivalent. It is always possible via reflection or bytecode manipulation to invoke the private constructor, so the jvm cannot rely on that ability.
final on the other hand, is something that persists through to the bytecode, and the guarantees it provides can be used by javac to generate more efficient bytecode, and by the jvm to generate more efficient machine instructions.
Most of the optimisations this enabled are no longer relevant, as the jvm now applies the same optimisations to all classes that are monomorphic at runtime—and these were always the most important.
By default this kind of class normally is used to aggregate functions who do different this, in that case we didn't need to create a new object

What is better: Interface or playing with public/protected?

I have a class with 5 methods. 3 of these methods just have to be opened by other classes in the same package and 2 have to be opened by other classes in an other package.
as example:
void setTimeArray(int[] zeitArray) {
this.timeArray = timeArray ;
}
public int[] getTimeArray() {
return timeArray ;
}
now I was wondering what I should make:
should I make the 3 methods protected and the 2 other public?
or
should I make an interface for the 2 methods?
so what would be cleaner and better for the performance of my application and why?
You seem confused about the use of public, protected, etc. The public methods in your class comprise the public interface of your class. When you design your class, you decide what functionality you want to expose to consumers of your class.
You should only make methods protected IMO for polymorphism. If you are making a method protected so that another class in the package can get at internals, etc., then it is probably a bad class design. You should not make a method protected just because no other classes are using it right now. If you need to use it from another class in the future, you'd have to change the class.
You shouldn't need to create an interface if there aren't multiple concrete classes implementing that interface.
The public interface of a class should flow pretty naturally if you get the OOP paradigm. The decisions should involve more about how to expose function than what to expose.
If there is a single "subject" that is common to the 2 methods but not to the other 3, consider splitting up the class into 2 different classes. If you do so, consider moving the class with the 2 methods to the package in which it will be used (if it makes sense in terms of the "subject" of that package).
In any case, use the lowest visibility that allows you to do what you wish to do.
Also, prefer default visibility to protected (the difference is that protected is like default, but also allows for subclasses in different packages to access those methods).
As the 3 methods of your class are access by the classes of the same package then no need to have a protected access modifier rather you can use default. protected should be used when you want your subclass to access the methods.
and about the public methods you can go for interface if you think you have a similar class which has these two methods implemented in it. so that through interface you can relate them.
You should write the interface as soon as you think, that you might use or need it ;)
In addition to the interface: keeping the non-interface methods protected is a valid solution for your problem.
Don't care about performance. Programming against interfaces or using access modifiers like public, protected or private has no performance impact.

What's meant by "Data Encapsulation"? Use private data fields or methods?

Say I have a ClassA and ClassB extends ClassA
ClassA {
private int x;
private void m1()
{
}
}
ClassB extends ClassA {
}
Under data encapsulation, we should private the data field and methods. Is that correct?
But, in this case, ClassB can not use ClassA's data field and methods.
So, under data encapsulation should I use private access modifiers only?
Can I use protected access modifier rather than private to solve the problem under the rule of data encapsulation?
Essentially, encapsulation is a way of making sure certain functions in a class are only ran by processes that are tested and known to work. If a function has no reason to be called by any object other than the ones you intend it to, why should it be given the ability to be seen and accidentally called?
It's really more a form of programmer controls, setting up rules and basic guidelines of proper code use, especially in an API scenario where you only want to expose certain functions or classes.
"Good practice" states you should be using 'private' for functions that do not interface with anything other than the class itself. For functions that need to interface with children classes, you can use protected. For all other interfacing between other classes, use public.
There is no rule that all methods need to be private.
Data encapsulation usually refers to hiding the details of implementation from client classes. It usually does not involve hiding all methods, since those are the public (or, in some cases, inherited) contract between the class and the client classes (and/or subclasses) of that class. Private methods are used usually as helpers to the public methods, and are kept private because their function—perhaps their very existence is based on details of implementation.
Sometimes certain details of the implementation are published for use by subclasses. That is the principal use of protected methods. The implementation data may sometimes also be exposed in this way, but that is—how shall I put this?—frowned upon. Nevertheless, there is a tradeoff here between strict adherence to the ideal of encapsulation and the practicalities of programming.

Single instance with methods in java

I am wondering about programming decision - which I think is matter of style.
I need to have single instance of class which has only methods and no attributes.
To obtain that in java I have two options:
create an abstract class with static methods within, thus it will not be possible to create any instance of the class and that is fine,
use a singleton pattern with public methods.
I tend to go for second approach although met with 1. Which and why is better of those, or there is third option.
Would it make sense for that singleton to implement an interface, allowing you to mock out those methods for test purposes?
I know it goes against testing dogma these days, but in certain situations I think a static method is fine. If it's the kind of behaviour which you're never going to want to fake for test purposes, and which is never going to be polymorphic with other implementations, I don't see much point in making a singleton. (Singletons are also generally the enemy of testability, although if you only directly refer to them in the injection part of your code, they can implement appropriate interfaces so their singletoneity never becomes a problem.)
It's worth mentioning that C# has "static classes" for this kind of situation - not only do they prohibit other code from deriving from or instantiating the class, but you can't even use it as a parameter. Basically it signals the intent very clearly.
I would definitely suggest at least having a private constructor to prevent instantiation by the outside world.
My personal view is that the class should contain a private constructor and NOT be abstract. Abstract suggest to a reader that there is a concrete version of the class somewhere, and they may waste time searching for it. I would also make sure you comment your code effectively.
public class myClass {
/** This class should never be instantiated. */
private myClass() {
}
public static void myMethod() {
}
...
//etc
...
}
For option #1, it may not even be that important to restrict instantiation of your static utility class. Since all it has is static methods and no state, there is no point - but neither harm - instantiating it. Similarly, static methods can't be overridden so it does not make sense - nor difference - if it is subclassed.
If it had any state, though - or if there is a chance that it will get stateful one day - it may be better to implement it as a normal class. Still I would prefer not to use it as a Singleton, rather to pass its sole instance around via dependency injection. This makes unit testing so much easier in the long run.
If it holds a state I would use the singleton pattern with private constructors so you can only instantiate from within the class. If it does not hold a state, like the apache commons utility classes, I would use the static methods.
I've never seen the problem with static methods. You can think of static methods as somehow breaking OO, but they make perfect sense if you think of static as a marker that something is stateless. You find this in the java apis in places like java.Math. If you're worried about subclassing you can always make it final.
There is a danger in that a class like that can end up as a "utility method garbage can", but as long as the functionality doesn't diverge too much then there's nothing wrong with it.
It's also clearer, as there's no need to manage an object lifecycle like you would with a singleton (and since there's no state, what's the point of that anyway?).
For a single instance, I suggest you have an enum, with one instance.
However, for a class with no attributes, you don't have to have an instance. You can use a utility class. You can use an enum, with no instances and only static methods. Note: this cannot be easily mocked out.
You can still implement an interface if you ever need to mock out the implementation in testing.

Categories

Resources