Java Interface Design - Helper Methods - java

I have an interface like so
public interface Manager {
public void manage();
}
Now, all Managers will need to load work to manage, however, I have mixed feelings about adding public void loadWork() to the interface...
On one hand, all Managers will do this, but on the other hand, users of a Manager class will not need to know about loadWork().
Question: Is it bad practice to add "helper" or "setup" type methods to an interface?

It's not always a bad idea to add "setup" methods in an interface. For example, Java EE has an interface called ServletContextListener that is purely meant to make setup and shut down.
It's even sometimes acceptable to make interfaces with methods you should actually never directly call such as the Runnable or the Callable interface.
Being said that, it seems is that you want to force your developers to implement a loadWork() method in Manager but you also want to hide it from the class' users.
As you say, one option is adding the method in the interface but this way the method will be accessible (which you don't want). If you don't want the method to have visibility I see two options:
Make the class Manager an abstract class and add a loadWork() protected method.
Create an interface called LoadWorker with a method loadWork(). Then create an abstract class AbstractManager that implements Manager and has as a private/protected LoadWorker field. This way, even though loadWork() is public, it's not accessible from AbstractManager's users as it is called through a protected/private field (LoadWorker).
At the end it comes to a balance between overengineering and good design. It's up to you to take the decision following the specific needs. Nevertheless, there is no 'perfect solution'.

Related

Starting method in all implemented classes

I'm kind of new to Java and have a rather simple question:
I have an interface, with a method:
public interface Interface_Updatable {
public void updateViewModel();
}
I implement this interface in several classes. Each class then of course has that method updateViewModel.
Edit: I instantiate these classes in a main function. Here I need code that calls updateViewModel for all objects that implement the interface.
Is there an easy way to do it combined? I don't want to call every method from every object instance separately and keep that updated. Keeping it updated might lead to errors in the long run.
The short form is: no, there's no simple way to "call this method on all instances of classes that implement this interface".
At least not in a way that's sane and maintainable.
So what should you do instead?
In reality you almost never want to just "call it on all instances", but you have some kind of relation between the thing that should trigger the update and the instances for which it should be triggered.
For example, the naming of the method suggests that instances of Interface_Updatable are related to the view model. So if they "care" about changes to the view model, they could register themselves as interested parties by doing something like theViewModel.registerForUpdates(this), the view model could hold on to a list of all objects that registered like this and then loop over all the instances and calls updateViewModel on each one (of course one would need to make sure that unregistration also happens, where appropriate).
This is the classical listener pattern at work.
But the high-level answer is: you almost never want to call something on "all instances", instead the instances you want to call it on have some relation to each other and you would need to make that relation explicit (via some registration mechanism like the one described above).
There is no easy way to call this method on all classes that implement this interface. The problem is that you need to somehow keep track of all the classes that implement this interface.
A possible object-oriented way to do this would be passing a list containing objects that are instances of classes that implement the Interface_Updateable interface to a function, and then calling updateViewModel on each object in that list:
public void updateViewModels(List<Interface_Updateable> instances) {
for(var instance : instances) {
instance.updateViewModel();
}
}

Prevent dependency on a class in Java / Kotlin, but allow extending

I wish to create a useful base Java class with a few protected methods and hooks so subclasses can be easily implemented.
However, I wish this class to ONLY be available for deriving a subclass, but not available as a dependency.
The reason is to prevent some junior/careless developers from coupling their code to this base class.
For example, if my base class is called BaseActivity.java, anyone can create their own
public class MyNewActivity extends BaseActivity
But no one can refer directly to BaseActivity with a field or method signature, for example this should not be allowed:
public void doSomethingOnBaseActivity(BaseActivity activity);
private BaseActivity someField;
public BaseActivity getActivity();
Is there any way to accomplish such a restriction in Java?
Maybe in Kotlin this would be possible?
EDIT:
This is NOT a duplicate of Kotlin: Can an abstract super class have an abstract constructor?.
I wish to prevent dependency on the base class, not just instantiation. "Abstract" doesn't help here.
No, this is not possible. This answer is true for all types, whether abstract or not, interface or class. When you are in the scope of a class (e.g. same package), and this class is not sealed then everybody in this scope can inherit it. As long you are inside the scope, you can reference this type. That's the point of access modifiers. It doesn't make sense to allow extension of a type but not referencing it. This contradicts the concept. Why would you want to do that? You can't remove that base class anyway because that would break the code of all inheritors. There is no point in allowing extension but disallowing referencing. What is the reason for this. Maybe there is a different way to accomplish your goal. The very moment somebody inherits from a type creates the dependency. This dependency is called inheritance. The subtype is a supertype. You can't hide this fact from the compiler.
If you want to omit a dependency but reuse code or provide a template of the code then don't use a type. You could use file templates or a code generator to generate the reusable code (like code snippets).
First off, let's address the why. Why are you looking for this? You're looking for a way to prevent the consumer from calling unwanted methods on a base class.
If you think you're looking for something else, think again. If you just want to hide it, think again. The end user will not care about implementation details at all.
If you created the base class, then don't publish an API that allows this in the first place. There was a chapter on this specifically in Clean Code.
If your base class extends another base class you're in trouble. You can't hide already published API, if you're extending and not encapsulating.
I wish this class to ONLY be available for deriving a subclass, but not available as a dependency. Is there any way to accomplish such a restriction in Java? Maybe in Kotlin this would be possible?
No. This is not an opinion, this is by design.
There may be a convoluted way to hide methods of parent classes but not on the class the consumer interacts with (extends).
You could have several layers of base classes each within its own Gradle module and setup implementation type dependency but then If you can extend the class, if you can see it, reference it, you can also use it anywhere.
Imagine this:
consumer module -> ConsumerActivity extends ExtensibleActivity
your library module -> ExtensibleActivity extends BaseActivity
your base library module -> BaseActivity extends Activity
Android SDK -> Activity
Consumer module only sees what's inside "your library module". It knows about ExtensibleActivity but it can't see any of its super types. The consumer can still reference ExtensibleActivity and its methods. The side effect is because the superclasses are not known from consumer's point of view, you can't pass an instance of ExtensibleActivity as an Activity because the type system doesn't know it extends an Activity, because it doesn't see the BaseActivity intermediary type. Here's a graph of what the consumer sees:
ConsumerActivity -> ExtensibleActivity -> BaseActivity (doesn't exist) -> ??? (don't know)
At this point you just have to ask yourself "should this have extended Activity in the first place?".
This is just terrible to work with. Lot of wasted effort for something that you shouldn't need to worry about.
If you want to conceal something, use composition over inheritance. Put your logic inside a Fragment or, better yet, put your logic inside a custom lifecycle aware component. That way you're in total control over the API. Make it so you don't have to worry about where it gets called from.
Write good documentation for your code and a usage manual.
And kindly allow me to break your damn library if I choose to use it incorrectly.
Do you have multiple methods in your API? Great! Nobody will prevent me from calling them out of order. You can write in your manual how it's supposed to be used, but ultimately, I'm writing my program, using your library, and if I do it wrong, then it's my fault when it breaks. This is fine.

How to prevent client from seeing internal private classes in Android library ?

I have a library with several packages-
lets say
package a;
package b;
inside package a I have public a_class
inside package b I have public b_class
a_class uses b_class.
I need to generate a library from this , but I do not want the Client to see b_class.
The only solution I know of is to flatten my beautifully understandable packages to single package and to use default package access for b_class.
Is there another way to do so ? maybe using interfaces or some form of design pattern ??
If you reject to move the code to an individual, controlled server, all you can do is to hinder the client programmer when trying to use your APIs. Let's begin applying good practices to your design:
Let your packages organized as they are now.
For every class you want to "hide":
Make it non-public.
Extract its public API to a new, public interface:
public interface MyInterface {...}
Create a public factory class to get an object of that interface type.
public class MyFactory
{
public MyInterface createObject();
}
So far, you have now your packages loosely coupled, and the implementation classes are now private (as good practices preach, and you already said). Still, they are yet available through the interfaces and factories.
So, how can you avoid that "stranger" clients execute your private APIs? What comes next is a creative, a little complicated, yet valid solution, based on hindering the client programmers:
Modify your factory classes: Add to every factory method a new parameter:
public class MyFactory
{
public MyInterface createObject(Macguffin parameter);
}
So, what is Macguffin? It is a new interface you must define in your application, with at least one method:
public interface Macguffin
{
public String dummyMethod();
}
But do not provide any usable implementation of this interface. In every place of your code you need to provide a Macguffin object, create it through an anonymous class:
MyFactory.getObject(new Macguffin(){
public String dummyMethod(){
return "x";
}
});
Or, even more advanced, through a dynamic proxy object, so no ".class" file of this implementation would be found even if the client programmer dares to decompile the code.
What do you get from this? Basically is to dissuade the programmer from using a factory which requires an unknown, undocumented, ununderstandable object. The factory classes should just care not to receive a null object, and to invoke the dummy method and check the return value it is not null either (or, if you want a higher security level, add an undocumented secret-key-rule).
So this solution relies upon a subtle obfuscation of your API, to discourage the client programmer to use it directly. The more obscure the names of the Macguffin interface and its methods, the better.
I need to generate a library from this , but I do not want the Client to see b_class. The only solution I know of is to flatten my beautifully understandable packages to single package and to use default package access for b_class. Is there another way to do so ?
Yes, make b_class package-private (default access) and instantiate it via reflection for use in a_class.
Since you know the full class name, reflectively load the class:
Class<?> clz = Class.forName("b.b_class")
Find the constructor you want to invoke:
Constructor<?> con = clz.getDeclaredConstructor();
Allow yourself to invoke the constructor by making it accessible:
con.setAccessible(true);
Invoke the constructor to obtain your b_class instance:
Object o = con.newInstance();
Hurrah, now you have an instance of b_class. However, you can't call b_class's methods on an instance of Object, so you have two options:
Use reflection to invoke b_class's methods (not much fun, but easy enough and may be ok if you only have a few methods with few parameters).
Have b_class implement an interface that you don't mind the client seeing and cast your instance of b_class to that interface (reading between the lines I suspect you may already have such an interface?).
You'll definitely want to go with option 2 to minimise your pain unless it gets you back to square one again (polluting the namespace with types you don't want to expose the client to).
For full disclosure, two notes:
1) There is a (small) overhead to using reflection vs direct instantiation and invocation. If you cast to an interface you'll only pay the cost of reflection on the instantiation. In any case it likely isn't a problem unless you make hundreds of thousands of invocations in a tight loop.
2) There is nothing to stop a determined client from finding out the class name and doing the same thing, but if I understand your motivation correctly you just want expose a clean API, so this isn't really a worry.
When using Kotlin, you can use the internal modifier for your library classes.
If I understand correctly you are asking about publishing your library for 3rd party usage without disclosing part of your source? If that's the case you can use proguard, which can obfuscate your library. By default everything will be excluded/obfuscated, unless you specify things you want to exclude from being obfuscated/excluded.
If you want to distribute [part of] your code without the client being able to access it at all, that means that the client won't be able to execute it either. :-O
Thus, you just have one option: Put the sensible part of your code into a public server and distribute a proxy to access it, so that your code would be kept and executed into your server and the client would still be able to execute it through the proxy but without accessing it directly.
You might use a servlet, a webservice, a RMI object, or a simple TCP server, depending on the complexity level of your code.
This is the safest approach I can think of, but it also deserves a price to pay: In addition to complexing your system, it would introduce a network delay for each remote operation, which might be big deal depending on the performance requirements. Also, you should securize the server itself, to avoid hacker intrussions. This could be a good solution if you already have a server that you could take advantage of.

Is it an ok practice to have a member ClientBundle in a containing ClientBundle?

In my app, I have MyAppResources, which will mainly contain custom styles for the app. I am thinking about what is a good way to go about applying custom styles to standard widgets, such as a CellTable, along with custom styles on the layout and custom widgets?
My question:
Since MyAppResources is a singleton (it doesn't have to be, as mentioned in other posts), but CellTableResources isn't, and CellTableResources is a member of this instance that is an interface also extending ClientBundle, will a proxy 'CellTableResources' be created on every MyAppResources.INSTANCE.cellTableResources().foo()?
If so, could I create a MyAppResources.CELLTABLE_RESOURCE_INSTANCE to get around this? Or would the creation of the proxy be negligible, even if there are plentiful calls to MyAppResources.INSTANCE.cellTableResources().#?
Secondly, more of a discussion question: what is best practice in regards to using multiple ClientBundles in this case? Should I instead use CellTableResources seperately (remove it from MyAppResources), using GWT.create(CellTableResources.class); in a widget that needs it (or using a singleton like I have for MyAppResources)?
MyAppResources:
public interface MyAppResources extends ClientBundle {
public static final MyAppResources INSTANCE = GWT.create(MyAppResources.class);
#Source("MyAppStyles.css")
public MyAppCssResource css();
public CellTableResources cellTableResources();
}
CellTableResources:
public interface CellTableResources extends CellTable.Resources {
interface CellTableStyle extends CellTable.Style {
}
#Override
#Source({ CellTable.Style.DEFAULT_CSS, "CellTableStyles.css" })
CellTableStyle cellTableStyle();
#Source("green_light.png")
ImageResource getGreenLight();
//...
}
Thank you for reading.
Multi-part question, so I'm going to try to hit this in several parts:
What is the cost of GWT.create()?
Most of the GWT class is 'magic', things that you cannot wrote for yourself in other ways, as they call on the compiler to fill in specific details for you. These are often different when running in dev mode vs compiled to JS.
In the case of GWT.create, it turns out that this is compiled out to new - it is used just to create new instances. So what is the cost of a new instance versus a singleton? This depends entirely on the object being created. If there are no fields in the object, then the cost is essentially free - in fact, the compiler may choose to actually remove the constructor call, and rewrite all later methods as static anyway!
This is what happens in most cases - GWT.create should be considered to be very cheap, unless you are doing something silly like calling it within a loop that is run many times.
What happens when I list a ClientBundle method inside another ClientBundle?
Well, what happens when you list anything inside a ClientBundle?
Anything that can be listed in a ClientBundle must be annotated with #ResourceGeneratorType, indicating how to generate that type. For example, here is ImageResource:
/**
* Provides access to image resources at runtime.
*/
#DefaultExtensions(value = {".png", ".jpg", ".gif", ".bmp"})
#ResourceGeneratorType(ImageResourceGenerator.class)
public interface ImageResource extends ResourcePrototype {
//...
It calls on ImageResourceGenerator to create images as needed. Any class described in that annotation must implement com.google.gwt.resources.ext.ResourceGenerator, which describes how to get ready to work, how to create necessary fields, how to initialize them, and how to finish up.
So what does this look like for ClientBundle itself? Check out com.google.gwt.resources.rg.BundleResourceGenerator - it is a very simple class that just calls GWT.create() on the type of the method given. So, predictable, this means that those 'child' ClientBundles are created via GWT.create, more or less the same as you might otherwise do.
Okay, what does that mean in this specific case?
It turns out that ClientBundles instances don't have fields where they track newly created objects from, but instead have static members that they use instead - effectively singletons. This means that once you have called a method once, the instance it returns will be the same instance created as the next time you call it. Two different ClientBundles with the same contents will of course then keep two different copies of the objects, but it doesn't matter how many times you create a ClientBundle - its internals will always be the same.
Anything else?
Yep! Remember that you are dealing with interfaces here, not classes, so you can actually extend more than once at once!
public interface MyAppResources extends
ClientBundle,
CellTable.Resources,
CellTree.Resources {//etc
//...
Now, if two interfaces describe the same methods you may have problems, but if not, this can provide an advantage when generated sprited images. Each individual ClientBundle will draw on its own pool of images when preparing them for use - if you have a ClientBundle within a ClientBundle, they won't work together to sprite images into bigger pieces. To get that, you need to make just one ClientBundle type. This may not matter in your particular case, but I figured it was also worth mentioning.

How to instantiate a class that has a constructor requiring an interface object

I am trying to use the Interactive Brokers Java API to see if I can do some algorithmic trading (on paper initially). I want to call a method called ReqMktDepth() which is in a class called EClientSocket.
The EClientSocket constructor requires an object of type AnyWrapper to be passed, and AnyWrapper is an interface not a concrete class. In theory how do I go about passing an AnyWrapper class to the EClientSocket constructor.
You need to create a class that implements AnyWrapper (using the "implements" keyword) and then you must provide the definitions for any methods defined by that interface.
Here's one simple tutorial:
http://www.uweb.ucsb.edu/~cdecuir/Polymorphism.html
You can either create your own class which implements AnyWrapper interface as Bobby suggests. or Use any other class(present in the library/jar/namespace) which already extends from AnyWrapper interface like the EWrapper, class which already has an implementation of AnyWrapper.
see -> http://www.interactivebrokers.com/php/apiUsersGuide/apiguide/java/eclientsocket.htm
You should probably use some class in that API you use which implements the AnyWrapper interface. You could have a look into the JavaDoc of that API or use your IDE's features (something like show type hierarchy) to find out which classes implement AnyWrapper, and pass one of them.
Several other answers have pointed out that you can create an instance of AnyWrapper by either implementing it yourself or by finding an existing class and passing in an instance of that class.
However it seems to me that what you are doing is not likely to succeed. You are trying to call a method whose argument is completely unknown to you. You need to read the documentation about that method and find out what the AnyWrapper is for and how it will be used. Maybe there just needs to be something provided, but maybe AnyWrapper has some responsibility that the EClientSocket needs.
This kind of programming by trial and error can lead to some serious problems down the road. For one thing, certain methods are not safe to call unless other safeguards are taken. Certain methods have major performance or security implications. In this case I think you really need to find out what it is you're trying to do before you figure out how to do it.

Categories

Resources