I have this class that tries multiple methods of getting data from Google maps web services API.
If one method fails, it tries another. etc.
Something like this (pseudo code):
FUNCTION FIND_ADDRESS( house_number, postcode )
get location co-ordinates for postcode from local database
if location returns false, try getting location from maps service
if map service fails, return "postcode not found", exit
get address components using location co-ordinates
if address components doesn't contain street name, return street name not found, exit
if street name exists, get all address_components + location for house number, street_name and postcode
if no results, try again without the postcode,
if still no results, return location co-ordinates for postcode found earlier in code
END
As you can see, This is very procedural!
I'm trying to think of ways to improve the code, and I've externalised all re-usable code, added exception handling to know exactly where the code fails if it does.
But I was wondering if anybody knows of a design pattern or similar solution.
Because I'm basically trying something, if it fails trying something else, if it fails trying something else and so on until I get a full address
Any ideas?
You might want to look into Chain of Responsibility.
In Object Oriented Design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
So instead of having many if/else or try/catch blocks, you do something like
$finderChain = new AddressFinder;
$finder
->add(new LocalFinder)
->add(new MapsService)
->add(…);
$result = $finder->find($houseNo, $postCode);
Internally, you will send $houseNo and $postCode to the LocalFinder. If it doesn't find the desired data, the next element in the chain is tasked with trying to find the desired data. This is repeated until either the end of the chain is reached or the desired data was produced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With