I am writing a financial application where the concept of 'Price' is used a lot. It's currently represented by the C# decimal type. I would like to make it more explicit and be able to change it to maybe double in the future, so I was thinking of creating a 'Price' struct that would basically act exactly the same as the decimal type (maybe add a bit of validation like must be greater than 0).

What do you think are the pros and cons of doing this?

Comments

perhaps it should be instead a member of a prototype/virtual class that is inherited by the item class, accessed with get/setters?

Written by Nona Urbiz

@Nona: Sorry, I don't get it. What exactly do you mean and what is that good for?

Written by Hermann

well I could be wrong, but it seems (to me) like a struct should be used to contain a set of values, not to just be a wrapper for a single piece of data. Because "price" is a single piece of data, and because price on its own is useless (price of what?), it should instead be a property of the larger class (price of Item). The g/setters will allow you to later put logic into their retrieval/alterations. Finally, I suggested a virtual class to allow you to have fundamentally different Item types but inherit their base characteristics, and forcing you to override what you know will change.

Written by Nona Urbiz

This sounds like a great time to apply the YAGNI principle. You Ain't Gonna Need It. I would not be designing my data types for the possibility that someday I might want to refactor them in the future. Premature generality is expensive, and you don't know what your needs are going to be in the future. What makes a program extensible in the future is not an excessive amount of abstraction to permit you to change implementation details, but rather a clean, clear model of business domain concepts. If you get the model right, you can extend the model to new scenarios in the future.

Written by Eric Lippert

Next to the YAGNI principle (which it is : I would & maybe in one sentence)... I'd like to say that doubles are not really the preffered data-type to use when it comes in storing monetary amounts.

Accepted Answer

There shouldn't be a reason to change the data type for a quantity like this; however, you may decide to add other information such as the currency or the number of decimal places to keep track of in calculations, so using a struct at this point will save you a LOT of time down the road.

Written by Jon Seigel
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki