I have a class (Capsule) which has a lot of methods (30+) that are protected. The idea is to allow devs to extend this class and use the protected methods within the class (ImADev), but leave it up to the dev to expose them as public (Overriding the methods as they see fit).
I now have a use case where I want to pass these objects into a few Utility classes/methods and allow them to have access to the protected methods .. except they're protected, so my utility classes/services can't see them.
See the example below:
// My Capsule class with protected methods
public abstract class Capsule {
public Capsule(..) { .. }
protected String getFoo() { return "foo"; }
}
// How a dev should use the class
public class ImADev extends Capsule {
public ImADev(..) { super(..); }
public String getBar() { this.getFoo() + "BAR");
}
// A special utility class
// Helper.helper() can accept any class derived from Capsule
public class Helper {
public String helper(Capsule c) {
return " im doing something awesome with " + c.getFoo();
// Except i cant do this, because c.getFoo() is protected.
}
}
What's the best way around this? Keep in mind I have a lot of protected methods.
Either your class is doing too much, in which case break it up into smaller more well defined classes
Or, implement safe public methods that your utility class can call to wrap you protected methods
Or, just make them public because it sounds like they might/should be
Or, separate the data in the class from the behaviour (composition) then your utility class only has to deal with safer public getter methods an not the protected behaviour methods that can change the internals
A bit difficult to provide a better answer without knowing more about your application and it's use
There is no way 'around' this, except to put the utility class in the same package as the classes with the protected method. If those classes are in more then one package, that won't help.
In deciding to use protected, you made a decision, and now you are stuck with the implications. You can live with it, change to public, or change package membership to take advantage of default access.
I see at least two options.
Make Helper a subclass of Capsule. Or,
Turn your protected methods into default accessibility, and put the Helper class in the same package as the Capsule class.
Edit: You can also probably accomplish exactly what you want with reflection.
Actually there is a way to call protected methods from outside the package or subclass: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/AccessibleObject.html
I'm just kidding! This tool exists for technical stuff like serialization of persistance.
Declaring a method as "protected" is just a way to organise your code and define which part should deal which which data, so trying to get "around" is not a good idea, unless you mistakenly declared it protected. In this case correct the first mistake.
If you are interested in how to organize your code in an efficient and clear way, i highly recommend reading http://java.sun.com/docs/books/effective/
Related
I have some common methods for two classes and maybe for others in the future. Therefore I do not want to copy same methods in all classes. I thought to create a utility class and put these methods inside and send the necessary data as a parameter. But I read about using utility class violate OOP.
As a second, I was thinking to apply strategy pattern but I do not need to change behaviour of the method in the runtime, it will work same for both classes therefore it looks it does not suit to my problem.
Do you have any idea what could be the best approach for this situation or which design pattern could be applied?
It's not bad to violate OOP for something that is really a utility class.
Almost all frameworks (spring, hibernate you_name_it) do that to some extend.
Furthermore, if you later plan to support your code, composition is much easier to refactor / support than to maintain inheritance in your classes.
public class Baseclass
{
public Baseclass(){
//init baseclass;
}
public void commonMethod(){
//do stuff;
}
}
public class AnyObject extends Baseclass
{
public AnyObject(){
super();
}
}
Simple example
I'm looking for a way to add some methods into exists class like this:
String s = "";
s.doSomething();
In objective C, I can use category to do this.
#interface NSString( Stuff)
-(void)doSomething();
#end
Is android has something like that? Or another hack?
Update: Actually, I got this problem: I use a class (not final) from jar file (so, I can't touch its source code). Then I want to add methods( or something like that) into this class without using inheritance. For example:
public class Provider{
// many methods and fields go here...
public String getName(){}
}
All I want to do is:
provider.print(); //that call getName() method;
I also tried proxy pattern, it worked, but I don't like that way (because it like a wrapper class, I must store an object with many fields and methods to use only one method):
public class ProxyProvider{
Provider provider;
public ProxyProvider(Provider provider){
this.provider = provider;
}
public void print(){
String name = provider.getName();
//do something
}
}
Is there any way to solve that?
You could create a utility class with static methods:
public final class ProviderUtils {
private ProviderUtils() {} // not instantiable, it is a utility class
public static void print(Provider provider) {
String name = provider.getName();
// print the name
}
}
In your code, you can then call it:
Provider p = new Provider(...);
ProviderUtils.print(p);
And if that class only has one print method, you can maybe call it ProviderPrinter instead of ProviderUtils.
In the end you don't have thousands of possibilities - you can:
extend the class and whatever method you need in the sub class => you said you don't want that
modify the source code of the class and recompile your own version of the jar
wrap the class in a wrapper that adds the methods you need (your ProxyProvider example)
put the methods you need in a static utility class (what I proposed above)
modify the class at runtime and add a method, but that's a complicated path because you need to play with classloaders.
It is not possible, however, there is a java like DSL available called Xtend that can be used as a compelling replacement for JAVA that might be work looking at which supports extension methods like this.
http://www.eclipse.org/xtend/
DISCLAIMER: I am in no way associated to this I am just an avid user of the core technology that was used to create xtend called xtext. I have considered using xtend on an Android project
In Java, a class can be extended using regular inheritence unless it final. String is final, because Strings are immutable, and therefore are intentionally protected against subclassing.
Also, adding behaviour by subclassing is considered bad practice in many cases - the coupling is simply too strong and sticks with you for instances of your objects you are ever going to create. The rule of thumb is "favour composition over inheritance".
Having said this, there are many approaches / patterns to solve your special problem. Decorator might be the pattern you are looking for.
Please update your question or post a new one with more information.
Try to extend the class in question and add your methods to it. if that can't be done (like it's been said, String is final) then just write a wrapper around it with the methods you want and the object you want to extend.
Like
public class MyString
{
private String internal;
//your methods
}
try to further elaborate your problem so i can give a better answer. like whats the real object in question and what you really wanna do, if you can disclose it that is.
Assume that you must access a protected method of a Java object that you receive somewhere in your code. What is your solution?
I know one approach: You can employ reflection and call setAccessible(true) on the Method object.
Any other idea?
As per the Java access modifiers, besides extending the object (which you can't if you receive the object) is to access it from an object in the same package as the object you received. So your option is to create a wrapper class in the same package which retrieves the attribute via the protected method for you.
You can subclass the method, create a public method that calls the protected method and returns the result.
If you can't do that (if the class is final), then setAccessible is pretty much your only way.
One other option is to create a class that extends that 3rd party class that has the protected method that you are interested in.
public class ThirdPartyClass
{
protected void foo(){}
}
and
public MyClass extends ThirdPartyClass
{
public void callFoo()
{
foo();
}
}
You can also extend the class, override the method, and make the overridden method be public. Then have it just call super.method().
The other way is to extend the Class (if possible) and get access to the protected method via inheritance. If you do not create the Object this is not possible, as you would need it at compile time and you would need to create the Object yourself.
A dodgy solution could be to use composition. So you create a class in the same package e.g. OtherObjectWrapper. As it's in the same package you could call the Object's protected method through a public API you expose. This is not recommended though, as you don't own the package which you are adding a Class too and you can make your code very brittle e.g.
package com.foo;
public class OtherObjectWrapper {
private com.foo.OtherObject wrappedObject;
public OtherObjectWrapper(com.foo.OtherObject wrappedObject) {
this.wrappedObject = wrappedObject;
}
public void callTheProtectedMethod() {
wrappedObject.callTheProtectedMethod();
}
}
Consider what the the API designer thinking when they marked the method as protected? Maybe they didn't have a clue what they were doing and it should be public, or worse still, it should be package private or private outright. Or maybe they did and they determined only code in the same package or through inheritance should have access to the protected method. If it's protected it may well be for a reason, so be wary as you may tie your codes behaviour to behaviours which may change and break your code. Also look at who owns the third party Object and whether there is a better API for accessing the protected method's functionality.
If you can put the calling class in the same package you will have access to the method.
This and inheriting from that class are the only non-reflective ways to access a protected method.
As already said, subclassing is normally the standard way to access that method.
Other approaches (wrapper in same package, reflection) should generally not used, since if you can't extend the class (due to being final) there often are good reasons accessing that method is made hard.
If the library is of any decent quality you definitely shouldn't have to use any other means besides subclassing to access a protected method or not access that method at all.
If a class is not final, you can use an anonymous class to call its protected method:
new ClassWithProtectedMethod() {
#Override
protected void method() {
super.method();
}
}.method();
Note, making method() public is unnecessary (since the new anonymous class is in the same package).
I have 5 or 6 classes that I want to have follow the same basic structure internally. Really most of those that the classes should follow are just for the use of the function itself, so I really want these methods to be private.
Is there any way to achieve this? I know interfaces would work great but they won't take private members and won't allow you to redefine the scope in the implemented method. Is there any workaround for this?
Thanks
I think the closest you can get is using an abstract class with abstract protected methods:
abstract class A {
protected abstract void foo();
}
class B extends A {
protected void foo() {}
}
To define common logic, you can call the protected method from a private method in the super class:
abstract class A {
private void bar() {
// do common stuff
foo();
}
protected abstract void foo();
}
This way, you can allow subclasses to fill the private common template method with specific behavior.
Create an abstract base class that outlines the structure and common flow. Specify abstract methods for the steps in the flow that must be implemented by the inheriting classes.
Hmm, private functions can't be called by any other classes, even by subclasses. So what's the point in having private functions with the same name in different classes?
There is no way to enforce it at compile time, but you can write a unit test or a simple program to test for the existence of the methods using reflection.
I assume you are doing this to make the classes consistent for aesthetics/design reasons. If you are doing it for some other reason you should really use the abstract protected way others are suggesting.
Here is some code to get you started on such a tool/unit tests (you should improve the error messages at the very least, and I would really suggest unit tests rather then what I have here):
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main
{
public static void main(String[] args)
{
check(B.class, Modifier.PRIVATE, void.class, "doit", new Class<?>[] { int.class });
check(C.class, Modifier.PRIVATE, void.class, "doit", new Class<?>[] { int.class });
}
private static void check(final Class<?> clazz,
final int modifiers,
final Class<?> returnType,
final String name,
final Class<?>[] params)
{
try
{
final Method method;
method = clazz.getDeclaredMethod(name, params);
if(method.getModifiers() != modifiers)
{
System.out.println("modifiers do not match");
}
if(method.getReturnType() != returnType)
{
System.out.println("return type does not match");
}
}
catch(final NoSuchMethodException ex)
{
System.out.println("could not find method");
}
}
}
interface A
{
void foo();
}
class B
implements A
{
public void foo()
{
doit(0);
}
private void doit(final int x)
{
}
}
class C
implements A
{
public void foo()
{
doit(0);
}
private int doit(final int x)
{
return (5);
}
}
Create an outline 'common' class, with all your private methods on them.
Then create your 5 or 6 classes , each which have a field on there of type 'common'.
You won't be able to call the private methods of course (but you say these are really internal to the class) - you'll have to advertise some public methods to alter state as well of course.
public class common {
private method1() { ; }
private method2() { ; }
public other() { ; }
...
}
public class myclass1 {
common commonMethods;
}
public class myclass2 {
common commonMethods;
}
or even (assume 'common' is defined as above):
public class template {
common commonMethods;
}
public class myclass1 extends template {
...
}
So you get a (package-protected) 'commonMethods' field for 'free' on each of 5 or 6 subclasses.
After subsequent discussion on this thread, it appears the author doesn't actually want to share logic : just method signatures essentially , so this answer doesn't fit with that requirement.
While the interface methods themselves must always be public, you could make the interface package private and keep all of your Car (for example) implementations in the same package.
package com.some.car.pkg;
interface Car
{
public void gas();
public void brake();
}
Even though the methods are public, it doesn't matter since outside of the package com.some.car.pkg, Car is not visible. This way, all of your implementers would not be forced to extend an abstract class. The fact that you want common methods means truly private isn't the real solution, and IMHO, you want an interface, since it sounds like in your case an abstract class isn't quite right as there is no shared logic.
My 2 cents.
The "throw MethodNotImplementedException();" might be a useful construct.
If abstract protected really isn't protected enough, I wonder what the concern is. In any case, an alternative similar to monojohnny's would be to use the strategy pattern. This ensures that:
derived classes must define the behavior
derived classes can't access the behavior after defining it
instances can't access one another's behavior
E.g., with apologies for borrowing the car metaphor despite no automotive chops:
public interface GearBoxStrategy {
public void changeGear(int newGear);
}
abstract public class Car {
private GearBoxStrategy gearBox;
public Car(GearBoxStrategy g) {
this.gearBox = g;
}
public void accelerate(double targetSpeed) {
int gear = getTargetGear(targetSpeed):
gearBox.shift(gear);
}
}
public class AutomaticTransmissionCar {
public AutomaticTransmissionCar() {
super(new AutomaticTransmissionGearBoxStrategy());
}
}
public class ManualTransmissionCar {
public ManualTransmissionCar() {
super(new ManualTransmissionGearBoxStrategy());
}
}
Create an abstract base class with a method marked final that describes the common flow that includes your private methods. Marking it as final means that it can't be extended by subclasses and thus the business logic is enforced as long as your calling code utilizes it. Extension points can be created by marking methods as protected. For example say you have a class that represents a retail store.
private final void doTransaction() {
float amountDue;
// a protected or abstract method that extenders can override
Collection items = this.unloadShoppingCart();
for (Object item : items) {
// another protected or abstract method
amountDue += this.getPrice(item);
}
// your private method
amountDue += this.getSalesTax(amountDue);
}
Is it possible to make all the classes inherit from the same base class?
If so, one thing you could consider would be at runtime in the base class's constructor use reflection to validate that the subclass is following the rules you describe, and throw an exception if it fails your validation rules.
The naive implementation of this test of course would have significant performance issues, so you'd have to be pretty clever about the way you implement the test.
For a start, the test should only be run once for all instances of a particular subtype T. So, you would have to cache the validation information somewhere. One way to do this would be to use some kind of static (global) hash table in the base class keyed on the type of each subtype.
You would also have to perform some kind of thread safe synchronization around this cache. What you really need to avoid on this is a performance hit for reads. What I've done in a similar case before was use a combination of the double check locking pattern and the use of an immutable hashtable so that you only take a performance hit for locking when attempting to write to the hashtable (i.e. when you create the first instance of a particular subtype T).
I'm actually not experienced in Java, what I describe, I implemented in .NET, which is why I can't provide you with a code example, but all the concepts should be easily transferable to Java - everything I mention is (AFAIK) available on both platforms.
Take a look at XDepend, it uses reflection to create a database based on your compiled code.
http://www.xdepend.com
It's aimed at software architects who wish to be able to quickly check potentially large libraries of compiled code for potential problem areas. It has inbuilt reports and visualization for such things as relationships between classes, cyclomatic complexity, coupling etc. etc.
In addition, it includes an inbuilt sql like query language "CQL" (for "code query language"). Using CQL you can define your own reports. You probably should be able to use it to define a report for violations of the rules you describe. Also, you can embed CQL queries directly into your code using annotations.
I haven't looked into it, but have used it's .NET equivalent 'NDepend', and it's a very cool tool.
Of course, you could also write your own custom tool which uses reflection to check your specific rules. XDepend may still be worth looking at though - it should be a lot more flexible.
Here's an idea: write a simple text parser to check for the existence of the methods. Include it as a task in Ant. As long as you are insisting on some form of coding standard, some simple text-matching should do it, ie, simply look for the formatted signature in the required source files.
In a comment you wrote "Yes that is the whole point. I know they can be called different things but I don't want them to be."
Now, some people might just say "that's impossible" but like most things in programming, it's not actually impossible, it's just a lot of work.
If you really want to do this, you can create a custom Java Annotation for your class and then write an Annotation processor and call apt as part of your build process.
Like I said a lot of work, but it might be worthwhile if you want to learn how Annotations work.
Writing annotations is actually pretty simple. They work kind of like regular classes. For example, if you just want to mark a class for some reason you can create an empty or marker annotation like this
public #interface Car { }
Then in your Annotation Processor you can check to make sure Car has the right private methods.
I've written my own annotations, but I checked them at Runtime using the reflection API, rather then at build time. They are actually pretty easy.
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!