I need to have couple global variables (eg: database name) which will be used by some other classes across my program.
I can create a Singleton class with the variables inside, but what I have found is that I can simply create an interface with the variables (without any methods) as well. As the variables in interface are static and final this seems to be a clean implementation.
I read thought that declaring variables in interfaces are poor design, so why is that and what is the best way to create global variables?
Using an interface only to hold constants is a code smell, according to Sonar rule:
Constants should not be defined in interfaces (squid:S1214)
According to Joshua Bloch, author of "Effective Java":
The constant interface pattern is a poor use of interfaces.
That a class uses some constants internally is an implementation detail.
Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface,
all of its subclasses will have their namespaces polluted by the constants in the interface.
Related
As Java 9 is going to allow us to define private and private static methods too in interfaces, what would be the remaining difference in interface and class?
Moreover, is Java moving towards multiple inheritance slowly?
Private interface methods in Java 9 behave exactly like other private methods: They must have a body (even in abstract classes) and can neither be called nor overridden by subclasses. As such they do not really interact with inheritance. Talking of which (and particularly multiple inheritance), there are (at least?) three kinds of it:
Inheritance of types means that one type can be another type, e.g. String is an Object. Java allowed multiple inheritance of types from day one (via interfaces).
Inheritance of behavior means that one type can inherit the behavior of another type. Before Java 8, only classes could implement methods, so there was only single inheritance of this kind. With Java 8 came default methods, which allowed interfaces to implement methods, thus giving Java multiple inheritance of behavior.
Inheritance of state means that a type inherits another type's internal state (i.e. fields). As it stands (Java 9 and everything currently proposed for future Java versions), only classes can have state, so there is only single inheritance of this kind.
As you can see private interface methods do not add anything here.
Regarding your question of how interfaces and classes compare, there are two main differences: multiple inheritance and state. Interfaces support the former, classes can have the latter. Since state is kind-of important in typical OOP, classes will remain relevant. 😉
If there were a way for an interface to force an implementation to have a particular non-public field or straight-out define one itself, the game would change and interfaces could compete with classes.
Private methods are not inherited by subclasses, so this feature doesn't affect implementation classes. I believe the private methods in interfaces allow us to share code between default methods.
Java interfaces still cannot have non-static members. That's a big difference and not multiple inheritance IMO.
Java 9 interfaces still cannot contain fields and constructors. This makes a huge difference between classes and interfaces, so Java 9 is far from multiple inheritance.
Java Interface in version 9 have private methods but static private. The feature has been introduced to allow modular methods. One function should work with one responsibility instead of using lengthy default methods. It has nothing to do with multiple Inheritance. The more private static methods, the more you will be able to write the clean and reusable code. Anyways, static methods whether public or protected can not be overridden.
Although its an old question let me give my input on it as well :)
abstract class: Inside abstract class we can declare instance
variables, which are required to the child class
Interface: Inside interface every variables is always public static
and final we cannot declare instance variables
abstract class: Abstract class can talk about state of object
Interface: Interface can never talk about state of object
abstract class: Inside Abstract class we can declare constructors
Interface: Inside interface we cannot declare constructors as purpose of
constructors is to initialize instance variables. So what
is the need of constructor there if we cannot have instance
variables in interfaces.
abstract class: Inside abstract class we can declare instance and static blocks
Interface: Interfaces cannot have instance and static blocks.
abstract class: Abstract class cannot refer lambda expression
Interfaces: Interfaces with single abstract method can refer lambda expression
abstract class: Inside abstract class we can override OBJECT CLASS methods
Interfaces: We cannot override OBJECT CLASS methods inside interfaces.
I will end on the note that:
Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.
I have a question regarding the design of my program. I have a class A that stores public constant so that i can use these constants in another class.
public static final String error_code1 = "Fatal Error";
public static final String error_code2 = "XXXX";
...
...
Between Composition vs Interface, i dont know which 1 is more suitable. From what i think, since i only need the constants for value-comparing in my program, so i think composition is enough (low coupling).
But can you guys give me some advice/arguments from software deign point of view? (cohesion, coupling, difficulties of maintenance, etc )
First of all I'd recommend you to use an enum for this case.
public enum ErrorCode {
FATAL_ERROR("Fatal Error"),
X_ERROR("XXXX");
public final String msg;
private ErrorCode(String msg) {
this.msg = msg;
}
}
If this doesn't suit you for some reason, I'd go with a final utility class with private (unused) constructor.
Regardless, since the fields are static and final, I would not consider having a reference to A or implement A to get hold of the constants.
Adding constants to interfaces is considered an anti-pattern since the primary purpose of an interface is to define behavior contracts. Use either an enum or access them directly since they are public.
I wouldn't use interface to store constant as having static members into an interface (and implementing that interface) is a bad practice and there is even a name for it, the Constant Interface Antipattern, see [Effective Java][1], Item 17:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
I would personally go for enum and if needed i could even use it to have error code or add relevant field/method as well.
String/int/... constants in another class have one problem: they are copied into the using class' constant pool, and after that no import to the original class exists. Should you then alter a constant's value, the using class is not forced to be recompiled.
The solution would be to use an interface, and "implement" that interface; ugly maybe.
Better is to use an enum.
For open ended value domains one would not use an enumeration, but an object oriented approach:
abstract class ParseError extends RuntimeException
class ExpressionExpectedError extends ParseError
class DigitsMayNotFollowLeadingZeroError extends ParseError
..
In the javadoc one might see all child classes of ParseError. Here the classes themselves form the domain values, and an instantiation bears the actual context information. That is more OOP. Calling several methods on an object is better than having several switches on constants. An enum however may be used with categorical method too: boolean errorHandledBySkippingToNextExpr().
In his book Effective Java, Joshua Bloch recommends against using Interfaces to hold constants,
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class’s exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the con-stants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
His reasoning makes sense to me and it seems to be the prevailing logic whenever the question is brought up but it overlooks storing constants in interfaces and then NOT implementing them.
For instance,
public interface SomeInterface {
public static final String FOO = "example";
}
public class SomeOtherClass {
//notice that this class does not implement anything
public void foo() {
thisIsJustAnExample("Designed to be short", SomeInteface.FOO);
}
}
I work with someone who uses this method all the time. I tend to use class with private constructors to hold my constants, but I've started using interfaces in this manner to keep our code a consistent style. Are there any reasons to not use interfaces in the way I've outlined above?
Essentially it's a short hand that prevents you from having to make a class private, since an interface can not be initialized.
I guess it does the job, but as a friend once said: "You can try mopping a floor with an octopus; it might get the job done, but it's not the right tool".
Interfaces exist to specify contracts, which are then implemented by classes. When I see an interface, I assume that there are some classes out there that implement it. So I'd lean towards saying that this is an example of abusing interfaces rather than using them, simply because I don't think that's the way interfaces were meant to be used.
I guess I don't understand why these values are public in the first place if they're simply going to be used privately in a class. Why not just move them into the class? Now if these values are going to be used by a bunch of classes, then why not create an enum? Another pattern that I've seen is a class that just holds public constants. This is similar to the pattern you've described. However, the class can be made final so that it cannot be extended; there is nothing that stops a developer from implementing your interface. In these situations, I just tend to use enum.
UPDATE
This was going to be a response to a comment, but then it got long. Creating an interface to hold just one value is even more wasteful! :) You should use a private constant for that. While putting unrelated values into a single enum is bad, you could group them into separate enums, or simply use private constants for the class.
Also, if it appears that all these classes are sharing these unrelated constants (but which make sense in the context of the class), why not create an abstract class where you define these constants as protected? All you have to do then is extend this class and your derived classes will have access to the constants.
I don't think a class with a private constructor is any better than using an interface.
What the quote says is that using implements ConstantInterface is not best pratice because this interface becomes part of the API.
However, you can use static import or qualified names like SomeInteface.FOO of the values from the interface instead to avoid this issue.
Constants are a bad thing anyway. Stuffing a bunch of strings in a single location is a sign that your application has design problems from the get go. Its not object oriented and (especially for String Constants) can lead to the development of fragile API's
If a class needs some static values then they should be local to that class. If more classes need access to those values they should be promoted to an enumeration and modeled as such. If you really insist on having a class full of constants then you create a final class with a private no args constructor. With this approach you can at least ensure that the buck stops there. There are no instantiations allowed and you can only access state in a static manner.
This particular anti-pattern has one serious problem. There is no mechanism to stop someone from using your class that implements this rouge constants interface.Its really about addressing a limitation of java that allows you to do non-sensical things.
The net out is that it reduces the meaningfulness of the application's design because the grasp on the principles of the language aren't there. When I inherit code with constants interfaces, I immediately second guess everything because who knows what other interesting hacks I'll find.
Creating a separate class for constants seems silly. It's more work than making an enum, and the only reason would be to do it would be to keep unrelated constants all in one place just because presumably they all happen to be referenced by the same chunks of code. Hopefully your Bad Smell alarm goes of when you think about slapping a bunch of unrelated stuff together and calling it a class.
As for interfaces, as long as you're not implementing the interface it's not the end of the world (and the JDK has a number of classes implementing SwingConstants for example), but there may be better ways depending on what exactly you're doing.
You can use enums to group related constants together, and even add methods to them
you can use Resource Bundles for UI text
use a Map<String,String> passed through Collections.unmodifiableMap for more general needs
you could also read constants from a file using java.util.Properties and wrap or subclass it to prevent changes
Also, with static imports there's no reason for lazy people to implement an interface to get its constants when you can be lazy by doing import static SomeInterface.*; instead.
I faced with a sample code in Java and it brought me a question.
Java sample code is:
...
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
void printf(String format, Object... args);
}
public static void main(String[] args) throws IOException {
CLibrary.INSTANCE.printf("Hello, World\n");
}
But in C# we cannot write like that:
public interface IMyInterface {
static readonly int staticInt = 5; // compile error
static readonly SomeClass staticInstance = new SomeClass(); // compile error
}
What is the difference between these two languages/frameworks?
What design policy permit java to have const fields in an interface or what prevents .NET from having that?
The use of interfaces to hold constants is usually frowned on these days in Java too. (I'd say that storing non-compile-time-constant fields like your example is even more frowned upon.)
Fundamentally, it's at odd with the idea of an interface: a contract that the implementation will uphold. The implementation isn't going to provide the field, so what's it doing there?
I suspect the C# team decided that it was sufficiently at odds with the concept behind interfaces to not include it in the language. I don't know whether it's just a C# restriction or a CLR restriction too. For example, I know that the CLR allows interfaces to declare nested types, but C# doesn't currently allow this.
In C#:
Interfaces consist of methods,
properties, events, indexers, or any
combination of those four member
types. An interface cannot contain
constants, fields, operators, instance
constructors, destructors, or types.
It cannot contain static members.
Interfaces members are automatically
public, and they cannot include any
access modifiers.
In Java:
Every field declaration in the body of
an interface is implicitly public,
static, and final.
Every field in the body of an
interface must have an initialization
expression, which need not be a
constant expression. The variable
initializer is evaluated and the
assignment performed exactly once,
when the interface is initialized.
In Java, all fields in an interface are implicitly static and final.
But its considered bad practice. To qoute Joshua Bloch from Effective Java:
The constant interface pattern is a
poor use of interfaces. That a class
uses some constants internally is an
implementation detail. Implementing a
constant interface causes this
implementation detail to leak into the
class's exported API. It is of no
consequence to the users of a class
that the class implements a constant
interface. In fact, it may even
confuse them. Worse, it represents a
commitment: if in a future release the
class is modified so that it no longer
needs to use the constants, it still
must implement the interface to ensure
binary compatibility. If a nonfinal
class implements a constant interface,
all of its subclasses will have their
namespaces polluted by the constants
in the interface.
As to why it is considered bad practice, I think a class implementing an interface with constant fields is exposing these in the interface to outside code which consumes this class which in most cases is not what is required.
I guess COM's Microsoft Interface Description Language does not allow it. So it's just an adaptation for the Windows environment, much like prefixing interface names with I.
Like most questions of this form, the question is basically pointless. It's not like the designers of Java and C# had a meeting about it. Historically Java came first so you would really have to ask the designers of C#, not that the question would necessarily make sense to them either. It's just how they saw it at the time.
I think it's weird that Java chose to allow this.
An interface is a contract for a Role. That is, it's an spec that all objects must implement in order to be considered as suitable/swappable candidates for that Role. It should contain the messages/methods that the Role responds to and the notifications that it triggers for interested listeners.
Fields are an implementation detail (and your example contains actual implementation dictating the return value for the INSTANCE field too) and do not belong within the contract. If you wanted to map this to C#, you should probably move it to an abstract base class, which allows default implementation to be specified in addition to specifying some members that derived classes must also implement.
In Effective Java, Item 17, Josh Bloch argues that putting static members into an interface (and implementing that interface) is a bad practice known as the Constant Interface Antipattern:
The constant interface pattern is a poor use of interfaces. That a class
uses some constants internally is an
implementation detail. Implementing a
constant interface causes this
implementation detail to leak into the
class's exported API. It is of no
consequence to the users of a class
that the class implements a constant
interface. In fact, it may even
confuse them. Worse, it represents a
commitment: if in a future release the
class is modified so that it no longer
needs to use the constants, it still
must implement the interface to ensure
binary compatibility. If a nonfinal
class implements a constant interface,
all of its subclasses will have their
namespaces polluted by the constants
in the interface.
There are several constant interfaces in the java platform
libraries, such as
java.io.ObjectStreamConstants. These
interfaces should be regarded as
anomalies and should not be emulated.
I'm pretty confident I understand the reasoning behind this and completely agree.
My question is: is grouping related constants (note: these are NOT suitable for an enum, consider the math example of the related constants pi and e) in an interface versus a non-instantiable class a good idea, provided you only access the values via static references and static imports, keep the interace hidden from your API w/ a default access modifier, and never actually implement the interface?
Why or why not? Are there any advantages are there to grouping them in a class other than being able to use a private constructor to ensure the constant grouping type is never instantiated?
Let's put it the other way. There is no advantage of using interfaces for constants. As you know, interfaces are for defining contracts, not for constants. I don't see the problem of changing the interface keyword to class keyword and using public static final fields for example. Using interfaces for keeping constants is never a good idea. I think people use this anti-pattern because they don't know about static imports(it was introduced in Java 5.0) or they are too lazy to dispatch their constants in the appropriate classes. Instead they just create one interface and let every class implement it.
Edit: By the way the question sounds me like - Is it a good idea to watch television, looking at the neighbourhood's TV using a telescope, provided the seeing is good. The answer is simple - no, the telescope is invented for other things. Ah, and I know this example is dumb:)