Generate SerialVersionUID for Java Class - serialization

From heading it is expected to be the same old question but trust me this is different.
I am working with an EJB3 and off course if I have to invoke it remotely I have to make all my data object implement Serializable interface.
The problem is that most my data objects are generated (using Velocity Templates), compiled and package in one go. For now I hard coded the default serialVersionUID in every class as follows;
private static final long serialVersionUID = 1L;
But I am wondering if there is any way I can do following;
private static final long serialVersionUID = getSerialUID();
private static long getSerialUID() {
// Serial Version Algo code here
}
Also, is there any problem in using Default serialVersionUID? Do I really need to generate a unique ID using Algo?

Is there any problem in using Default serialVersionUID?
There is no issue in using default serialVersionUID unless you have more than
one versions of same class.
Read:
What is a serialVersionUID and why should I use it?
Do I really need to generate a unique ID using Algo?
Answer would be again no. You dont have to generate a unique ID using any Algo. If you have different versions of same class then you can provide a unique number as serialVersionUID (e.g. serialVersionUID=123 and serialVersionUID=456)
I strongly recommend you to go through Javadoc java.io.Serializable

First answer is helpful but it does not tell you how to generate class serialVersionUID. I have done it as follows as all of my classes are generated by Velocity Template I have to get it at the time of code generation. So I created a method to get hashcode() for all the properties and add them in the end to get the serialVersionUID. For example;
public int getSerialVerionUID() {
return getName().hashCode() +
getTypeName().hashCode() +
getCardinality().hashCode() +
getComplexity().hashCode();
}
So as soon as any of the property changes, we will have the different UID and that's all we are looking for.
Hope this helps to some one.

Related

Jackson private constructors, JDK 9+, Lombok

I'm looking for documentation on how Jackson works with private constructors on immutable types. Using Jackson 2.9.6 and the default object mapper provided by spring boot two running with jdk-10.0.1
Given JSON:
{"a":"test"}
and given a class like:
public class ExampleValue {
private final String a;
private ExampleValue() {
this.a = null;
}
public String getA() {
return this.a;
}
}
Deserialisation (surprisingly, at least to me) seems to work.
Whereas this does not:
public class ExampleValue {
private final String a;
private ExampleValue(final String a) {
this.a = a;
}
public String getA() {
return this.a;
}
}
And this does:
public class ExampleValue {
private final String a;
#java.beans.ConstructorProperties({"a"})
private ExampleValue(final String a) {
this.a = a;
}
public String getA() {
return this.a;
}
}
My assumption is that the only way the first example can work is by using reflection to set the value of the final field (which I presume it does by java.lang.reflect.AccessibleObject.setAccessible(true).
Question 1: am I right that this is how Jackson works in this case? I presume this would have the potential to fail under a security manager which does not allow this operation?
My personal preference, therefore, would be the last code example above, since it involves less "magic" and works under a security manager. However, I have been slightly confused by various threads I've found about Lombok and constructor generation which used to generate by default #java.beans.ConstructorProperties(...) but then changed default to no longer do this and now allows one to configure it optionally using lombok.anyConstructor.addConstructorProperties=true
Some people (including in the lombok release notes for v1.16.20) suggest that:
Oracle more or less broke this annotation with the release of JDK9, necessitating this breaking change.
but I'm not precisely clear on what is meant by this, what did Oracle break? For me using JDK 10 with jackson 2.9.6 it seems to work ok.
Question 2: Is any one able to shed any light on how this annotation was broken in JDK 9 and why lombok now considers it undesirable to generate this annotation by default anymore.
Answer 1: This is exactly how it works (also to my surprise). According to the Jackson documentation on Mapper Features, the properties INFER_PROPERTY_MUTATORS, ALLOW_FINAL_FIELDS_AS_MUTATORS, and CAN_OVERRIDE_ACCESS_MODIFIERS all default to true. Therefore, in your first example, Jackson
creates an instance using the private constructor with the help of AccessibleObject#setAccessible (CAN_OVERRIDE_ACCESS_MODIFIERS),
detects a fully-accessable getter method for a (private) field, and considers the field as mutable property (INFER_PROPERTY_MUTATORS),
ignores the final on the field due to ALLOW_FINAL_FIELDS_AS_MUTATORS, and
gains access to that field using AccessibleObject#setAccessible (CAN_OVERRIDE_ACCESS_MODIFIERS).
However, I agree that one should not rely on that, because as you said a security manager could prohibit it, or Jackson's defaults may change. Furthermore, it feels "not right" to me, as I would expect that class to be immutable and the field to be unsettable.
Example 2 does not work because Jackson does not find a usable constructor (because it cannot map the field names to the parameter names of the only existing constructor, as these names are not present at runtime). #java.beans.ConstructorProperties in your third example bypasses this problem, as Jackson explicitly looks for that annotation at runtime.
Answer 2:
My interpretation is that #java.beans.ConstructorProperties is not really broken, but just cannot be assumed to be present any more with Java 9+. This is due to its membership in the java.desktop module (see, e.g., this thread for a discussion on this topic). As modularized Java applications may have a module path without this module, lombok would break such applications if it would generate this annotation by default. (Furthermore, this annotation is not available in general on the Android SDK.)
So if you have a non-modularized application or a modularized application with java.desktop on the module path, it's perfectly fine to let lombok generate the annotation by setting lombok.anyConstructor.addConstructorProperties=true, or to add the annotation manually if you are not using lombok.

How to convert existing POCO classes in C# to google Protobuf standard POCO

I have POCO classes , I use NewtonSoft json for seralization. Now i want to migrate it to Google protocol buff. Is there any way i can migrate all my classes (not manually) so that i can use google protocol buff for serialization and deseralization.
Do you just want it to work? The absolute simplest way to do this would be to use protobuf-net and add [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]. What this does is tell protobuf-net to make up the field numbers, which it does by taking all the public members, sorting them alphabetically, and just counting upwards. Then you can use your type with ProtoBuf.Serializer and it should behave in the way you expect.
This is simple, but it isn't very robust. If you add, remove or rename members it can all get out of sync. The problem here is that the protocol buffers format doesn't include names - just field numbers, and it is much harder to guarantee numbers over time. If your type is likely to change, you probably want to define field numbers explicitly. For example:
[ProtoContract]
public class Foo {
[ProtoMember(1)]
public int Id {get;set;}
[ProtoMember(2)]
public List<string> Names {get;} = new List<string>();
}
One other thing to watch out for would be non-zero default values. By default protobuf-net assumes certain things about implicit default values. If you are routinely using non-zero default values without doing it very carefully, protobuf-net may misunderstand you. You can turn that off globally if you desire:
RuntimeTypeModel.Default.UseImplicitZeroDefaults = false;

Static methods in OOP

I've always known what static methods are by definition, but I've always avoided using them at school because I was afraid of what I didn't know.
I already understand that you can use it as a counter throughout your entire project.
Now that I am interning I want to know when exactly static methods are used. From my observation so far, static classes/methods are used when it contains a lot of functions that will be used in many different classes and itself doesn't contain too many critical local variables within the class where it is not necessary to create an instant of it.
So as an example, you can have a static class called Zip that zips and unzips files and provide it to many different classes for them to do whatever with it.
Am I right? Do I have the right idea? I'm pretty sure there are many ways to use it.
Static functions are helpful as they do not rely on an instantiated member of whatever class they are attached to.
Static functions can provide functionality related to an a particular class without requiring the programmer to first create an instance of that class.
See this comparison:
class Numbers
{
public int Add(int x, int y)
{
return x + y;
}
public static int AddNumbers(int x, int y)
{
return x + y;
}
}
class Main
{
//in this first case, we use the non-static version of the Add function
int z1 = (new Numbers()).Add(2, 4);
//in the second case, we use the static one
int z2 = Numbers.AddNumbers(3, 5);
}
Technically, answers above are correct.
But the examples are not correct from the OOP point of view.
For example you have a class like this:
class Zip
{
public static function zipFile($fileName)
{
//
}
public static function unzipFile($fileName)
{
//
}
}
The truth is that there is nothing object-oriented here. You just defined two functions which you need to call using the fancy syntax like Zip::zipFile($myFile) instead of just zipFile($myFile).
You don't create any objects here and the Zip class is only used as a namespace.
So in this case it is better to just define these functions outside of class, as regular functions. There are namespaces in php since version 5.3, you can use them if you want to group your functions.
With the OOP approach, your class would look like this:
class ZipArchive
{
private $_archiveFileName;
private $_files;
public function __construct($archiveFileName) {
$this->_archiveFileName = $archiveFileName;
$this->_files = [];
}
public function add($fileName)
{
$this->_files[] = $fileName;
return $this; // allows to chain calls
}
public function zip()
{
// zip the files into archive specified
// by $_archiveFileName
}
}
And then you can use it like this:
$archive = new ZipArchive('path/to/archive.zip');
$archive->add('file1')->add('file2')->zip();
What is more important, you can now use the zip functionality in an OOP way.
For example, you can have a base class Archive and sub-classes like ZipArchive, TarGzArchive, etc.
Now, you can create an instance of the specific sub-class and pass it to other code which will not even know if files are going to be zip-ped or tag.gz-ipped. For example:
if ($config['archive_type'] === 'targz') {
// use tar.gz if specified
$archive = new TarGzArchive($path);
} else {
// use zip by default
$archive = new ZipArchive($path);
}
$backup = new Backup($archive /*, other params*/);
$backup->run();
Now the $backup object will use the specified archive type. Internally it doesn't know and doesn't care how exactly files will be archived.
You can even have a CopyArchive class which will simply copy files to another location.
It is easy to do it this way because your archive support is written in OOP way. You have small object responsible for specific things, you create and combine them and get the result you want.
And if you just have a bunch of static methods instead of real class, you will be forced to write the procedural-style code.
So I would not recommend to use static methods to implement actual features of your application.
Static methods may be helpful to support logging, debugging, testing and similar things. Like if you want to count number of objects created, you can use class-level static counter, increment it in the constructor and you can have a static method which reads the counter and prints it or writes to the log file.
Yes, static classes are used for problems that require stateless computation. Such as adding two numbers. Zipping a file. Etc.
If your class requires state, where you need to store connections or other longer living entities, then you wouldn't use static.
AFAIK. Static methods does not depends on a class instance. Just that.
As an example:
If you have an single thread program that will have only ONE database connection and will do several queries against the database it will be better to implement it as a static class (note that I specified that you will not connect, ever to several databases or have several threads).
So you will not need to create several connection objects, because you already know that you will only use one. And you will not need to create several objects. Singletons in this scenario are, also, an option.
There are other examples.
If you create an class to convert values.
class Convert{
static std::string fromIntToString(int value);
}
This way you will not need to create the class convert every time you need to convert from integer to an string.
std::string value = Convert::fromIntToString(10).
If you haven't done that you would need to instantiate this class several times through your program.
I know that you can find several other examples. It is up to you and your scenario to decide when you are going to do that.

Hibernate noob - retrieve partial object

Greetings!
I have the following class and at times need to retrieve only title and subTitle elements:
public class Article implements Serializable {
private static final long serialVersionUID;
private int id;
private String title;
private String subTitle;
private String body;
....
}
What's the best way to facilitate this? I thought about making title and subTitle stand alone objects but I honestly don't know what I'm doing yet.
I have the luxury of changing the entire composition of Article, but asking first is the most sensible thing for me at the moment.
Thanks in advance.
You can annotate every simple property with LAZY -> just like this #Basic(fetch = FetchType.LAZY)
So, it will be loaded only if you need
Provided this is for displaying purpose, you could also rely on a ResultTransformer.
See this SO answer which deals with similar problem and limits the retrieved properties.
I think you can solve this by creating a specific class to hold the information you want, then you import it in your mapping. See 5.1.19.import in the manual. I believe you can use the imported class in your HQL, like this:
"select new Titles(a.title, a.subTitle) from Article a where a.id = :id"
Here's a blog post I found on this subject: http://gustavoringel.blogspot.com/2009/02/creating-dto-in-nhibernate-hql-using.html.
Good luck!

Best practice: ordering of public/protected/private within the class definition?

I am starting a new project from the ground up and want it to be clean / have good coding standards. In what order do the seasoned developers on here like to lay things out within a class?
A : 1) public methods 2) private methods 3) public vars 4) private vars
B : 1) public vars 2) private vars 3) public methods 4) private methods
C : 1) public vars 2) public methods 3) private methods 4)private vars
I generally like to put public static vars at the top, but then would a public static method be listed ahead of your constructor, or should the constructor always be listed first? That sort of thing...
I know it's finnicky but I just wondered: what are best practices for this?
PS: no I don't use Cc#. I know. I'm a luddite.
In Clean Code, Robert C. Martin advises coders to always put member variables at the top of the class (constants first, then private members) and methods should be ordered in such a way so that they read like a story that doesn't cause the reader to need to jump around the code too much. This is a more sensible way to organize code rather than by access modifier.
The best practice is to be consistent.
Personally, I prefer putting public methods first, followed by protected methods, following by private methods. Member data should in general always be private or protected, unless you have a good reason for it not to be so.
My rationale for putting public methods at the top is that it defines the interface for your class, so anyone perusing your header file should be able to see this information immediately.
In general, private and protected members are less important to most people looking at the header file, unless they are considering modifying the internals of the class. Keeping them "out of the way" ensures this information is maintained only on a need to know basis, one of the more important aspects of encapsulation.
Personally I like to have public at top, protected and then private. The reason for this is that when somebody cracks open the header he/she sees what he/she can access first, then more details as he/she scrolls down.
One should not have to look at the implementation details of a class in order to use it, then the class design is not done well.
I think I have a different philosophy on this than most. I prefer to group related items together. I can't stand having to jump around to work with a class. The code should flow and using a rather artificial ordering based on accessibility (public, private, protected etc. ) or instance versus static or member versus property versus function doesn't help keep a nice flow. So if I nave a public method Method that is implemented by private helper methods HelperMethodA, HelperMethodB etc. then rather than have these method far apart from each other in the file, I will keep them close to each other. Similarly, if i have an instance method that is implemented by a static method, I will group these together too.
So my classes often look like this:
class MyClass {
public string Method(int a) {
return HelperMethodA(a) + HelperMethodB(this.SomeStringMember);
}
string HelperMethodA(int a) { // returns some string }
string HelperMethodB(string s) { // returns some string }
public bool Equals(MyClass other) { return MyClass.Equals(this, other); }
public static bool Equals(MyClass left, MyClass right) { // return some bool }
public double SomeCalculation(double x, double y) {
if(x < 0) throw new ArgumentOutOfRangeException("x");
return DoSomeCalculation(x, y);
}
const double aConstant;
const double anotherConstant;
double DoSomeCalculation(double x, double y) {
return Math.Pow(aConstant, x) * Math.Sin(y)
+ this.SomeDoubleMember * anotherConstant;
}
}
This would be my ordering
Static Variables
Static Methods
Public Variables
Protected Variables
Private Variables
Constructors
Public Methods
Protected Methods
Private Methods
I use the following rules:
static before anything
variables before constructors before methods (i consider
constructors to be in the category of
methods)
public before protected before private
The idea is that you define the object (the data), before the behaviours (methods). Statics need to be separated because they aren't really part of the object, nor it's behaviour.
I used to care a lot. Over the last several years using modern IDEs pretty much everything is only 1 or 2 keystrokes away, I've let my standards relax substantially. Now, I start with statics, member variables, then constructors after that I don't worry about it much.
In C# I do let Resharper organize things automatically.
I generally agree with the public, protected, private order as well as the static data, member data, member functions order.
Though I sometimes group like members (getters & setters) I generally prefer listing members within a group ALPHABETICALLY so that they can be located more easily.
I also like lining up the data/functions vertically. I tab/space over to the right enough so that all names are aligned in the same column.
To each his own, and as Elzo says, modern IDEs have made it easier to find members and their modifiers in an easy way with colored icons in drop-down menus and such.
My take is that it is more important for the programmer to know what the class was designed for, and how it can be expected to behave.
So, if it is a Singleton, I put the semantics (static getInstance() class) first.
If it is a concrete factory, I put the getNew() function and the register / initialize functions first.
... and so on. When I say first, I mean soon after the c'tors and d'tor - since they are the default way of instantiating any class.
The functions that follow are then in:
logical call-order (e.g. initialize(), preProcess(), process(), postProcess() ), or
related functions together (like accessors, utilities, manipulators etc),
depending on if the class was meant primarily to be a data-store with some functions, or function provider with a few data members.
Some editors, like Eclipse and its offspring, allow you to reorder in the outline view the the vars and the methods, alphabetically or as in page.
The sequence of public followed by protected and private is more readable to me, It's better to describe the class logic in comments at top of the header file simply and function call orders to understand what a class dose and algorithms used inside.
I am using Qt c++ for a while and see some new sort of keywords like signal and slot I prefer to keep ordering like above and share my idea with you here.
#ifndef TEMPLATE_H
#define TEMPLATE_H
class ClassName
{
Q_OBJECT
Q_PROPERTY(qreal startValue READ startValue WRITE setStartValue)
Q_ENUMS(MyEnum)
public:
enum MyEnum {
Hello = 0x0,
World = 0x1
};
// constructors
explicit ClassName(QObject *parent = Q_NULLPTR);
~ClassName();
// getter and setters of member variables
// public functions (normal & virtual) -> orderby logic
public slots:
signals:
protected:
// protected functions it's rule followed like public functions
private slots:
private:
// methods
// members
};
#endif // TEMPLATE_H