0

Let's say I have a very simple program that adds/edits/removes and lists products, and I don't want to make the user install a data base in his machine. Would it be a bad idea to store all the products in a single class and then serialize/save it whenever a change is made?

The class would be something like this for example:

public class MyProducts implements Serializable {

    private List<Product> products;

    public void AddProduct(Product p) {
        // Adds a product...
    }

    public void RemoveProduct(Product p) {
        // Removes a product...
    }
}

Have in mind that it would be a simple program, nothing critical, just so that I don't need to bother with relational data base in such a simple software.

Scenario 2: In a real software, would it be a good idea to store the program's configuration/preferences in a serialized file?

Thanks!

FelipeKunzler
  • 1,204
  • 1
  • 11
  • 17
  • 1
    Java has a Preferences API, working quite well. – Arnaud Dec 07 '15 at 16:30
  • Re. your first question, I don't think it's bad. A database is better, but if the data isn't too large then a simple file should be quick to read. – markspace Dec 07 '15 at 16:30
  • Re. the Preferences API, on Windows Java stores preferences in the Registry, which is not ideal imo. Use the Preferences API for the simplest information, like the default directory where all the real configuration is stored. – markspace Dec 07 '15 at 16:32
  • SQLite could be an option. – syck Dec 07 '15 at 16:48

1 Answers1

1

This is probably a Bad Idea (TM) because:

  1. any change requires rewriting the entire file
  2. there is no data integrity guarantee - no ACID
  3. you cannot, in the future, query the file - everything must be in memory.

I would suggest a file based database. There are literally hundreds of embedded database programs for Java, for example:

Why not use one of them?

If you do want to store the data in a file consider:

  • defining serialversionuid so that you can control backwards compatibility
  • possibly using a human readable format such as JSON, rather than Java serialisation, this also has the advantage of being faster.

To answer your last question, in a "real software" I would expect something like a file-database driven with JPA to be used. With current tools, such a Spring Boot, this is almost configuration free.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166