简体   繁体   中英

How to make an important unary minus stand out in code?

I have an entity that represents a reservation of some quantity. There will also exist entities where this property is negative indicating a lack of availability for the reservation. The logic will then decrease the quantity of a reservation with a positive quantity property value. Therefore I have this statement:

long quantityToDecrease = -reservation.getQuantity();

How can I make the unary minus stand out so that the reader of my code will be aware of it?

I went with the inline comment and empty lines around it:

// note the unary minus
long quantityToDecrease = -reservation.getQuantity();

But I also do find the solution suggested by @Kayaman appealing, because it makes the code read more like the busines logic is described.

To make it really stand out you can make a seperate method and maybe in a seperate class:

long quantityToDecrease = negate(reservation.getQuantity());

It may look like over kill, but I think this way you will get the readers attention the best.

Also if you use this in a lot of places maybe you can write your own NumberUtil class or something in that direction, where you can define your negate method in. Making it something like:

long quantityToDecrease = NumberUtil.negate(reservation.getQuantity());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM