Sharing Code Between Projects

Firstly, I think I’ve posted this in the most relevant category, it would have fit in development too, feel free to move it if you want.

Right, I’m making a game that has seperate server and client programs. However there’s a lot of shared code between the two. At the moment this exists as duplicate code. IE two of the same java file, one in each project.

I’d just like to know how I can share code between programs. I’ve tried making a third project and including this as a library in the other two but I’m not exactly sure how to do this. I obviously need to be able to reference the same code from both projects.

I may even be able to put it all in seperate source packages in the same project and compile them seperately? I really don’t know.

I’m fairly new to java development and I have tried Googling. Any help is much appreciated.



Question is always how your code is organized and looks. Theres no “right” way to implement a software (but there are many wrong ways, I give you that ;)) MonkeyZone is for example a game that has one class for server and client management of entities. This is possible as the same data (about the “world content”) needs to be available on both client and server.

If you modularized your code using Controls and AppStates as suggested you can re-use much of the code by maybe even separating certain functions of one AppState in a separate AppState so that can be used on server and client.

Another good way to re-use code in games is the entity-component-system way of doing things, although its a bit counter-intuitive for people used to OOP at first, see this link for a good article on this topic.

Edit: Oh, and if the question is just “how do I add the jar file from one project I compile to another” then this video answers your question:

The problem with doing that though is that the server program would still be included in the client binary. I don’t want to distribute the server, just the client.

Do I put my server code in a seperate project like I have been doing?

Just a new package?

Like you said, it’s world data etc that I want to share, and in my case I’d like to share assets too.

I just need the ability to compile two seperate programs with some of the same code.

Thanks for your reply.

Theres multiple ways. As it seems you don’t really have a clear idea where to draw the line code-wise so I would not start thinking about deployment already, just do everything in one project for now. Later when its clearer you have multiple options: Move your code to a separate library project or just modify the build.xml of the main project to create 2 jar files (requires a bit of ANT magic, but its good to learn ANT anyway since its the default build system for java, like “make” for c/c++).

I know which code will be totally shared if that’s what you meant?

Anyway I’ll do a bit more experimentation and have a look at ANT.

Thanks for your help, I’ll let you know how it goes.