0

I have java two projects; one server project and one client project. In my network code between the two, I send requests. I don't want to type 0, 1, 2 for the different types of requests in the code, so I use constants instead. My problem is that I don't want to declare these constants in both projects, but rather at one place, since the constants are the same for both projects. Does anyone know a good solution for this?

Edit: The client project is an android application and the server is a servlet which should handle requests from clients.

Alle
  • 324
  • 4
  • 19

2 Answers2

6

Create a library project with an Interface. This interface declares the constants. Share this library in both projects. If you use some dependency management as in maven this is quite easy.

EDIT:

Using a final Class as described in http://en.wikipedia.org/wiki/Constant_interface is better! But the core is, to use a library project and share the common part of both projects in a separate jar.

ollins
  • 1,851
  • 12
  • 16
  • Doing this is a bad practice, see _Constant Interface Antipattern, Effective Java, Item 17_ – Kai May 06 '12 at 10:20
  • ... or [this question](http://stackoverflow.com/questions/2659593/what-is-the-use-of-interface-constants) – Kai May 06 '12 at 10:28
  • @user714965 Only **implementing** that interface is bad practice, really. But writing a final, noninstantiable class is still better as it makes it impossible to do the bad thing. – Marko Topolnik May 06 '12 at 10:44
  • Yes, using a interface to define the constants is not the best thing, I know. But the core point is to use a lib and share this lib. Alternatives: http://en.wikipedia.org/wiki/Constant_interface – ollins May 06 '12 at 10:47
  • Ah, thanks everyone, I'll try to make a library project and use the final class. – Alle May 06 '12 at 11:03
  • I would create an enum with no instances. This is implicitly final with a private constructor. Some consider this a hack. ;) – Peter Lawrey May 06 '12 at 11:03
0

I don't know about your architecture but if the client makes calls to the server you have a dependency here already.

So you should add the server project as a dependency in your client project. Then you can define a class (or maybe an enum in your case) in the server project which contains the constants. This is where it belongs as the server provides those method.

Kai
  • 38,985
  • 14
  • 88
  • 103