2

I am trying to make a Retail Store program, just for practice. It consists of a simple window with an editable JTable, showing the existing items for sell, along with its properties (price, stock, name, etc.) I would like these properties to be fully customizable (add or remove any), so the way I thought of it was to make an "Item" class which holds a list of "Property" objects. In the "Property" class I wrote two variables as follows

String name;
Float value;

The problem I have is, what if a property is a non numeric value? Such as the name of a product for example. I have thought of possible solutions to this but I am not convinced with them, so I would like to hear what would you do instead or what would be the best option in terms of good programming practices.

So far I've come up with these ideas:

  • Use a String type: but this wouldn't let me operate with the value as numbers, which I may need for prices (although I know I can sort out this using parseFloat() or similar but it doesn't seem optimal)
  • Use an Object type: with this I would need to store somewhere which type the value is, to cast it later, I could use an Enum type to do it, but also casting every time looks a bit like hard coding, I don't think is a good idea either
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
lautar0
  • 23
  • 4
  • 1
    Welcome! Incidentally, it's tempting to use `float` or `double` to represent prices, but that can cause problems. See https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – dnault Feb 05 '20 at 01:19
  • You could model it as a "typesafe heterogeneous container". See https://stackoverflow.com/questions/49761657/alternative-to-map-of-java-lang-object/49761937#49761937 – dnault Feb 05 '20 at 01:26

1 Answers1

2

Even if you limited yourself to numeric properties, price is a different type of number from weight. Adding in string properties makes it more difficult to manage just one property class.

One answer is to have more than one property class. One for strings, one for integer numbers, and one for prices. A reason to separate prices from other numbers is that you want to be careful when adding and subtracting prices.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111