Using non-created classes in current class - java

Scenario
This question may be a question about conventions, but Java might have a built-in way to do this. I'm explaining my problem with a scenario:
We are three people working on a project, and we're all doing different parts, and working on different git branches, all of which will be needed in the end project.
My part of the program runs the TUI (let's call the class Startmenu), which requires to run functions from an instance of the Database class. In my switch cases, I know the future code from the other branch will allow me to simply run db.printElements(), as an example.
Problem
Nevertheless, this is the problem: I cannot define Database db; in the class structure, nor can I assign my Startmenu() constructor to take a Database db as an input such as Startmenu(Database db), because it does not yet exist.
In practice, how do I solve this issue? Currently, I'm commenting out the parts that require parts of the other code, and replace it with poisoned code instead, as a placeholder. This doesn't seem like the best idea.
I know a solution is to create the Database class, with empty functions for those functions I will be needing right now, but this will mess with git instead.
tl; dr: How can I prepare my own files to use code that does not yet exist, which will appear "magically" by other people over time?

All components in your project should have specified an interface to exchange information across layers and other Java components during the design phase.
You can early commit and share these interfaces, so other colleagues can provide their own testing implementations or mock behaviours.

Related

2 Classes with the same name, serving different purposes

The question I have is so weird that I couldn't even come up with a better title at the moment. Anyhow, I am looking for a way to name 2 classes but cannot figure out what would be the best way forward. I do understand this is an opinion based question but I'm stuck with this... so I would appreciate any opinion on this
Project: A
-> Class name: Call (This class will represent the call from one telephone to another) Other classes may/may not subclass this particular class and if so the name of these subclasses would probably relate somehow to the parent class (CallState, CallEndPoint, CallSomething). This Class will not know about the existence of the database, one could say this class will be part of the general telephony driver.
Project: B
-> Class name: Call? (This will represent the actual table in a database. The table will have some information about the call like call id, time it entered the system etc, but also other information that may/may not relate to the call). This class will serve essentially as a RowMapper.
Now, these 2 projects most likely will be combined down the line, and If I name the classes the same I would then end up with 2 same name classes in a single project serving 2 different purposes. Now if I was the only person to build this application I could probably digest this, but if multiple people start work on the application it will become confusing to others, especially if more classes will follow the same pattern.
I'm not entire sure what the question here is. Do you want to know if it's possible to give 2 classes the same name, or just whether it's a bad idea?
A convention that is often used for classes that are meant to model database entities, is to postfix the classname with Entity. So you could name the first class Call and the second CallEntity. This removes some ambiguity about the classes purposes. Most professional developers will also immediately make the assumption that the Entity class is supposed to represent something that is persisted.
However if you really insist on giving both classes the same name. That's perfectly possible, if you put them in separate packages. The package you put them in can also provide more clarity about the intent of the class. The first could be domain.model.Call, while the second could be domain.entity.Call
Hope this is somewhat helpful :)
Now, these 2 projects most likely will be combined down the line, and
If I name the classes the same I would then end up with 2 same name
classes in a single project serving 2 different purposes.
When inside a same application two classes with distinct responsibilities/data need to have the same simple name (that is without the package), you should indeed consider it as something to think of and very probably fix.
Of course you could define these classes in distinct packages but does it really solve your issue ? I don't think. It will make things less clear as client code could use the bad one and at each time developers manipulate/read Call in the code they have to wonder "which Call" they are currently copping with.
Today you have two distinct Call. With such permissive naming conventions, why not a new one in the future ?
Really, not a good idea.
The source of the problem is the way which you design your application.
You split the model in two pats : the agnostic persistence part in a class and the data persistence part in another class. It is a choice (that personally I avoid) but if you make this choice you have to go until the end : distinct clearly each class with a different name. This choice has to be visible and not hidden in a package name only.
For example :
Call (domain) and CallEntity (persistence) or in the reverse way CallDTO(domain) and Call(persistence)

JAVA refactoring using reflection

I am using a 3rd party API in few Java applications. They have updated few things in the latest version. We will have to update to the latest version and it needs corresponding changes from our code.
The changes are,
1) The interface and the abstract class name which we used to implement/extend has been changed. Also, the method names has been changed.
These are all just the name changes.
2) Need to annotate the class which implements these interfaces with #Service
3) Then need to add some new Java file and a property file.
4) We also have the abstract class which implements the 3rd part abstract class and then there are many concrete classes. So, few methods from the 3rd party abstract class is been overridden in our base abstract class which extends the base abstract class and few methods are there in the concrete abstract class.
I can do the refactoring through Eclipse IDE, but we dont prefer this.
I like this to be completely automated like running a script.
I tried with Java reflection to find all the concrete class of an Abstract class and rename the methods. Still, it looks risky.
Is there any other better approach?
It depends how much code you need to change, how long it takes to do each step and how many times you repeat the same refactoring.
If it is only a few hundred classes and/or simpler refactorings like rename class/interface can do most of the work, then do it by hand.
Otherwise if you really want to, you can try to write rules in a tool like AutoRefactor: https://github.com/JnRouvignac/AutoRefactor
Disclaimer: I am the author of AutoRefactor.
I remember reading somewhere that a programmer is someone who would rather spend 12 hours writing a script to automate a manual task than to spend 20 minutes actually doing that task.
I understand why you want to automate this - the API you're using is making life hard for its clients by renaming things. It's unusual for APIs to break compatibility with naming only - are you sure it's as simple as that?
My strong recommendation is to just bite the bullet and manually refactor. It will almost certainly take less time than automating the process, you'll identify further opportunities to improve your own application's design, and it's unlikely you will ever need to use the refactoring script again.
Unfortunately, I do not now the exact details of you situation. I can point some principles which can simplify life in future according to my experience.
Shortly, if you are using any 3rd party API, try to minimize it's propagation into your code. Hide the 3rd party code behind your own abstractions (interfaces) using patterns like Adapter, Facade etc.
So, in case the 3rd party code changes, you will make changes only in one place. This approach gives you extra freedom: if you'll decide to use another 3rd party API, it will be simple, because the major peace of your code will not touched. Also it is useful while testing: you can mock actual 3rd party functionality.
For example, suppose your project need to have persisting storage. So you can start from declaring interface like this:
interface IStorage {
void save(Model m);
Model load(int id);
}
This will allow you:
Make decision about storage provider (may be it will be MySQL or
MongoDB or simply just XML file on disk) more later.
Easily substitute one 3rd party API by another (for example change from file storage to DB).
Test you business logic easily by mocking this interface instead of use real storage.
Speed up development in case some modules (which another developers have to do) require working storage (they will just use
IStorage interface as if it is already implemented).

How to split a Java library source into two blocks, keeping one package?

We are creating an android library for use with Android. That means an Eclipse-like IDE and an Ant-like build process.
The nature of the library is that it has two distinct parts, representing different levels of abstraction - let's say 'upper' and 'lower'.
Assume, for the purposes of this question, that we need to call methods in one part from the other, but would like to keep those methods hidden from the library user. I've scoured the usual references but they all stop at the point of explaining package name conventions and scope rules. I've failed to find anything that answers this on SO, though this was useful.
The immediate solution is to simply have everything in one package and for those methods to be package-private. However, for reasons of maintainability, clarity, and not-having-100-files-in-one-folder we'd prefer to split the parts into different folders.
The obvious splitting point is to split the (let's say 'wibble') package into com.me.wibble.upper and com.me.wibble.lower packages/folders, but that makes any interconnecting methods undesirably public. In mitigation they could be hidden from the javadoc with #hide.
Another thought is whether could we split the parts at the top level and instead of the classic /main and /test folders have /upper, /lower and /test and all parts share the same com.me.wibble namespace. I'm unsure if/how Eclipse would cope with that.
Is there a conventional way of doing this, or is it just not done? If there are ways, what are the pro's and con's?
hmmm......Instead of asking for the solution, sometimes it is better to give the question. WHY you want library users to have a restricted view may generate a better answer than the HOWTO. There are a few answers I thought of but didn't give because I don't know the motivation behind the question (I don't want to waste your time with an answer that is not applicable).
/upper,/lower/,/test doesn't make your situation any nicer. It just makes the project more organized. Whether they are all in the same folder or separate it doesn't affect much.
It sounds like you need public 'interfaces' for library users while having private 'interfaces' for your own use. This is possible with hacking but can be painful if this is large pre-existing collection of code.

need design/pattern/structure help on coding up a java 'world'

I've always wanted to write a simple world in Java, but which I could then run the 'world' and then add new objects (that didn't exist at the time the world started running) at a later date (to simulate/observe different behaviours between future objects).
The problem is that I don't want to ever stop or restart the world once it's started, I want it to run for a week without having to recompile it, but have the ability to drop in objects and redo/rewrite/delete/create/mutate them over time.
The world could be as simple as a 10 x 10 array of x/y 'locations' (think chessboard), but I guess would need some kind of ticktimer process to monitor objects and give each one (if any) a chance to 'act' (if they want to).
Example: I code up World.java on Monday and leave it running. Then on Tuesday I write a new class called Rock.java (that doesn't move). I then drop it (somehow) into this already running world (which just drops it someplace random in the 10x10 array and never moves).
Then on Wednesday I create a new class called Cat.java and drop that into the world, again placed randomly, but this new object can move around the world (over some unit of time), then on Thursday i write a class called Dog.java which also moves around but can 'act' on another object if it's in the neighbour location and vice versa.
Here's the thing. I don't know what kinda of structure/design I would need to code the actual world class to know how to detect/load/track future objects.
So, any ideas on how you would do something like this?
I don't know if there is a pattern/strategy for a problem like this, but this is how I would approach it:
I would have all of these different classes that you are planning to make would have to be objectsof some common class(maybe a WorldObject class) and then put their differentiating features in a separate configuration files.
Creation
When your program is running, it would routinely check that configuration folder for new items. If it sees that a new config file exists (say Cat.config), then it would create a new WorldObject object and give it features that it reads from the Cat.config file and drops that new object into the world.
Mutation
If your program detects that one of these item's configuration file has changed, then it find that object in the World, edit its features and then redisplay it.
Deletion
When the program looks in the folder and sees that the config file does not exist anymore, then it deletes the object from the World and checks how that affects all the other objects.
I wouldn't bet too much on the JVM itself running forever. There are too many ways this could fail (computer trouble, unexepected out-of-memory, permgen problems due to repeated classloading).
Instead I'd design a system that can reliably persist the state of each object involved (simplest approach: make each object serializable, but that would not really solve versioning problems).
So as the first step, I'd simply implement some nice classloader-magic to allow jars to be "dropped" into the world simulation which will be loaded dynamically. But once you reach a point where that no longer works (because you need to modify the World itself, or need to do incompatible changes to some object), then you could persist the state, switch out the libraries for new versions and reload the state.
Being able to persist the state also allows you to easily produce test scenarios or replay scenarios with different parameters.
Have a look at OSGi - this framework allows installing and removing packages at runtime.
The framework is a container for so called bundles, java libraries with some extra configuration data in the jars manifest file.
You could install a "world" bundle and keep it running. Then, after a while, install a bundle that contributes rocks or sand to the world. If you don't like it anymore, disable it. If you need other rocks, install an updated version of the very same bundle and activate it.
And with OSGi, you can keep the world spinning and moving around the sun.
The reference implementation is equinox
BTW: "I don't know what kinda of structure/design" - at least you need to define an interface for a "geolocatable object", otherwise you won't be able to place and display it. But for the "world", it really maybe enough to know, that "there is something at coordinates x/y/z" and for the world viewer, that this "something" has a method to "display itself".
If you only care about adding classes (and not modifying) here is what I'd do:
there is an interface Entity with all business methods you need (insertIntoWorld(), isMovable(), getName(), getIcon() etc)
there is a specific package where entities reside
there is a scheduled job in your application which every 30 seconds lists the class files of the package
keep track of the classes and for any new class attempt to load class and cast to Entity
for any newlly loaded Entity create a new instance and call it's insertIntoWorld().
You could also skip the scheduler and automatic discovery thing and have a UI control in the World where from you could specify the classname to be loaded.
Some problems:
you cannot easily update an Entity. You'll most probably need to do some classloader magic
you cannot extend the Entity interface to add new business bethod, so you are bound to the contract you initially started your application with
Too long explanation for too simple problem.
By other words you just want to perform dynamic class loading.
First if you somehow know the class name you can load it using Class.forName(). This is the way to get class itself. Then you can instantiate it using Class.newInstance(). If you class has public default constructor it is enough. For more details read about reflection API.
But how to pass the name of new class to program that is already running?
I'd suggest 2 ways.
Program may perform polling of predefined file. When you wish to deploy new class you have to register it, i.e. write its name into this file. Additionally this class has to be available in classpath of your application.
application may perform polling of (for example) special directory that contains jar files. Once it detects new jar file it may read its content (see JarInputStream), then call instantiate new class using ClaasLoader.defineClass(), then call newInstane() etc.
What you're basically creating here is called an application container. Fortunately there's no need to reinvent the wheel, there are already great pieces of software out there that are designed to stay running for long periods of time executing code that can change over time. My advice would be to pick your IDE first, and that will lead you someways to what app container you should use (some are better integrated than others).
You will need a persistence layer, the JVM is reliable but eventually someone will trip over the power cord and wipe your world out. Again with JPA et al. there's no need to reinvent the wheel here either. Hibernate is probably the 'standard', but with your requirements I'd try for something a little more fancy with one of the graph based NoSQL solutions.
what you probably want to have a look at, is the "dynamic object model" pattern/approach. I implemented it some time ago. With it you can create/modify objecttypes at runtime that are kind of templates for objects. Here is a paper that describes the idea:
http://hillside.net/plop/plop2k/proceedings/Riehle/Riehle.pdf
There are more papers but I was not able to post them, because this is my first answer and I dont have enough reputation. But Google is your friend :-)

Where to put business logic in Eclipse RCP program

I'm writing a small application in RCP to wrap around the business logic in another (non-RCP) simulation library. I can access and use the library fine from any of my plugins, but I don't know where I should put the instance of the Simulation library so that, say, one of the command handlers can make calls to it.
From reading the docs it sounds like I should be storing 'global' information like this in the workbench - but I still don't really understand how to do that.
Help?
First, the business layer (BL) can and should reside in its' own plugin. That will provide decent decoupling between the layers.
Second, you should carefully decide what the interface should be and which classes are exposed. Ideally, you should mostly expose interfaces and data objects.
Finally, decide how the "hand shake" works. E.g., how to obtain the initial interface to the BL. Since it is a Plugin, it could have an Activator which loads it. You could add a method in the activator which returns the BL interface.
If you are looking for something more decoupled, you could create an extension point or deploy the BL as an OSGi service, but that's a bit of an overkill for you need.
If I understand you correctly, I see two ways:
Store the instance in the model plug-in itself, using ‘SimulationFactory.getInstance(String myAppId)‘. The passed String is a constant in you app that is always used, when obtaining the reference.
Define a new class e.g. GlobalAccess in you app that is initilized with an instance of your model and has some getter (whether you use a single instance again or only provide public static methods is a matter of taste).
The seocond way is similar to some classes in eclipse like platfom or platformui, where you can obtain initial references and navigate through the workbench.
edit
i just found a tutorial that might help you:
Passing Data between Plug-ins

Categories