...
/Part 2: Creating Functions for an Automatic Light Application
Part 2: Creating Functions for an Automatic Light Application
Learn how to modularize the logic into multiple functions in our automatic light application.
We'll cover the following...
Splitting the code further
In the previous lesson, we wrote code for our automatic light application. Reading this code is hard and confusing. What can we do about it? Functions are the answer, so let’s see how that works.
When breaking long code into small functions, we must remember that a function should do one thing or answer one question.
One trick we can use to identify separate tasks within the code is to read it from beginning to end, and when we feel that the application shifts its focus from one thing to another, we can insert a blank line into the code. Let’s do that for the application that we have created so far:
while truelocation = Locationmy_latitude = location.get_latitude()my_longitude = location.get_longitude()home_latitude = 48.870320home_longitude = 2.286560earth_radius = 6371my_lat_radians = radians(my_latitude)my_long_radians = radians(my_longitude)home_lat_radians = radians(home_latitude)home_long_radians = radians(home_longitude)lat_distance = home_lat_radians – my_lat_radianslong_distance = home_long_radians – my_long_radiansa = sin(lat_distance / 2)**2 + cos(my_lat_radians) *cos(home_lat_radians) * sin(long_distance / 2)**2distance = 2 * earth_radius * asin(sqrt(a))if distance < 0.5 then# some code that connects to the home computer# some code that sends a notification to home computerend_ifend_while
As we can see, there are now blocks of code separated by blank lines. Let’s study them closely.
There’s nothing we can do about the first line with while
, at least not at this point. It will just sit at the top and make sure that we repeat the code over and over.
After the line with while
, we have lines 2–4, which all have to do with establishing our location. When reading the code, we should ask ourselves, what task does this line help us to accomplish? For all of these lines, the answer will be to answer the question, “Where are we?” But when we hit the line that begins with home_latitude
on line 6, this is no longer true. We’re now in a block of code that does something else. The code has shifted focus, so we insert a blank line.
We now have two lines, lines 6– 7, that answer the ...