Why is the location of a handler important?

Member Peavine made a post to this thread over on the code exchange forum : Saving Persistent Values - #8 by bmose
where he posted a more generalised form of some code that I found on the web and used to maintain user settings/preferences in a script. The code I found and the more generalised example that Peavine posted use a script object.

In his post Peavine makes a passing comment that implies the location of the read and write handlers are important with the read having to be placed at the top and the write at the bottom of the main script:

The get handler would normally be placed at the beginning of the script:

set thePreferences to getPreferences() --returns a list of two values

on getPreferences()
	set theScript to (path to preferences as text) & "test.scpt" --set to desired value
	try
		set thePreferences to load script file theScript
		return {preferenceOne of thePreferences, preferenceTwo of thePreferences}
	on error
		return {"Default Value One", "Default Value Two"} --set to desired values
	end try
end getPreferences

The write handler would normally be placed at the end of the script:

writePreferences("Test Value One", "Test Value Two")

on writePreferences(valueOne, valueTwo)
	set theScript to (path to preferences as text) & "test.scpt" --set to desired value
	script thePreferences
		property preferenceOne : valueOne
		property preferenceTwo : valueTwo
	end script
	store script thePreferences in file theScript replacing yes
end writePreferences
type or paste code here

I think I read somewhere that script objects have to be declared at the beginning of a script but I would welcome some more information from those in the know.

I took that as meaning “you would call this handler at the start/end of the script”, i.e. you would load preferences at the start, do whatever needs to be done, make changes to preferences as needed, then save the preferences at the end.

In most cases (unless doing some odd things with properties and ObjC objects), the location of handler definitions does not matter from a functionality standpoint.

1 Like

This is my understanding, thanks for the clarification.