In the previous eight posts, we have designed a program to calculate the age of a tree, given its circumference, and species. In these basic lessons, the core techniques for writing a program in Julia have been covered. Along the way we made changes to the basic program which improved both its functionality, and the the code within it. Now let’s look briefly at the codes style. Style you say… why is that important? It is important because while compilers or interpreters don’t care what a program looks like, humans do. It’s nice to look at a program that is formatted in an aesthetically pleasing manner. Here is the program as it stands:
function readNum(str)
print(str)
c = parse(Int, chomp(readline()))
return c
end
n = readNum("How many trees? ")
species = ["Silver Maple", "White Birch", "Black Walnut",
"Red Oak", "White Oak", "American Elm"]
g = [3.0, 5.0, 4.5, 4.0, 5.0, 4.0]
for i=1:n
c = readNum("Enter the circumference of the tree (inches): ")
println("Tree Species: ")
for i=1:length(species)
println("(",i,") ",species[i])
end
t = readNum("Choose a tree (?): ")
d = c / pi
age = d * g[t]
println("The ", species[i], " is ", round(age,digits=2), " years old")
end
It is already quite well formatted, with 3-space indenting (see previous posts on indenting), and good whitespace between sections. There are only two things not quite right: (i) poorly named variables, and (ii) a lack of comments. Variable names like c, and g and non-descriptive, so therefore require a comment, which is wasteful. If they were better named, there would be no need to comment them. Comments are important to inform the reader of a program what is going on. They are really only needed for parts of the program which are not self-explanatory (i.e. complex pieces of code). Here is the program with better style:
# This program calculates the approximate age of a tree using
# the measured circumference of a trunk (4ft from the ground),
# and a growth factor specific to the species of tree.
function readNum(str)
print(str)
aNum = parse(Int, chomp(readline()))
return aNum
end
nTrees = readNum("How many trees? ")
species = ["Silver Maple", "White Birch", "Black Walnut",
"Red Oak", "White Oak", "American Elm"]
growthF = [3.0, 5.0, 4.5, 4.0, 5.0, 4.0]
for i=1:nTrees
treeCirc = readNum("Enter the circumference of the tree (inches): ")
println("Tree Species: ")
for i=1:length(species)
println("(",i,") ",species[i])
end
menuItem = readNum("Choose a tree (?): ")
treeDiam = treeCirc / pi
treeAge = treeDiam * growthF[menuItem]
println("The ", species[i], " is ", round(treeAge,digits=2), " years old")
end
The pink code shows variables that have been modified with better names. The orange code, an overall comment on what the program does – there is no need for specific comments in the program, as the variables are descriptive, and the code short and self–explanatory.