Does is break SRP to keep incompatible physical units and quantities together in the same class, where quantities describe an object?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/395149

Question

I want to design a Crate object. A crate is a wooden box that stores things. I need to be able to keep track of of the following things in regards to this crate:

  • length in inches
  • width in inches
  • height in inches
  • weight in pounds
  • price of crate in dollars

My question

can I store all of the above in the same class? Does it break SRP if I store the quantities in the same class?

An alternative, for example will be to break up the class into 3:

  • CrateDimensions (length, width, height)
  • CrateWeight (weight)
  • CratePrice (price)

My specific use case is as follows: I have various many products that can be put into the crate. Based on those products I have code that creates the crate - sets up initial dimensions and weight of the product inside the crate, and if more product is added, the crate dimensions are adjusted, as well as the weight. Price is something that is not currently added, but will be added later.

Was it helpful?

Solution

There's nothing inherently wrong with your design, although as @RobertHarvey points out in the comments, you might want to treat price separately, as that can depend on a lot of things besides the crate itself. That's dependent on your business rules in regards to price, though.

Your Crate class does have one responsibility - describing a crate. Dimensions and weight are pretty integral for describing a physical object, especially when your use case seems to be to use it for containing objects of specified dimensions and weights. From what you've told us, it sounds like a pretty good class.

You might find that you want to extract the set of dimensions into a Dimensions class, which would contain properties for Length, Width, and Height. You could then add some methods / operator overloads to e.g., handle adding two Dimensions together, which I'm guessing you do as you pack items into the crate. Your Crate and Product classes could both use this Dimension class, making your arithmetic a bit less messy.

The use of a Dimensions class doesn't take away from the benefit of having the Crate class hold its own dimensions, whether its as a single property or 3 different ones.

OTHER TIPS

Up to now, you've only described attributes, no responsibilities at all. This isn't actually object-oriented, and the SRP isn't applicable. Start by looking at what you want to do in your application, and what roles the crate plays in it. Attributes come later as needed to fulfill these roles. If you find that the Crate object's only responsibility is to hold attribute values for some algorithms to work with, then that's its responsibility, and SRP isn't violated.

Licensed under: CC-BY-SA with attribution
scroll top