Related
I have lot of static/constant data which I want to store, this data is also related with each other. I can use lot enums referencing each other forming a tree or a graph. Or simply use tables or database enums and store values in them and create corresponding classes and respective relationships. The data I have is constant and is certainly not going to change. I might have to also consider internationalization in near future. I will be using this constant data as filter to various other data.
I am tempted to use enums as it gives me immutability by default, but seeing the complexity of relationship between data, like I might have to sacrifice with inheritance, I am also little apprehensive of enums. And populating these enum classes from database and internationalization might be little more tricky. And at later stage hoping that it will scale and embrace the complexity with ease are the areas of concern as I would not like to revert from the mid way.!
---Update---
I have not seen examples of enums related(associations) with each other, containing fields of complex types referencing other enums. Can in this type of cases enums replace classes when data is constant.
Is there any objective way to look at this problem.
To understand better, I have similar classification like below.
Animal Kingdom having tree hierarchy
While this Question is likely too broad for Stack Overflow, a few thoughts.
Enums
You may not fully understand the enum facility in Java. See the Oracle Tutorial, and see the Enum class doc.
An enum is a class, a regular Java class, a subclass of Enum. The only thing special is that syntactic sugar that automatically instantiates the static instances you define and name. Otherwise, they are normal classe:
Your enums can carry member variables.
Your enums can have constructors, and you can pass arguments to those constructors.
Your enums can offer other methods, and you can pass arguments to those methods.
You can even pass instances of one enum as arguments to methods of another enum’s instances – just as you might pass instances of an enum to instances of other non-enum classes. Each enum instance is just an object, plain and simple, saved as a static reference on the enum-defining class.
Example:
public enum Food { HERBIVORE, OMNIVORE, CARNIVORE ; } // Syntactic sugar for automatically instantiating these named static instances of this class type.
…and…
public enum Animal {
RABBIT( Food.HERBIVORE ) ,
DOG( Food.OMNIVORE ) ,
CAT( Food.CARNIVORE ) ;
// Member variables.
public Food eats ;
// Constructor
Animal( Food foodType ) {
this.eats = foodType ; // Assign an instance of another enum to this instance of this enum.
}
}
Limitations of enums
While more powerful and useful than in other languages, there are limitations.
Compile-time
Firstly, enums are defined at compile-time. If your values change at runtime, perhaps you want to add or delete items, then enums are not appropriate.
Permanently in memory
Also, enums are static. This means when first used, all the objects of that enum class are instantiated immediately and held in memory throughout the execution of your app. So they are never retired from memory until program ends. So having an enormous number of them might be a burden on memory.
Understand that your can collect enum instances. See the EnumSet and EnumMap classes for fast-to-execute and low-memory usage collections of enum instances. Search Stack Overflow for much coverage on this topic. And be aware that every enum carries a values() method that returns an array of its values, yet this method is mysteriously not listed in the JavaDoc.
As for your mention inheritance, your enums by definition are subclasses of Enum class. So they cannot inherit from any other class you may have in mind, as Java does not support multiple-inheritance. Your enums can implement one or more interfaces. In later version of Java, an inheritance can carry implementation code by way of new default methods, so you can pass along some code that way.
Internationalization
Internationalization and localization seems to be an orthogonal issue. You can add a method on your enum to generate localized String representation of their value. As an example, see DayOfWeek::getDisplayName and Month::getDisplayName enum methods.
Database
If you want to dynamically define your values at runtime, or you have zillions of them, then a database is the way to go. A serious database such as Postgres is designed to manage memory, handle concurrency, and execute efficiently.
You can even combine enums with the database. For example, localization. You might have enum values defined at compile-time, but their getDisplayName method does a lookup into a database to find the French or Arabic translation. That translation value in the database can be updated during runtime by running SQL INSERT or UPDATE commands via JDBC.
Recursive hierarchical relationships
If you are trying to represent relationships of a hierarchy of arbitrary depth, that is a whole other topic I'll not address here other than to say that is often implemented with recursion. Search Stack Overflow and other sources to learn more.
As a rule of thumb, I only involve a database when the values are likely to change faster than code release cycles, and when it's possible or likely that someone who is not me is going to change them. Making the code depend on a running (and available) database means that when some DBA takes the database down for maintenance then your application can't be started.
Context: I believe that object creation and management in Java has a cost that we should bear in mind while programming. However, I don't know how big that cost is. Hence my question:
I have multiple functions that share the same arguments:
detectCollision(ArrayList<Mobile>, ArrayList<Inert>, double dt)
updatePositions(ArrayList<Mobile>, double dt)
etc.
As I see it, there are two ways to organize them (see code below):
define (possibly static, but not necessarily) methods and forward the arguments for each call
create a temporary object with private member variables and remove argument list.
Note that the Mover object has no private internal state and is just a bunch of algorithms that use the arguments ArrayList<Mobile>, ArrayList<Inert>, double dt.
Question: Which approach is the prefered one ? Does it have a cost ? Is there a more standard alternative ?
Here is a snippet illustrating the first point:
public class Mover{
public static void updatePositions(ArrayList<Mobile>, double dt){...}
/* remove the static keyword if you need polymorphism, it doesn't change the question */
public static Collisions detectCollision(ArrayList<Mobile>, ArrayList<Inert>, double dt){...}
//etc.
}
Here is a snippet illustrating the second point:
public class Mover{
public Mover(ArrayList<Mobile>, ArrayList<Inert>, double dt){...}
public void updatePositions(){...}
public Collisions detectCollision(){...}
//etc.
private ArrayList<Mobile> mobiles;
private ArrayList<Inert> inerts;
//etc.
}
I'd recommend you to go with the second variant. Besides the good readability it will also allow you to extend the class later (see SOLID -> open / closed principle). In general, I'd never create such utility classes, as it is not OOP (OOP Alternative to Utility Classes).
While I think that static utility methods are not necessarily a Bad Thing™, you should be aware of the semantics of these methods. One of the most important points here is that static means that a method may not take part in any form of polymorphism. That is: It may not be overridden.
So regarding the design, the second option offers a greater degree of flexibility.
A side note: Even if you choose the second approach, you might eventually dispatch to a (non-public) static method internally:
class Mover {
private final List<? extends Mobile> mobiles;
public void updatePositions(){
MyStaticUtilityMethods.updatePositions(this.mobiles);
}
}
Note that I'm not generally recommending this, but pointing it out as one option that may be reasonable in many cases.
It might be off-topic, but there is another degree of freedom for the design here. You could (and at least should consider to) go one step further: As far as one can guess (!) from the method names, you might consider having interfaces PositionUpdater and a CollisionDetector. Then you could store instances of classes implementing these interfaces inside your Mover class, and dispatch the actual call to these. This way, you can easily combine the different aspects of what comprises a "Mover".
(I know, this does not answer the actual question. In fact, it just "defers" it to whether the PositionUpdater should receive the data as arguments, or receive them at construction time...)
You could then assign instances of different implementations of the PositionUpdater interface to a Mover instance. For example, you could have concrete classes called LinearMovementPositionUpdater and RandomWalkPositionUpdater. Passing instances of these classes (which are both implementing the PositionUpdater interface) to the Mover allows you to change one aspect of the implementation of a Mover - basically, without touching any code! (You could even change this at runtime!).
This way, the responsibilities for
updating the positions
detecting the collisions
are clearly encapsulated, in view of several of the SOLID principles that already have been mentioned in another answer.
But again: This is just a hint. Judging whether this approach is actually sensible and applicable in one particular case is what software engineers get all the $$$ for.
The problem you're having here is mostly due to having an orchestrated model (and which probably has an anaemic domain model to accompany it).
If instead you use an event driven approach these methods would simply disappear and be replaced by event handlers each of which would respond to the appropriate events independently of the other, taking whatever information they need from the initial event.
This means that you wouldn't have to deal with passing parameters or working out which parameters to pass -- each 'handler (method)' would know what it needs and would take it, rather than having to have an external orchestrator understand what data is needed and pass it in.
The orchestrator model breaks encapsulation by having it 'know' about the information needs of the components it is orchestrating.
Now, this isn't a java specific problem. It applies to most modern object-oriented languages. It doesn't matter if you're doing java, c-sharp, or c++. It's a general pattern.
To break away from this thinking, read about DDD (Domain Driven Design) and Event Sourcing.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am maintaining some Java code that utilizes an interface (let's call it BunchOfConstants) to simply store an abundance of public static final Strings. Occasionally these string names change or string names are added / removed. (which causes a bit of a headache for maintanance)
The only current use for this interface is to compare to input later in a big ugly if/then construct like this:
if(BunchOfConstants.CONSTANT1.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT2.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT3.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}
...
I thought it would be more elegant to create a class that implements Iterable or even a class that stores this data in a hashMap.
I can not figure out why the original developers decided to use an interface for this design as the interface is never actually implemented anywhere. Does anyone have any input?
Would you agree that an iterable class with these members as constants would be more appropriate?
Use enums. Then get myenum.values() and then apply a for-each loop over the values.
I would consider using enums instead as constants are not type safe (e.g., they are just ints, or strings, etc.).
This (having dedicated interface for storing constants) was a fairly common way of storing constants before the era of enums. (Pre Java 5 times.) It saved you the hassle of prefixing your constants with the containing class name. I personally never really liked this practice, but this is the reason people did it.
As for what it can be replaced with:
An enum and a switch/case construct. This requires the least modification but only has modest benefits in readability. It does give you type and value safety, plus you can get warnings out of your IDE if you forget to handle a possible value (no case for it and no default block either).
A properties file. This obviously only works if you don't want to branch based on your constant values. (I.e. if your constants don't have to appear in your source code.) This is important, otherwise you'd end up with a secondary set of constants and a properties file, which is as bad as it gets.
A doSomeStuff() factory. For this you have to wrap your doSomeStuff() implementations in separate operation classes and you can configure your factory either statically or from a properties file. (via a constant value->operation class mapping). This is the most "enterprisey" solution, which means that although it looks nice and is very flexible, a lot of the time it is an overkill.
I think this is a good candidate for enum
Well, this looks like the Constant Interface antipattern and maybe should not be used. Using an enum might be a way as suggested, or at least using a final class with private constructor.
If you want to have different implementations for doSomeStuff based on the input string, you might also consider using the strategy pattern, i.e. have a Map<String, Strategy> and then lookup the strategy for whatImLookingFor. If you found the strategy, execute its doSomeStuff, otherwise handle the "not found" case.
I would suggest you to use a property file to store all your constants. This way you can load your properties into a HashMap as you suggest in your question.
Note that property support is brought natively with java: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Properties.html
Well, enums are the way to go ... but if the 'dosomestuff' is semantically dependent upon the specific value then why not add a 'dosomestuff' method to the enum itself. That is one that this is really great about Java enums - they are not merely data but as all good objects they have semantics. Then you just loop over the enums invoking dosomestuff(whatIamLookingFor) and whatever happens happens.
Hard to say.
Yes, I agree, that it will be more elegant - at least for you. But think, what the next programmer will think about it. It will be even more complicated.
Previously mentioned strategy pattern and java's enum are definitely better solution, but since you are maintaining this code, I'm not sure if your boss will be happy with time consuming refactoring. My advice would be to use enums - not so big code change.
This question already has answers here:
Interface naming in Java [closed]
(11 answers)
Closed 7 years ago.
How do you name different classes / interfaces you create?
Sometimes I don't have implementation information to add to the implementation name - like interface FileHandler and class SqlFileHandler.
When this happens I usually name the interface in the "normal" name, like Truck and name the actual class TruckClass.
How do you name interfaces and classes in this regard?
Name your Interface what it is. Truck. Not ITruck because it isn't an ITruck it is a Truck.
An Interface in Java is a Type. Then you have DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc that implements Truck.
When you are using the Interface in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just Hungarian style notation tautology that adds nothing but more stuff to type to your code.
All modern Java IDE's mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass that is tautology just as bad as the IInterface tautology.
If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions, could be something like AbstractTruck. Since only the sub-classes will ever see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck or DefaultTruck instead since the abstract is in the definition. But since Abstract classes should never be part of any public facing interface I believe it is an acceptable exception to the rule. Making the constructors protected goes a long way to crossing this divide.
And the Impl suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl suffix on every name of every Class?
The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.
Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No, you see List and ArrayList, and LinkedList. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principle as well.
Also, if you find yourself adding DTO, JDO, BEAN or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even internally adhere to in a consistent manner.
If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have a situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface in most cases.
However, in general for maintainability, testability, mocking, it's best practice to provide interfaces. See this answer for more details.
Also Refer this interesting article by Martin Fowler on this topic of InterfaceImplementationPair
I've seen answers here that suggest that if you only have one implementation then you don't need an interface. This flies in the face of the Depencency Injection/Inversion of Control principle (don't call us, we'll call you!).
So yes, there are situations in which you wish to simplify your code and make it easily testable by relying on injected interface implementations (which may also be proxied - your code doesn't know!). Even if you only have two implementations - one a Mock for testing, and one that gets injected into the actual production code - this doesn't make having an interface superfluous. A well documented interface establishes a contract, which can also be maintained by a strict mock implementation for testing.
in fact, you can establish tests that have mocks implement the most strict interface contract (throwing exceptions for arguments that shouldn't be null, etc) and catch errors in testing, using a more efficient implementation in production code (not checking arguments that should not be null for being null since the mock threw exceptions in your tests and you know that the arguments aren't null due to fixing the code after these tests, for example).
Dependency Injection/IOC can be hard to grasp for a newcomer, but once you understand its potential you'll want to use it all over the place and you'll find yourself making interfaces all the time - even if there will only be one (actual production) implementation.
For this one implementation (you can infer, and you'd be correct, that I believe the mocks for testing should be called Mock(InterfaceName)), I prefer the name Default(InterfaceName). If a more specific implementation comes along, it can be named appropriately. This also avoids the Impl suffix that I particularly dislike (if it's not an abstract class, OF COURSE it is an "impl"!).
I also prefer "Base(InterfaceName)" as opposed to "Abstract(InterfaceName)" because there are some situations in which you want your base class to become instantiable later, but now you're stuck with the name "Abstract(InterfaceName)", and this forces you to rename the class, possibly causing a little minor confusion - but if it was always Base(InterfaceName), removing the abstract modifier doesn't change what the class was.
The name of the interface should describe the abstract concept the interface represents. Any implementation class should have some sort of specific traits that can be used to give it a more specific name.
If there is only one implementation class and you can't think of anything that makes it specific (implied by wanting to name it -Impl), then it looks like there is no justification to have an interface at all.
I tend to follow the pseudo-conventions established by Java Core/Sun, e.g. in the Collections classes:
List - interface for the "conceptual" object
ArrayList - concrete implementation of interface
LinkedList - concrete implementation of interface
AbstractList - abstract "partial" implementation to assist custom implementations
I used to do the same thing modeling my event classes after the AWT Event/Listener/Adapter paradigm.
The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.
I like interface names that indicate what contract an interface describes, such as "Comparable" or "Serializable". Nouns like "Truck" don't really describe truck-ness -- what are the Abilities of a truck?
Regarding conventions: I have worked on projects where every interface starts with an "I"; while this is somewhat alien to Java conventions, it makes finding interfaces very easy. Apart from that, the "Impl" suffix is a reasonable default name.
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
I use both conventions:
If the interface is a specific instance of a a well known pattern (e.g. Service, DAO), then it may not need an "I" (e.g UserService, AuditService, UserDao) all work fine without the "I", because the post-fix determines the meta pattern.
But, if you have something one-off or two-off (usually for a callback pattern), then it helps to distinguish it from a class (e.g. IAsynchCallbackHandler, IUpdateListener, IComputeDrone). These are special purpose interfaces designed for internal use, occasionally the IInterface calls out attention to the fact that an operand is actually an interface, so at first glance it is immediately clear.
In other cases you can use the I to avoid colliding with other commonly known concrete classes (ISubject, IPrincipal vs Subject or Principal).
TruckClass sounds like it were a class of Truck, I think that recommended solution is to add Impl suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List interface and implementations: ArrayList or LinkedList), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl is the solution.
I'm a bit confused as to why languages have these. I'm a Java programmer and at the start of my career so Java is the only language I've written in since I started to actually, you know, get it.
So in Java of course we don't have properties and we write getThis() and setThat(...) methods.
What would we gain by having properties?
Thanks.
EDIT: another query: what naming conventions arise in languages with properties?
Which one looks more natural to you?
// A
person.setAge(25)
// B
person.age = 25;
// or
person.Age = 25; //depending on conventions, but that's beside the point
Most people will answer B.
It's not only syntaxic sugar, it also helps when doing reflection; you can actually make the difference between data and operations without resorting to the name of the methods.
Here is an example in C# for those not familiar with properties:
class Person
{
public int Age
{
set
{
if(value<0)
throw new ArgumentOutOfRangeException();
OnChanged();
age = value;
}
get { return age; }
}
private int age;
protected virtual void OnChanged() { // ... }
}
Also, most people always use properties rather than promote a public member later for the same reason we always use get/set; there is no need to rewrite the old client code bound to data members.
The syntax is much nicer:
button.Location += delta;
than:
button.setLocation(button.getLocation() + delta);
Edit:
The code below assumes that you are doing everything by hand. In my example world the compiler would generate the simple get/set methods and convert all direct variable access to those methods. If that didn't then the client code would have to be recompiled which defeats a big part of the purpose.
Original:
The main argument for properties is that it removes the need to recompile your code if you go from a variable to a method.
For instance:
public class Foo
{
public int bar;
}
If we later decided to validation to "bar" we would need to do this:
public class Foo
{
private int bar;
public void setBar(final int val)
{
if(val <= 0)
{
throw new IllegalArgumentException("val must be > 0, was: " + val);
}
bar = val;
}
public int getBar()
{
return (bar);
}
}
But adding the set/get method would break all of the code. If it was done via properties then you would be able to add the validation after the fact without breaking client code.
I personally don't like the idea - I am much happier with the idea of using annotation and having the simple set/get geterated automatically with the ability to profive your own set/get implementations as needed (but I don't like hidden method calls).
Two reasons:
Cleaned/terser syntax; and
It more clearly indicates to the user of the class the difference between state (properties) and behaviour (methods).
In Java the getters and setters are in essence properties.
In other modern languages (c#) , etc it just makes the syntax easier to work with/comprehend.
They are unnecessary, and there are workarounds in most cases.
It's really a matter of preference, but if the language you're using supports them I would recommend using them :)
I struggled with this at first, too, however I've really come to appreciate them. The way I see it, properties allow me to interact with the exposed data in a natural way without losing the encapsulation provided by getter/setter methods. In other words, I can treat my properties as fields but without really exposing the actual fields if I choose not to. With automatic properties in C# 3.0 it gets even better as for most fields -- where I want to allow the consumer to read/write the data -- I have even less to write:
public string Prop { get; set; }
In the case where I want partial visibility, I can restrict just the accessor I want easily.
public string Prop { get; private set; }
All of this can be done with getter/setter methods, but the verbiage is much higher and the usage is much less natural.
A general rule of object oriented programming is that you never change an existing interface. This ensures that while in inner content may change for the objects calling the object don't need to know this.
Properties in other languages are methods masquerading as a specific language feature. In Java a property is distinguished only by convention. While in general this works, there are cases where it limits you. For example sometimes you would to use hasSomething instead of isSomething of getSomething.
So it allows flexibility of names, while tools and other code depending on can still tell the difference.
Also the code can be more compact and the get and set are grouped together by design.
In Object Oriented Software Construction 2 Bertrand Meyer calls this the "Uniform Access Principle" and the general idea is that when a property goes from a simple one (i.e. just an integer) to a derived one (a function call), the people using it shouldn't have to know.
You don't want everyone using your code to have to change from
int x = foo.y;
to
int x = foo.y();
That breaks encapsulation because you haven't changed your "interface" just your "implementation".
You can also create derived fields and read-only/write-only fields. Most Properties that I've seen in languages I've worked in allow you to not only assign simple fields, but also full functions to properties.
Properties provide a simple method to abstract the details behind a set of logic in an object down to a single value to the outside world.
While your property may start out only as a value, this abstraction decouples the interface such that it's details can be changed later with minimal impact.
A general rule of thumb is that abstraction and loose coupling are good things. Properties are a pattern that achieve both.
Properties at the language level are a bad idea. There's no good convention for them and they hide performance deficits in the code.
It's all about bindings
There was a time when I considered properties to just be syntactic sugar (i.e. help the developer by having them type a bit less). As I've done more and more GUI development, and started using binding frameworks (JGoodies, JSR295), I have discovered that language level properties are much, much more than syntactic sugar.
In a binding scenario, you essentially define rules that say 'property X of object A should always be equal to property Y of object B'. Shorthand is: A.x <-> B.y
Now, imagine how you would go about actually writing a binding library in Java. Right now, it is absolutely not possible to refer to 'x' or 'y' directly as language primitives. You can only refer to them as strings (and access them via reflection). In essence, A."x" <-> B."y"
This causes massive, massive problems when you go to refactor code.
There are additional considerations, including proper implementation of property change notifications. If you look at my code, every blessed setter requires a minimum of 3 lines to do something that is incredibly simple. Plus one of those 3 lines includes yet another string:
public void setFoo(Foo foo){
Foo old = getFoo();
this.foo = foo;
changeSupport.firePropertyChange("foo", old, foo);
}
all of these strings floating around is a complete nightmare.
Now, imagine if a property was a first class citizen in the language. This starts to provide almost endless possibilities (for example, imagine registering a listener with a Property directly instead of having to muck with PropertyChangeSupport and it's 3 mystery methods that have to get added to every class). Imagine being able to pass the property itself (not the value of the property, but the Property object) into a binding framework.
For web tier developers, imagine a web framework that can build it's own form id values from the names of the properties themselves (something like registerFormProperties(myObject.firstname, myObject.lastname, someOtherObject.amount) to allow for round-trip population of object property values when the form is submitted back to the server. Right now to do that, you'd have to pass strings in, and refactoring becomes a headache (refactoring actually becomes downright scary once you are relying on strings and reflection to wire things up).
So anyway, For those of us who are dealing with dynamic data updates via binding, properties are a much needed feature in the language - way more than just syntactic sugar.