80. Using var and implicit type casting to sustain the code's maintainability

In the previous section, Using var with primitive types, we saw that combining var with implicit type casting can cause real problems. But in certain scenarios, this combination can be advantageous and sustain the code's maintainability.

Let's consider the following scenario—we need to write a method that sits between two existing methods of an external API named ShoppingAddicted (by extrapolation, these methods can be two web services, endpoints, and so on). One method is dedicated to returning the best price for a given shopping cart. Basically, this method takes a bunch of products and queries different online stores to fetch the best price.

The resulting price is returned as int. A stub of this method is listed as follows:

public static int fetchBestPrice(String[] products) {

float realprice = 399.99F; // code to query the prices in stores
int price = (int) realprice;

return price;
}

The other method receives the price as int and performs the payment. If the payment is successful, it returns true:

public static boolean debitCard(int amount) {

return true;
}

Now, by programming with respect to this code, our method will act as a client, as follows (the customers can decide what items to buy, and our code will return the best price for them and debit their cards accordingly):

// Avoid
public static boolean purchaseCart(long customerId) {

int price = ShoppingAddicted.fetchBestPrice(new String[0]);
boolean paid = ShoppingAddicted.debitCard(price);

return paid;
}

But after some time, the owners of the ShoppingAddicted API realize that they lose money by converting the real price into int (for example, the real price is 399.99, but in int form, it's 399.0, which means a loss of 99 cents). So, they decide to quit this practice and return the real price as float:

public static float fetchBestPrice(String[] products) {

float realprice = 399.99F; // code to query the prices in stores

return realprice;
}

Since the returned price is float, debitCard() is updated as well:

public static boolean debitCard(float amount) {

return true;
}

But once we upgrade to the new release of the ShoppingAddicted API, the code will fail with a possible lossy conversion from float into int exceptions. This is normal since our code expects int. Since our code doesn't tolerate these modifications well, the code needs to be modified accordingly.

Nevertheless, if we have anticipated this situation and used var instead of int, then the code will work without problems thanks to implicit type casting:

// Prefer
public static boolean purchaseCart(long customerId) {

var price = ShoppingAddicted.fetchBestPrice(new String[0]);
var paid = ShoppingAddicted.debitCard(price);

return paid;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset