I’m looking for a method to describe fields in a structured way, so I am able to reuse it in various languages and levels of my application.
For instance, if I’m developing an Android application about food items, I might be dealing with fields like Name, Description, Price and Kcal. However, these fields will appear multiple times: In the viewholder of my Android application, in the C++ server which handles the messages, in my SQL database which stores them, etc. Imo, this violates the DRY principle, and if I also want to save the barcode of a food item for example, I need to add it to all these places.
I’ve been thinking about using XML or TDL, but I’m not sure if those languages are intended for this goal. Preferably, I would have a file like this:
Fieldname Type Lower bound Upper bound May be NULL
-----------------------------------------------------------
Name string 3 100 No
Price float 0 * Yes
...
Of course I could create such a thing myself, but would that be a good way to go? Or is there something out there which is used for this purpose (I want to avoid beginners mistakes). Preferably, I would have these definitions been read out at compile-time because the definition won’t be altered at runtime anyway.
2
There are already frameworks like this, for example the ORM ones. This will ensure that you don’t have to define the SQL structure too. I’m more familiar with the Java ones, like DataNucleus or Hibernate.
Based on the same code annotations, you can generate the domain model for the Android application.
But, in my experience, maintaining such a framework, will soon become very expensive, as most probably you will need a lot of exceptions, like different constraints (URL, all lowercase, list etc).
If you would use Java on the server side, you can actually use the same classes for the domain model on both client and server. But, there could also be the case that you want a thinner model on the client side (the Android app) than on the server side (Java or C++ server).
A few of thoughts:
-
The problem with fields is that they are a code abstraction rather than a business domain abstraction.
-
Treating
name
,price
,kcal
, etc. as types rather than fields [e.g. usingtypedef
in C++ and wrapper classes for primitives in Java] focuses on what is common and black boxes implementation details such as the differences between the representation of strings in Java and C++ and their immutable/mutable natures respectively. -
Aspects of the system which boil down to typechecking such as validation requirements (along the lines of
name.length
being between 3 and 50) can live on their own layers behind API’s.
Implicitly, the direction you’re heading is toward a Domain Specific Language. Thinking about types and type-checking is a foundation upon which one might be built.