I have a table in my database schema which contains configuration information for an application that I'm building. I'd like to generate a number of enums based on the contents of the table. I'm currently using JOOQ in my build scripts to generate other, standard JOOQ classes from the same database, and am hoping that I can obtain this new functionality through JOOQ.
For example, if the table contained the following data
Product Component PresentationOrder
HydroProduct Boat 1
HydroProduct Canoe 2
HyrdoProduct Ship 3
LandProduct Car 1
LandProduct Bike 2
Then I'd want to generate two enums
hydroProduct.Components { Boat, Canoe, Ship; }
and
landProduct.Components {Car, Bike; }
where hydroProduct and landProduct are packages, and the enums are both called Components.
The precise details are up for grabs (e.g. I'd be fine with different naming conventions, so any suggestions are welcome), but the principal (two enums from the one table, based on the data therein) is, at least for this question, the thing that I need.
Having read the JOOQ docs, I see that generating Enums was once a part of JOOQ, and then removed. I can't see the "obvious" way of doing what I want in JOOQ, but it's a pretty amazing library, so I'm guessing that there might be one.
EDIT
A number of commenters have questioned the overall approach, which I understand. I'd like to avoid that kind of conversation - it's basically impossible for me to debate that level of design over this forum. This approach (code generation based on DDL and SQL) is very well tested within my organisation, and has had a very large amount of design scrutiny.
Just for the record, here's an outline the pipeline. I'm putting it in because I appreciate that people have spent time considering my original question, and I'd like to make it clear how the question fits into our overall dev system.
Project One holds some bootstrapping classes, some DDL and some SQL scripts that contain the data constants that our overall system uses. It's output includes (amongst other stuff), some .jar files containing compiled versions of classes generated. These basically comprise the core agreed vocabulary that the rest of our system uses to communicate.
Project Two holds java source code, which makes use of the various artefacts generated from project one. Before project two ever gets compiled, artefacts from project one can be assumed to have been generated. So, for example, an Enum generated from data held in project one can be used, at compile time, in project two.
Our build scripts build project one, and make the outputs available for project two. This includes generating Eclipse project files so that users of project two can check-out, build, and open eclipse for any branch of the project and it "just works".
There are other projects (including in different languages, e.g. Javascript) that also make use of the artefacts generated by project one.
The key benefit of this approach is that, when the data in project one changes, and the definitions of classes and enums in project one therefore change, project two reflects this change with compile-time errors, rather than run-time errors. The benefits of this in practice are absolutely enormous. There is a setup-cost, yes, but in our experience tools like JOOQ (which we use to generate the outputs of Project 1) have made us incredibly more productive than we used to be.
This is especially the case where we ship desktop, in-browser, and J2EE components and they all need to talk together.
This won't be an exhaustive answer, as the question is a bit opinionated, but I can provide some authoritative background on the history of this feature in jOOQ:
Having read the JOOQ docs, I see that generating Enums was once a part of JOOQ, and then removed.
Yes, the reason for removal was precisely because the then-existing implementation was far from sophisticated enough to accommodate, for instance, your particular use-case.
Code generation is a very ad-hoc "science" and it is extremely difficult to maintain a configuration API backwards compatibly, which can accommodate all the possible use-cases... For instance, the fact that you want to map parts of your master data onto packages, class names being constant, ordering custom is rather particular, not generic.
Furthermore, where should generated enums be referenced from? The original implementation replaced foreign keys (e.g. Integers) by enum references in the generated code. This might not at all be what you want in some cases, where you do want to join the master data in its raw form, not as a generated enum.
Long story short, this was an eagerly added feature in jOOQ 1.x, which was extremely hard to maintain during major internal refactorings that were needed to create jOOQ 3.x, which is why it was dropped.
I can't see the "obvious" way of doing what I want in JOOQ, but it's a pretty amazing library, so I'm guessing that there might be one.
Not out of the box. I'd recommend using a templating language like Velocity or Xtend and generate the code manually as part of your build. You could, in fact, even generate custom Converter or Binding implementations to bind your enums to the relevant referencing columns.
Related
I am new to android programming. I often see that programmers create packages as collection of activities, fragments, adapters, etc. To me it seems more intuitive to put all java code required for an activity/screen in one place. For example: For home screen, I will keep the activity, fragments, adapters, custom views, etc all at one place.
Is there is any definite reason the the general practice or is it just a traditional practice ?
This has to do with creating components, reusable objects and code maintenance in a codebase as it grows. Your approach will work for a small application, and there is no rule against it. However, generally creating package/file structures according to the recommended and common approaches makes it easier to make modifications to code and work with others on the same project. Consider the following:
If you have many Activities spread across many packages or folders, then someone tasked with changing the UI will have to traverse those packages. That makes it difficult to identify UI patterns that could be used across Activities and even harder to use those patterns, since you will need to implement them in each package/folder.
This also creates a problem seeing less obvious patterns in non-UI components like data object models, view controllers, etc. For example, if you need a "user" object in two different Activities do you create 2 different objects? This is not reusable code.
So let's say you decide to reuse the "user" object so that you only have 1 class. Then do you sub-class in the other packages that need it in order to follow your pattern? Then if one UI element needs a new method, do you implement it in just that place? Or the base object?
Or do you make the "user" object public and reference it from other packages/folders? If this is your answer then you will begin to create objects in places based on the evolution of the code, instead of based on logic or ease of maintenance. Among other things, this makes it very difficult to train a new person on "where everything is" in your codebase. The "user" object will sit in one place, and then the "user account" object ends up where it is first needed, but not likely to be with the "user" object.
As a project grows to hundreds of classes, I think it is obvious that this approach becomes unmanageable for many applications. Classes will appear in packages based on the UI requirement, not based on the function it performs. Maintaining them becomes challenging.
For example in the case of Lollipop to Marshmallow, Apache http became deprecated. If you had this dependency scattered throughout your project, then you will be looking in a lot of places at how to handle this change. On a small project that might be fine, but on a larger project if you try to do this while other development is taking place, this can become a real mess since you are now modifying across many packages and folders instead of in only a few locations.
If, however, you have a Data Access Layer or Model Layer components that encapsulate the behavior in one or several folders, then the scope of your changes is easier to see to those around you. When you merge your changes into the project, it is easy for the people you work with to know if other components were impacted.
So while it is not necessary to follow these guidelines (especially for small projects), as a project grows and several or many people become involved in the development, you will see variations but the general practice is to group by purpose or function rather than group by UI / visual component. If you start off with some of this in place, you will have less work later to deal with the change. (However, starting with too much structural support early in a project can put the project at risk of never being completed...)
Several answers provides links to the guidelines. I hope this answer helps to explain why those guidelines exist, which I believe is at the heart of your question.
Is there is any definite reason the the general practice or is it just
a traditional practice ?
Yes. In my current application I have over 50 custom UI views and a few activities. At least 10 singleton controller and a lot of database model. So to not lost in the project, I'm using a tidy structure like this:
Activity
Adapter
Controller
Native
Model
-Database
-Rest
Ui
I suggest you to use this structure.
There are no official rules, well maybe best practices which I have not in mind.
I so we get now a opinion based answer:
I use the package names for grouping classes to a logical topic like adapters, activities, etc.
If you want another structure do it like you want, just it could confuse other devs.
Keep in mind that the package name should be unique so you should use a prefix like a domain you own or you are allowed to use (in reversed order of cause).
Check also this link where are some more ideas pointed out: http://www.javapractices.com/topic/TopicAction.do?Id=205
The first question in building an application is "How do I divide it up into packages?". For typical business applications, there seems to be two ways of answering this question.
Package By Feature
Package-by-feature uses packages to reflect the feature set. It tries to place all items related to a single feature (and only that feature) into a single directory/package. This results in packages with high cohesion and high modularity, and with minimal coupling between packages. Items that work closely together are placed next to each other. They aren't spread out all over the application. It's also interesting to note that, in some cases, deleting a feature can reduce to a single operation - deleting a directory. (Deletion operations might be thought of as a good test for maximum modularity: an item has maximum modularity only if it can be deleted in a single operation.)
Normally the activities are places in the main package and fragments, adapters, utils, models in their own packages like fragments in fragments packages and ISODateParser class could go into utils package.
You can find more about it in the Android Best Practices guide which contains best practices for android.
The guidelines about which classes should be placed under which packages are discussed under the Java packages architecture heading in the guide.
Hope it Helps!
I have been given a task of "generate sequence diagrams automatically on execution of junit/test case" in eclipse. I am learning UML. I found tools that can generate a sequence, and I am aware of junit, but how do I club this both.
The tools that I found good were UMLet,ModelGoon UML, Object Aid. But I zeroed in on ModelGoon. I found that simple and easy to use. How do I automate this task, if so please guide me.
If there are any-other tools that are available then guide me.
First: This is a very good idea, and there are several ways to go about it. I will make the assumption that you are working in a jvm language (e.g. Kotlin or Java) so the suggestions I will make are biased by that.
Direct approach
Set up your logging to log using json, it makes the rest much simpler: https://www.baeldung.com/java-log-json-output
Make a library where you log the name of the component/method you are in, and the session you are processing. There are many ways of doing this, but a simple one is to a thread local variable: Set the variable to contain the name of the thing you are tracing ("usecase foobar"), and some unique ID (UUIDs are a decent choice). Another would be to generate some tracing ID (or get one from an external interaction), and send that as a parameter to all involved methods. Both of these will work, and which one is the simplest in practice depends on the architecture of your application.
In the methods you want to trace, write a log entry that contains that tracing information (name of usecase, trace ID, or any combination thereof), the location where the log entry was written, and any other information you want to add to your sequence diagram.
Run your test normally. A log will be produced. You need to be able to retrieve that log. There are many ways this can be done, use one :-)
Filter the log entries so you get only the ones you are interested in. Using the "jq" utility is a decent choice.
Process the filtered output to generate "plant uml" input files (http://plantuml.com/) for sequence diagrams.
Process the plant UML files to get sequence diagrams.
Done.
Industrial approach
Use some standard tooling for tracing like "https://opentracing.io/", instrument your application using this tooling, and extract your diagrams using that standard tooling.
This will also work in production an will probably scale much better than the direct approach, but if scaling isn't your thing, then the direct approach may be what you want to do.
Is there some sort of tool that you can point at a set of Java classes, and it produces output showing the transitive imports of each class?
I understand that imports are not "transitive" from the point of view of the language itself - i.e. if com.acme.X imports com.acme.Y, and com.acme.Y imports com.acme.Z, that does not mean that you can refer to com.acme.Z within com.acme.X. But that's not what I mean:
Rather, I mean that com.acme.X nonetheless depends upon com.acme.Z (at least under the current implementations of X and Y), and I want to know that fact. In fact I want to know it for a large number of classes, and so I'm hoping that there's a tool do determine it automatically.
Either a standalone tool or an Eclipse plugin or feature would be great.
Thanks in advance.
EDIT to hopefully show what I want this for:
I have a huge monolithic jar that contains many features that are (essentially) completely unrelated. I'd like to break it apart into several smaller, more manageable, and more self-coherent jars.
Unfortunately, I can't do it simply by breaking it up based on packages, because many of the packages themselves are not self-coherent either. That is, for example, there's a "com.acme.utils" package. Two things in that package are probably have nothing in common except for the fact that they're both, in some sense, "utilities". One may be a utility for some particular business function, another may be TCP/IP utilities, another may be a set of string utilities, another may be some completely unrelated business function.
And there are a bunch of packages like this. So when you look at the transitivity of imports from the point of view of packages, they snowball without limit, and so more or less everything in the monolithic jar depends on everything else in the monolithic jar.
So I'd like to start by considering transitivity of imports from the class point of view, rather than the package point of view. That way I should be able to more easily determine what classes need to be reorganized from what existing packages into new, more coherent packages, and then after that I can break the monolithic jar apart by packages / sets of packages.
we're using sonar for software metrics. http://www.sonarsource.org/
I have an enum that has two dependencies. These two are in different projects (Im coding in Java). I want to show this dependency ina UML diagram but how can I show what projects these classes are from? (I know for packages you can put it like this: Package :: pkgName).
Any ideas would be helpful. Thanks
What tool are you using?
In Rational Rose, if you this structure:
Folder1
|___Class1
Folder2
|___ClassDiagramX
and the ClassDiagramX shows Class1 then you'll see a small "stereotype" like note indicating "from Folder1" in the box representing Class1.
That should be sufficient.
There are other options using fancy-colorful-notes, but I don't care so much for them.
--edit--
Without knowing the tool I can't really say what you can and can not do. From UML pov, I don't know of any defined convention, so whatever conveys what you wan to can be used. Class diagram is a representation and does not affect the meta-data of the class (e.g. which project it belongs to). So as long as the "class" is in the correct package, it's doesn't matter how it's "shown" in the class diagram.
E.g. in the class-diagram you can put up 2 big squares in the background showing / grouping classes from each project and dependency arrows running across these groups.
OR
"add the line" if that's possible in your tool.
If you use Eclipse and java then you have a feature which allow to join two different projects. I mean open the package explorer and click on the project name then select join, or merge with I don't really remember the exact title of the menu but it is easy to find.
Once your both projects have been joined your can create a class diagram and just drag drop inside the same diagram two classifiers coming from different projects.
Project in the sense of "a set of planned activities and deliverables, with common goal" can not be reasonably encoded in UML.
Project in the sense of "a set of related files and metadata that allows an IDE to compile and run a program" is out of scope for UML, as this is a development environment artifact and not application design artifact.
For example, you can decide to use multiple projects for each module of your app or a single project for all modules. This will not change your design, only the instructions for the IDE - it's even possible that different team members have different project configurations, especially if some use Eclipse, others IntelliJ IDEA and some EMACS.
On the other hand, if you still want to denote logical sets of classes, you do have options - the formal way would be to use tagged values. Alternatively, I often use colors (for example, green for public API, yellow for extension points/SPI and red for implementation classes; or blue for low-latency multicast component, green for guaranteed messaging components).
You may also use a separate component diagram, showing which class belongs to which component (remember not to build uber-diagrams, but instead aim for simplicity and showing only the relevant facets of the design)
This was a generic advice, but the answer you need is very context-specific. I can get more concrete if you can describe in more detail what are the classes in question, what are the projects (how do you delineate between them) and the overall architecture of the system.
I had written a lot of java bean classes using my IDE. Another person suggests a different approach. He suggests that I put an xml file with bean definitions in them. Then I either use jaxb or xslt to dynamically generate the classes during build time. Though its a novel and interesting approach, I do not see any major benefit in it.
I see only one benefit in this suggested approach : The java bean classes need not be maintained in configuration control. Any bean changes is going to require only an update in the xml file.
Are there any major benefits in dynamically generating java classes ? Is there any other reason why this approach is taken ?
I agree with #Akhilss. My experiences have been in large scale Java EE projects where code generation is common.
It all depends on your project. If you are coding only a few beans and only need basic functionality then I don't see the need to start with XML (Which is often over used anyway). Especially if you actually don't need the XML as well.
However if you are building a system which needs the XML, an example being a SOAP web service WSDL and schema, then generation is a good idea because it saves you from manually keep schemas and beans in sync. As well as providing factory classes and other support code.
As a counter argument, with EJB3 and similar standards, it's now often easier to write the beans and generate the messy XML stuff on the fly. Ie. let the server do the grunt work.
Another reason to consider code generation is if you require more complex functionality in your beans because they represent data structures. A few years ago I trialled the Apache Tuscany project for generating SDO beans from XML. The nice thing about that was that I could generate functionality like property change notifications so when I modified any of the bean's properties (including collections), other parts of your program could be notified automatically. Generated functionality like that can save you a lot of time and money if you need it.
Ultimately, I'd suggest adhering to the KISS principle. So don't add what you don't need. Generated code from XML is useful if it helps you in the long run. But like any technology, be sure you are adding it for the right reasons.
I have used Jibx and its generator in my project. My experience has been mixed.
The usual case for using JAXB's (XJC) generator is referred to in http://static.springsource.org/spring-ws/site/reference/html/why-contract-first.html
Conversion to and from XML maked it possible to store in the DB and retrieve for future use as well as use for test case input for functional tests.
Using any kind of generator (Jaxb,Jibx,XMLBeans,Custom) might make sense for large sized projects. It allows for standardization of data types (like BigDecimal for financial amounts, like ArrayList for all lists), forcing interfaces (like Serializable or Cloneable). This enforces good practices and reduce the need for reviews of generated files.
It allows for injection of code through XSLT or post processing of generated java file. Example is to inject Rounding code to a specific decimal size(2,6,9) with a specific policy (UP,DOWN,NEAR) within the setter method for each field of type financialAmount. Forcing such behavior does reduce the instance of bugs(for incorrect financial values which companies are liable for).
The disadvantage are
Usually each java class can be only a bean class. Any customization made will be overwritten. Since (in my case) the generator is tied in to the build process. The classes get generated with every build.
You cannot do implementation of your custom interfaces on a bean class or add annotations for your own or third party frameworks.
You cannot easily implement patterns like a factory method since default constructors are usually generated. Refactoring is usually difficult since generators do not usually support it.
You may(not sure now, was true a couple of years ago for Jibx) not be able to generated ENUMS when it would be most applicable.
You may not be able to override the default datatype with your own regardless of the need. CopyOnWrite list and not ArrayList for a variable shared across threads or a custom implementation of a List which also implements the Observer pattern.
The benefits of a generator outweigh the costs for large sized (in persons and not code, think 150 developers in three locations) distributed projects. You can work around the disadvantages by defining your custom classes which contain the bean and implements behaviour or post processing (adding additional code) with further metadata picked up from XSD annotations or another configuration file. Remember support and Maintenance of the generator become critical since the entire project depends on it. Use it with CAUTION.
For smaller sized projects I personally would write my own classes. For larger sized projects I personally would not use it in the middle tier mostly because of the lack of refactoring support. It can be used for simple beans meant to be bound to UI frameworks.