package visibility [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Why use package visibility (the default), unless the class should be public in java

As Rostislav Matl said, it's useful for when you want to make something that doesn't form part of your package's interface.
As an example, imagine you have a package and it provides an interface and at least one concrete implementation of a service.
People who use this service are going to care about the interface you provide and use one of the concrete classes you provide but they aren't going to care about much else beyond that. Our service has to talk to a database and it needs to be able to map the result from database queries into its own data type (that form its contract).
I find that I regularly create package private helper classes that contain utility type methods or perform tasks like the mapping that we need. Default (package private) visibility is perfect for this because other classes inside your package can use these helpers but no-one outside the package can see them so you're free to change them whenever you like.
This is a an example using some code:
We have our interface:
public interface UsefulService {
Collection<DataThings> getThings(Identifier id);
}
...and our concrete implementation:
public class JdbcUsefulServiceImpl implements UsefulService {
//We can break the code for the mapping out into its own class
private Mapper mapper;
#Override
public Collection<DataThings> getThings(Identifier id){
DatabaseQueryResult queryResult = //Code to hit a database and return objects from that domain model
Collection<DataThings> result = mapper.mapFromDatabaseToServiceDomain(queryResult);
return result;
}
}
Then we have our mapper. We don't need anyone outside the package to care about the service works internally so we use package private visibility and we can have as many classes as we want to get the job done:
class Mapper {
Collection<DataThings> mapFromDatabaseToServiceDomain(DatabaseQueryResult queryResult){
//magic to map objects goes here
}
}
The benefit that we have is that we can always change this Mapper class however we want or delete it or create new package private classes and we know the only (immediate) effects we can cause are inside this package. By immediate effects I mean compiler errors and serious things like that. Obviously you could break your service if you change its behaviour but that's what your automated test suite is there to catch :P

My understaning is package/default access is for package internals, i.e. classes that do not form package interface, i.e. classes that should not be used outside the package.

Related

Implement inner-class-like reference behaviour? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
First of all, allow me to explain a "behaviour" that I observed, then I will ask in "Example" section.
Inner-class-reference behaviour
In Java we can have (non-static) inner-classes, which seem to behave like having a strong-reference to their container-class and/or owner-class, but without causing memory-leak.
I mean, I observed that even if both owner-class and inner-class keep strong-reference to each other, the classes are garbage-collected anyway (once no external class references them, although having reference-recursion).
In other words, or in other programming-languages, where "reference-counters" are often used (unlike Java?);
We could achieve such behaviour if owner-class and all inner-classes share the same reference-counter. Where just like above, even if we only keep a single reference to inner-class, owner-class is kept as well.
Example (background and question)
My previous logic, which used above said behaviour, was something like:
public class WebApi {
public UserApi user = new UserApi();
public PostApi post = new PostApi();
protected String post(String url, String json) {
// ...
}
public class UserApi {
public void login() {
WebApi.this.post(...);
}
public void logout() {
WebApi.this.post(...);
}
// ...
}
public class PostApi {
// ...
}
}
Then day by day the project did grow, till each of UserApi and PostApi classes deserved their own separate files (instead of being inner-classes of one huge file).
How can we implement above described "Inner-class-reference" behaviour for external classes?
In Java we can have (non-static) inner-classes, which seem to "behave" like having a strong-reference to their container-class and/or owner-class, but without causing memory-leak.
I mean, I observed that even if both owner-class and inner-class keep strong-reference to each other, the classes are garbage-collected anyway (once no external class references them, although having reference-recursion).
Yes, that's how references work in Java: if an object is reachable, then it's retained, and if not, then it's (eventually) garbage-collected.
But how can we implement above described "Inner-class-reference" behaviour for external classes?
You don't need to do anything special: just give UserApi a field of type WebApi, and initialize it in the constructor.
Java's reference-tracing and garbage collection will ensure that, as long as any reachable UserApi instance holds a reference to a given WebApi instance, the WebApi instance is also considered reachable, and hence retained.

How to pass List<Object> objects to a constructor parameter (Object object1, Object object2)? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
My goal is to pass List<Object> objects to a constructor parameter Object object1, Object object2.
For example,
public class A {
public A(Object object1, Object object2) {
}
}
public class App {
public static void main(String[] args) {
List<Object> objects = new ArrayList<>();
objects.add(new Object());
objects.add(new Object())
A a = new A(...objects);
}
}
My expected result: It should work.
My actual result: The IDE throws error unexpected token.
Java, the language, has zero syntactical support for what you are trying to do here. And most likely never will, it is fundamentally tricky to do in java.
In general if you have a java method that takes a heap of arguments, all of which are of the same type, that's a badly designed method and you shouldn't be having it. Java could hypothetically grow a language feature that helps you out, but why cater to idiotic API designs, right?
Alternatively, you could have a List<Object> with a heterogenous (bunch of differently typed) objects, but you shouldn't have that either, it's un-java-like. Same cause for why java doesn't have this and probably never will: Why cater to bad code style?
Note that in java you can have 15 methods all with the same name differentiated solely by their types, so figuring out which one you actually intended to call is not necessarily simple.
You CAN do what you want with generics but it's a ton of code and very ugly:
public class Example {
public void callMe(String a, Integer b) {}
public void dynamicallyCallMe(List<Object> list) {
Method m = Example.class.getMethod("callMe", String.class, Integer.class);
m.invoke(this, list.toArray());
}
}
You do not want to this.
If you're facing a scenario where you do want this, then you'd want to change the environment some. For example, if these arguments are being provided by a user via a config script or whatnot, the method you are calling should be aware of this, and should therefore follow the interface public interface ConfigurableApp { void configure(List<String> aguments); } or whatnot. Make it explicit. Write a wrapper if you must, which would then be the place in your code where you perform any translations as needed.
If you're facing a more code-heavy config concept (where the config file needs to contain code, or code-esque constructions), then go all the way and make it a script file, run it with a script runner. Let them write that config file in javascript or what not and execute it from your java process.
And so on.
EDIT: With some more insights provided via the comments on this question:
What you're likely looking for is an SPI system that discovers factories.
SPI
SPI, or Service Provider Interface, is the name generally used in the java community for the idea of 'I have a mechanism by which a JDK can read a list of classes that implement some service straight from the classpath, usually via a file in META-INF/services/fully.qualified.name.ServiceInterface which lists 1 fully qualified classname per line. Reading these files out is baked into the core: ServiceLoader. Making them - lots of utilities around that let you just annotate a class and an annotation processor makes the services file for you.
The java module system has its own take on this idea, using the provides keyword. I suggest you don't mess with the java module system, though. Nobody* uses it.
Factories
The way ServiceLoader forces you to work, but this way is quite sensible so you should do this too (handrolling your own ServiceLoader is a single page class, so if you want to deviate, you can - it won't be difficult, it's just a bad idea stylewise), is that the involved classes have the following rules:
They MUST implement/extend the service interface.
They MUST have a public no-argument constructor.
The SPI system will then instantiate the class once using that constructor and will then give you a list of the service interface.
If this 'no arguments' thing is bothering you, that's when you add in a single layer of abstraction: The 'service' describes a factory, the classes in the META-INF/services class file are implementations of the factory service, and the factory's job is to make the instances you actually want.
Example
Let's say we are an image editor and you want a pluggable 'find interesting objects using AI'.
You start by making an interface that describes an image filter:
public interface ThingieFinder {
/** Describe what this thingiefinder finds */
String getDescription();
/** Try to find stuff within a segment of the image */
List<Thingie> find(Coords coords, double howSeriously);
}
But what's missing in this description is the constructor which would, of course, take the object representing the entire image.
Factories are the answer. Make this interface too:
public interface ThingieFinderFactory {
public ThingieFinder make(Image image);
}
This interface 'represents' the constructor. An implementation of this factory can be a trivial one-liner:
public class FaceFinderFactory implements ThingieFinderFactory {
public FaceFinder make(Image image) {
return new FaceFinder(image);
}
}
and this factory has a single no-args public constructor! ThingieFinderFactory can be the service, and this can be an implementation of it.
*) Rounding down considerably, but it's far less than half and that doesn't appear to be changing.
Mulitple problems in your code
List does not have put method. Learn about List from here
Java does not support spread operator(...) like JavaScript. In Java (...) is used for varargs
One of many ways to handle your errors.
public A(Object ... args) {
}
List<Object> objects = new ArrayList<>();
objects.add(new Object());
objects.add(new Object());
A a = new A(objects);

Is this appropriate to create a class with one method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm wondering whether it's a good practice to produce the code which being used like this:
new TemplateProcessor(inputStream).processTemplate("output-path.xhtml");
Here, TemplateProcessor contains only one public method. It seems the code above can be expressed with a static method, but I would like to avoid that. The reason is simple: object may contain encapsulated state, (maybe now, maybe in the future). Dear experts what would You prefer in this case?
It's reasonable to encapsulate the code in a static method, with static imports it becomes very easy to use:
processTemplate(inputStream, "output-path.xhtml");
The above static method would just be a façade, a convenience method to be used for that specific use case that your class is solving, supposedly one that's very common. It does not prevent the class from evolving, even adding state. For more specialized use cases, the consumers can still create instances of the class and use its methods as usual.
To make that separation even more pronounced, you could add the static method to a sibling class, like TemplateProcessorFacade, which is a non-instantiatable utility class:
public final class TemplateProcessorFacade {
private TemplateProcessorFacade() {}
public static void processTemplate(...) {
...
}
}
A class should be seen as an object or module that performs a key role or function in the program. A role that no other class or module fulfils. For example, you can have a class Animal that provides the functions sleep(), run() . But you might want a class for carnivores which also kill() , hunt() etc. So you implement the Carnivores class by extending from Animal, which does what all variables of type Animal do, but also additionally kill and hunt.
If your class has only one public method, but if it's important for the design to have it as a separate module, then having a class for it is good. You can extend it later, if needed.
Also you can, keep the sleep() and run() functions static and public, all Animal's do that, and so you can just do Animal.sleep() and such, without creating a separate instance. But a function like roar() shouldn't be.
Update:
The reason I said, sleep() and run() can be static is, there can be a class Man who also sleeps and runs.
The question to ask:
Does it make sense to call sleep() and run() or any function of a class without initializing an object of that class? If yes, then it makes sense to make it static.

practical situation to use an abstract interface? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was trying to understand when it can be useful to create an abstract interface.
I know that if you create an interface the methods have to be public, so is nice for a service. But what happens if service is an abstract interface? Does that make sense?
If I create a service declared abstract interface and some methods are private, the class that implements this interface sees the private methods and the other (another application's or similar) doesn't see this methods, correct?
I this is a correcte implementation?
Finally after a lot of people that can sleep by my fault I write my solution, ty for waiting.
package cat.base.gpt.domini;
public interface IExpMS extends Serializable{
... methods here..
}
public interface IExpMSDetallGIM extends IExpMS {
more methods here..
}
public interface IExpMSDetallOGC extends IExpMS{
..no methods just inheritance.
}
package cat.base.gpt.domini.impl;
import cat.base.gpt.domini.IClauExpedient;
import cat.base.gpt.domini.IExpMS;
public class ExpMS implements IExpMS{
..atributs and #overide methos interface
}
public class ExpMSDetallGim extends ExpMS implements IExpMSDetallGIM {..}
public class ExpMSDetallOGC extends ExpMS implements IExpMSDetallOGC {..}
*every method is public, atributs are private. maybe i can write methods in the interfaces protected, but i'm not really sure...if someone needs to see full code i can't post or send by email.
if ypu wanna see the databasze views to think about my solution here there are:
![IExpMSDetallGIM4
ty.
Interfaces are always abstract. They define the interface of a class, so they are only about public methods, regardless the language, I think.
And while private methods are implementation detail and NOT the interface, they cannot be declared in an interface.
If you want a private method to be the same in a set of classes, you can create a base abstract class with protected methods.
Abstract means "you cannot create a member of this type".
Interface is just a description of some of the classes' properties. They are always abstract, while you cannot create an instance of an interface.
Look at the link http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/ - it describes the code in C#, but it's the same thing, only the keywords differ.
i'm working with java..is the same?so interface = abstract interface?
In Java 7, yes. In Java 7 (or earlier) an interface is implicitly abstract. The interface itself does not include bodies for any of the methods that it specifies, so it makes no sense to create an instance.
In Java 8, it is possible to include default methods in an interface. These default methods have bodies with executable code in them, but (naturally) they cannot refer directly to the state of an instance. (Instance state variables are declared in the classes that implement interface ... and the default methods can't refer to stuff that has not, and may not ever be declared.)
However, you still cannot create an instance of a Java 8 interface, so it is still abstract in the sense that an abstract class is abstract.
You then ask this:
If I create a service declared abstract interface and some methods are private, the class that implements this interface sees the private methods and the other (another application's or similar) doesn't see this methods, correct?
That is correct ... but it is nothing to do with what the abstract keyword means in Java. In fact, that is describing how all Java classes behave ... vis-a-vis the visibility of private members.
The primary purpose of interfaces is to allow multiple different implementations of "the same thing". The user of the interface is not dependent on the particular implementation and this allows for good separation of concerns. New implementations can be added later and the program can be extended, without ever need to modify the code that is using them.
Imagine how you would write a program for summing up numbers from various data sources. You could write one separate program for every type of data source (e.g. csv, xls, database table). But then, the "summing up" logic would be repeated. If you wanted to add a new data source type, you'd have to write a whole program from scratch.
Interfaces allow to make it more flexible. You realize, that your summing up logic needs to operate on a list of numbers. It doesn't care where those numbers come from. So you define an interface:
interface NumberListProvider {
List<Double> readNumbers();
}
Then you make your whole complex algorithm dependent only on this interface and you provide different implementations (concrete classes), reading the numbers from csv, xls or various databases.

What is the shortest way to delegate unimplemented methods to a contained object in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I am containing the "primary object" (with most of the features) within a "helper object" that will provide convenience methods. I have only an Interface available, aside from a returned object with that interface from a factory method. I am thinking a good way to "extend" this object is composition, but the problem that my superclass must implement the primary object's interface, which would be about 600 lines of stub code.
Clearly an uncomplicated but verbose solution would be to fill out all the stubs so they merely call the primary object's methods. Is there a better way than this in Java? In other languages I'm familiar with, there would be ways to do automatic delegation for methods that are not implemented in the helper object.
Example:
class Helper implements Interface {
Primary primary;
Helper(Primary _primary) {
primary = _primary;
}
void helper() {
doStuff();
}
// 500 lines of this
void stub() {
primary.stub();
}
}
Note:
Original plan was to just use regular expressions to replace all the stub TODOs in Eclipse with the actual calls. Will be looking for an Eclipse tool that does this automatically though. Also, looks like extending the interface or using Proxy is better in the end, so will be pursuing that.
Use Lombok's #Delegate annotation.
Second-fastest is to use your IDE; many have this functionality.
Third-fastest is to write a tiny little introspecter and dump them out yourself.
There are a few possiblites.
First: Use an abstract implementation that delegates the calls.
abstract class InterfaceDelegator implements Interface {
protected final Interface primary;
public InterfaceDelegator() {
this.primary = primary;
}
// implements all the calls as: primary.call(...)
}
class Helper extends InterfaceDelegator {
// override just the methods you need
}
Second: Use the proxy (probably cleaner).
See: http://docs.oracle.com/javase/1.5.0/docs/guide/reflection/proxy.html
final Interface primary = ...;
return (Interface) Proxy.newProxyInstance(Inteface.class.getClassLoader(),
new Class[] { Interface.class },
new InvocationHandler() {
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
// if m is a method that you want to change the behaviour of, return something
// by default, delegate to the primary
return m.invoke(primary, args);
}
});
The invocation handler will handle calls through executing a method that you have coded, an all the others would be delegated to the primary implementation.
Then, you can wrap a code like this in a method or another factory.
Third: Using the IDE to generate the methods (as others pointed out).
Some IDEs support inheritance to delegation refactoring. This will generate most of the code you need.
If you don't want to use this you can create a dynamic proxy to direct the method calls to a selection of implementing delegates.
There are two choices of which you can choose only one: reduced verbosity or speed/performance. You can of course use a generic reflection based approach which would affect the runtime performance or go with Lombok / eclipse auto-generated methods and live with the verbosity/magic. :)
Your interface is too big. Classes and interfaces tend to grow over time, and it's usually a lot more trouble than its worth to break them up. Once you start wrapping a big class inside another, however, some cleanup may be in order.
In crude terms, what you want to do is break Interface into manageable pieces. The original Interface loses a whole bunch of methods, but picks up a few to return objects implementing the other interfaces. Now, instead of container.getX();, you would have
Interface container = new Helper( primary );
Letter li = container.getLetterInterface(); // Convenience Method
// "li" comes straight from primary
int x = li.getX();
Ideally Interface drops from over 100 methods to under 20. The returned interface implementations can be the underlying Primary objects, or objects created by them. (And in the latter case, as desired they can show either the data as of the time the method was called or the current values in primary.) This basically lets you slip information straight from primary to the caller without bothering with convenience methods.
Do this right and your code will be a lot easier to manage in this and other situations. But it is a lot of work, so if you know this the last thing you are going to do with this code, use one of the other solutions.

Categories

Resources