I've the following scenario. My application interacts with the database which contains some static tables. If I have to use that static information in the code level mostly for conditional code, what is the best approach.
For eg: I've a student database, which contains a static table student_type ( indicating hard-working, smart, lazy etc types ). In the code, I need to take action based on the student_type.
So, my code would look like this
studentTypeId = student.getTypeId(); // student constructed from database
switch (studentTypeId)
{
case HARDWORKING_ID :
// do something
case LAZY_ID :
// do something
break;
}
Well, in my code, I would either use constants or an enum to store type ids. But, isn't this kind of replicating things in code since I already have type ids in database. If the type id in database changes I'll have to change the same in my Enum which increases maintenance. Is there a better way to achieve this?
Thanks.
The question to ask is: does the addition of the row in the database imply a change in your java? If yes, go for the enum approach, and don't worry about the duplication. If you're going to have to change code anyway, for instance, to add new cases to your switch, then I usually find it's a good idea to keep things simple.
studentTypeId = student.getTypeId(); // student constructed from database
switch (studentTypeId)
{
case HARDWORKING_ID :
// do something
case LAZY_ID :
// do something
case SMART_ID : // added smart student, very rare corner case :-)
// do something
break;
}
Often in cases where you're storing static data like this you've got other constraints that go with the data, and when you change the data in the database, you have to change the code that uses that data.
If you really really want to reduce the duplication, then you can go for a fully pluggable architecture, as suggested by Dave Newton. This could be implemented as a id -> class name relation for each id. You'd then instantiate the class and all of the logic associated with each id would be contained in that class. This isn't always easy or possible. For your example, it may well be possible, but unless it's done right, this can be complicated.
Also, it doesn't solve all of your problems. You still have to develop the java, test it, and redeploy the new class. So actually, the amount of work you would save may be minimal.
It's often easier to accept the small amount of duplication and just go with the simple solution.
If the student_type table contains only some ID's and perhaps some descriptive text but nothing more as in this small example
ID description
1 'Hard worker'
2 'Lazy snob'
then your only chance is to use the IDs in your code, perhaps giving them proper names using either an enum or some constant interface as you did already. And every change on `student_type' which requires a change in behaviour will require code changes. There is no way out, because the only place where behaviour is formalized and defined is in your code.
IF however the table has formalized content like here
ID description min_ max_ min_ max_ fire_ give_
points points grade grade ASAP kudos
1 'Hard worker' 100 200 B A F T
2 'Lazy snob' 0 50 Z Q T F
3 'Medium' 50 100 P C F F
then the behaviour of your app is not driven by the ID but by the associated data - the data forms a simple rule system. In that case you don't need any constants in your code, because you will implement the rule system like this:
StudentType studentType = student.getStudentType();
if( studentType.isGiveKudos() )
doGiveKudos(student);
if( studentType.isFireAsap() )
doFire(student);
// next student...
This is the way to go if the flexibility is a must.
scratch head Now I don't know if this deviates to much from the question.
There's a bunch of ways this could be implemented. For quick/dirty stuff I'll often store the class name of an implementation in the DB and just instantiate at runtime. Sometimes I'll keep a Groovy implementation in the DB. Sometimes I'll use Spring beans where the factory is stored in the DB. All depends.
Related
It is not easy to explain my issue.
JPA creates some complex objects for calculations, which are stored in a database.
We decided to set the results in a working copy of this objects.
This means for each object model we created a seperated working copy model file with the same fields but some other LocalDates values and new result fields.
When the calculation was starting the working copies are instantiated.
This approach is not the best i think.
I think of the prototype pattern to clone the object.
There i come to the problem how to add the new fields. How?
Instantion costs and ist creates lots of additionals model class files.
I only think of put the result field in the calculation data models as transient fields.
Maybe inner class or local class?
I also tried to use an interface as data bucket.
But thats not the realy purpose of interfaces and also it works only with many curious trick.
For Unit Tests and user input i think it is the best to use the builder pattern and then tell JPA to store the parent object, or not?
Sorry but my answer was to long for a comment :(
There is big complex object relationship with Lists and Sets One To Many etc. relationship. When i set the result i a new class i cant determine the right object e.g. in a list. So we bild the same structurefor these result and seperated these classes in a package. Maybe it is possible to dont build the structure a second time with also references to the "basic classes". It should be sufficient to reference to each basic class a result class. It would only a little bit more navigation to get values from deeper classes. For a similiar use case there must be a best practise, or? Interfaces or sth. I very dislike the many classes for the result. Is it not possible to clone and add classmember to it for the result or to logical group easier or something like this?
It could be a solution for somebody:
http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2FIWorkingCopy.html
Here you will work with the Eclipse API and create IWorkingCopies.
For the described task toooo much.
To end 2014 year I got a simple question I think.
I would like to use "DDD" a bit more, and I'm currently trying to experiment various usecases to learn more about DDD.
My current usecase is the following :
we have a new database schema that is using a classic pattern in our company : modeling our nomenclature table as "id / code / label". I think it's a pretty classic case when using hibernate for example.
But in the OO world things get "complciated" for something this simple when using a API like JDBC or QueryDSL. I need to fetch an object by its code, retrieve its id or load the full object and then set it as a one to one relation in another object.
I wondering :
this kind of nomenclature can be an enum (or a class with String cosnatnts depending on the developer). in DDD terms, it is my ValueObject
the id /code / label in the database is not i18n friendly (it's not a prerequisite) so I don't see its advantages. Except when the table can be updated dynamically and the usecase is "pick something in a combobox loaded from this table and build a relation with another object : but that's all because if you have business rules that must be applied you need to know the new code etc etc).
My questions are :
do you often use the id / ocde / label pattern in your database model.
how do your model your nomenclature data ? (country is perhaps not the best example :) but no matter what how do you model it ? without thinking much I would say database table for country; but for some status : "valid, waiting validation, rejected" ?
do you model your valueObjects using this pattern ?
or do you use lots of enum and only store their toString (or ordinal) in the database ?
In the Java OO objects world, I'm currently thinking that it is easier to manipulate enum that objects loaded from the database. I need to build repositories to load them for example. And it will be so simple to use them as enums. I'm searching some recomfort here or perhaps am I missing something so obvious ?
thanks
see you in 2015 !
Update 1 :
We can create a "Budget" and the first one is mark as Initial and the next ones are marked as "Corrective" (with a increment). For example, we can have a list of Budgets :"Initial Budget", "Corrective budget #1", "Corrective budget #2".
For this we have this database design : a Budget Table, a Version Budge with a foreign key between the two. the Version budget only contains an ID, a CODE and a LABEL.
Personnaly, I would like to remove this table. I don't see the advantages of this structure. And from the OO perspective, when I'm creating a budget I can query the databse to see if I need to create an Inital or Corrective budget (using a count query) then I can set the right enum to my new budget. But with the current design I need to query the database using the CODE that I want, select the ID and set the ID. So yes, it's really database oriented. Where is the DDD part ? a ValueObject is something that describe, quantify something. In my case seems good to me. A Version describe the current status of my Budget. I can comapre two versions just but checking their code, they don't have lifecycle (I don't want this one in particular).
How to you handle this type of usecases ?
It's only a simple example because I found that if you ask a database admin he would surely said that all seems good : using primary key, modeling relations, enforing constraints, using foreign key and avoid data duplication.
Thanks again Mike and Doctor for their comments.
I will hook in in your country example. In most cases, country will be a value object. There is nothing that will reference a country entity and that should know that if the values of the country changes it is still the same country. In fact, the country could be represented as an enum, and some nasty resource lookup functions that translate the Iso3 into a usefull display text. What we do is, we define it as a value object class with iso3, displayname and some other static information. Now out of this value object we define a kind of "power enum" (I still miss a standard term here). The class implementing the country value object gets a private constructor and static properties for each of its values (for each country) and explicit cast operators from and to int. Now you can treat it just like a normal enum of your programing language. The advantage to a normal enum beside having more property fields is, that it also can have methods (of course query methods, that don't change the state of the object). You can even use polymorphism (some countries with different behaviour than others). You could also load the content of the enums from a database table (without the statics then and a static lookupByIso3 method instead).
This you could make with some other "enum like" value objects, too. Imagine Currencies (it could have conversion methods that are implemented polymorphic). The handling of the daily exchange rates is a different topic though.
If the set of values is not fixed (for example another value object candidate like postal adress) then it is not a value object enum, but a standard value object that could be instantiated with the values you want.
To decide if you can live with something as a value object, you can use the following question: Do you want copy semantic, or reference semantic? If you ever change a property of the object, should all places where you used it update, too, or should they stay as they are? If the latter, than the "changed" object is a new and different value object. Another question would be, if you need to track changes to an object realizing that it remains the "same" despite of changing values. And if you have a value object, where you only want specific instances to exist, it is a kind of enum described above.
Does that somehow help you?
I have a class which models FK relationship. It has 2 lists in it. These lists contains the column names of the Parent Table & the Child Table respectively. These lists are passes by the client to me. Now before creating my FK object, I think it is necessary to do following checks (in order):
Check if lists are not null.
Check if lists contains null.
If a list contains duplicates columns?
Size of both the lists are equal.
So you can see there will be total 7 checks. Is it OK to have so many checks?
If it is OK to have these many checks, is there any pattern to handle such cases (with high no. of validation checks)?
If it is not OK, then what should I do? Should I just document these conditions as part of contract & mention that API will produce nonsensical results if this contract is violated?
Edit : Basically, I am trying to takes these 2 lists & produce a Database specific Query. So, it is kind of important to have this object built correctly.
Like everybody says, it depends on you. There is no such fixed/standard guideline for this. But to make it simple, you must have to put all your validation logic in one place, so that it remains readable and easy to change.
A suggestion can be, as you said, all of your validation logic seems to be very business oriented..by which I mean the end user should not be bothered about your db configuration. Let assume your class name, FKEntity. So if you follow the entity concept then you can put the validation logic in FKEntity.validate() (implementing an interface Validatable) which will validate the particular entity...this is for those kind of validation logic which applies to all FKEntity type objects in same way. And if you need any validation logic that compares/process different FKEntity depending on each other (e.g. if there is one FKEntity with some value "x" then no other entity can have "x" as their values, if they do, then you can not allow the entire entity list to persist), then you can put the logic in your Service layer.
Inteface Validatable { void validate() throws InvalidEntityException; }
Class FKEntity implements Validatable {
//..
public void validate() throws InvalidEntityException {
//your entity specific logic
}
}
Class FKDigestService {
public digestEntities() {
try {
for(FKEntity e : entityList)
e.validate();
//your collective validation logic goes here
} catch (EntityValidationException e) {//do whatever you want}
}
}
This will give you two advantages,
Your entity specific validation logic is kept in a single place (try to think most of the logic as entity specific logic)
Your collective logic is separated from entity logic, as you can not put these logic in your entity since these logic is only applicable when there is a collection of FKEntity, but not for single entity...it is business logic, not validation logic
I depends on you. There is no real argument against many checks. If your are developing an API, this can be very useful for other programmers. And it will make your own program more reliable.
I think the important point is, that you do your checks at one single point. You must have a clean and simple interface for your API. In this interface, it is ok to make checks. After these checks you could be sure that everything works.
What happens if you leaf the checks away? Will an exception be thrown somewhere or will the program just do something? If the program will just work and do something unpredictable, you should provide checks or things will begin to get strange. But if an exception will be thrown anyway, (I think) you can leaf the checks away. I mean, the program will get an exception anyway.
This is complex problem, so solution should be simplest possible to do not make it even more complicated and less understandable.
My approach would be:
some public method wrapping private method named something like doAllNeededListsValidationInFixedOrder() in which I'd create another private methods - each for every needed validation.
And ofc writing method like doAllNeededListsValidationInFixedOrder should be follow by some solid javadoc, even though it's not public.
If you want to go for pattern - the solution wouldn't be so straightforward. Basic thing to require checks in given order is to create lots or classes - every one for state telling that object is after one check, before another.
So you can achieve this with State pattern - treating every check as new state of object.
OR
You can use something like Builder pattern with forced order of methods invoked to create object. It is basically using a lot of interfaces to have every single (building) method (here validating) fired from different interface, to control order of them.
Going back to begining - using simple, well documenented and properly named method, that hides validating methods set, seems better for me.
If it is OK to have these many checks, is there any pattern to handle such cases (with high no. of validation checks)?
These checks become trivial if tackled from a data conversion point of view.
List from a client is actually any list of any possible elements
List from a client is to be converted to a well defined list of not duplicating not null elements
This conversion can be decomposed into several simple conversions ToNonNull, ToNonNullList, ToNonDuplicatingList
The last requirement is essentially conversion from two lists to one list of pairs ToPairs(ListA, ListB)
Put together it becomes:
ParentTableColumns = List1FromClient.
ToNonNull.
ToNonNullList.
ToNonDuplicatingList
ChildTableColumns = List2FromClient.
ToNonNull.
ToNonNullList.
ToNonDuplicatingList
ParentChildColumnPairs = List.
ToPairs(ParentTableColumns, ChildTableColumns)
If data from client is valid then all conversions succeed and valid result is obtained.
If data from client is invalid then one of the conversions fails and produces an error message.
My question more specificity is this:
I want users on multiple front ends to see the "Type" of a database row. Let's say for ease that I have a person table and the types can be Student, Teacher, Parent etc.
The specific program would be java with hibernate, however I doubt that's important for the question, but let's say my data is modelled in to Entity beans and a Person "type" field is an enum that contains my 3 options, ideally I want my Person object to have a getType() method that my front end can use to display the type, and also I need a way for my front end to know the potential types.
With the enum method I have this functionality but what I don't have is the ability to easily add new types without re-compiling.
So next thought is that I put my types in to a config file and simply story them in the database as strings. my getType() method works, but now my front end has to load a config file to get the potential types AND now there's nothing to keep them in sync, I could remove a type from my config file and the type in the database would point to nothing. I don't like this either.
Final thought is that I create a PersonTypes database table, this table has a number for type_id and a string defining the type. This is OK, and if the foreign key is set up I can't delete types that I'm using, my front end will need to get sight of potential types, I guess the best way is to provide a service that will use the hibernate layer to do this.
The problem with this method is that my types are all in English in the database, and I want my application to support multiple languages (eventually) so I need some sort of properties file to store the labels for the types. so do I have a PersonType table the purely contains integers and then a properties file that describes the label per integer? That seems backwards?
Is there a common design pattern to achieve this kind of behaviour? Or can anyone suggest a good way to do this?
Regards,
Glen x
I would go with the last approach that you have described. Having the type information in separate table should be good enought and it will let you use all the benefits of SQL for managing additional constraints (types will be probably Unique and foreign keys checks will assure you that you won't introduce any misbehaviour while you delete some records).
When each type will have i18n value defined in property files, then you are safe. If the type is removed - this value will not be used. If you want, you can change properties files as runtime.
The last approach I can think of would be to store i18n strings along with type information in PersonType. This is acceptable for small amount of languages, altough might be concidered an antipattern. But it would allow you having such method:
public String getName(PersonType type, Locale loc) {
if (loc.equals(Locale.EN)) {
return type.getEnglishName();
} else if (loc.equals(Locale.DE)){
return type.getGermanName();
} else {
return type.getDefaultName();
}
}
Internationalizing dynamic values is always difficult. Your last method for storing the types is the right one.
If you want to be able to i18n them, you can use resource bundles as properties files in your app. This forces you to modify the properties files and redeploy and restart the app each time a new type is added. You can also fall back to the English string stored in database if the type is not found in the resource bundle.
Or you can implement a custom ResourceBundle class that fetches its keys and values from the database directly, and have an additional PersonTypeI18n table which contains the translations for all the locales you want to support.
You can use following practices:
Use singleton design pattern
Use cashing framework such as EhCashe for cashe type of person and reload when need.
What is the best data structure to store an oracle table that's about 140 rows by 3 columns. I was thinking about a multi dimensional array.
By best I do not necessarily mean most efficient (but i'd be curious to know your opinions) since the program will run as a job with plenty of time to run but I do have some restrictions:
It is possible for multiple keys to be "null" at first. so the first column might have multiple null values. I also need to be able to access elements from the other columns. Anything better than a linear search to access the data?
So again, something like [][][] would work.. but is there something like a 3 column map where I can access by the key or the second column ? I know maps have only two values.
All data will probably be strings or cast as strings.
Thanks
A custom class with 3 fields, and a java.util.List of that class.
There's no benefit in shoe-horning data into arrays in this case, you get no improvement in performance, and certainly no improvement in code maintainability.
This is another example of people writing FORTRAN in an object-oriented language.
Java's about objects. You'd be much better off if you started using objects to abstract your problem, hide details away from clients, and reduce coupling.
What sensible object, with meaningful behavior, do those three items represent? I'd start with that, and worry about the data structures and persistence later.
All data will probably be strings or cast as strings.
This is fine if they really are strings, but I'd encourage you to look deeper and see if you can do better.
For example, if you write an application that uses credit scores you might be tempted to persist it as a number column in a database. But you can benefit from looking at the problem harder and encapsulating that value into a CreditScore object. When you have that, you realize that you can add something like units ("FICO" versus "TransUnion"), scale (range from 0 to 850), and maybe some rich behavior (e.g., rules governing when to reorder the score). You encapsulate everything into a single object instead of scattering the logic for operating on credit scores all over your code base.
Start thinking less in terms of tables and columns and more about objects. Or switch languages. Python has the notion of tuples built in. Maybe that will work better for you.
If you need to access your data by key and by another key, then I would just use 2 maps for that and define a separate class to hold your record.
class Record {
String field1;
String field2;
String field3;
}
and
Map<String, Record> firstKeyMap = new HashMap<String, Record>();
Map<String, Record> secondKeyMap = new HashMap<String, Record>();
I'd create an object which map your record and then create a collection of this object.