On 2/17/06, Aaron Roberson <[EMAIL PROTECTED]> wrote:
>
> In my Java book it says that if a method is public, a data filed could
> be assigned a value directly, BUT doing so "violates an important
> principle of object-oriented programming -- that of data hiding using
> encapsulation.
>
> However, I have seen alot of CF developers write code that directly
> assigns values to data fields in CFC's like the following:
Officially, yes, true object oriented programming does not allow you to
access variables in an object directly. You can reference constants
directly, but never set or retrieve variables.
In the CFC world I don't think there is any such thing as a constant, so
you're either going to program get/set methods, or you're not.
My preference - for the most part - is not.
In a large development environment, with many developers working on
difference pieces of a project, it does make sense to do this kind of
encapsulation, because it protects your variables and allows you to
control what values they contain.
For example, if you're using the this scope to store an ID variable that
is an integer, if you ALLOW that variable to be set from the outside
world (maybe someone elses CFC), then they could easily set it to "foo",
and suddenly something doesn't work the way they expect it to and it
breaks in YOUR code.
In the world of encapsulation, you control how that variable is set.
This example only returns "false" but it could return or log a more
specific error message.
<cfcomponent>
<cfset variables.id = 0
<cffunction name="setID" access="public" output="false"
returnType="boolean" hint="pretend ID must be a non negative 10 digit
number that starts with 10">
<cfargument name="id" type="numeric" required="yes">
<cfif id neq int(id)>
<!--- it's not an integer --->
<cfreturn false>
<cfelseif id neq abs(id)>
<!--- it's a negative number --->
<cfreturn false>
<cfelseif len(id) neq 10>
<!--- it's not 10 digits --->
<cfreturn false>
<cfelseif left(id,2) neq "10">
<!--- it doesn't start with "10" --->
<cfreturn false>
<cfelse>
<cfset variables.id = id>
<cfreturn true>
</cfif>
</cffunction>
</cfcomponent>
This forces other programmers using your CFC to send proper data to the
variable, or setting the variable will fail, preventing unknown
consequences later in the application.
Rick
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
Message: http://www.houseoffusion.com/lists.cfm/link=i:4:232678
Archives: http://www.houseoffusion.com/cf_lists/threads.cfm/4
Subscription: http://www.houseoffusion.com/lists.cfm/link=s:4
Unsubscribe: http://www.houseoffusion.com/cf_lists/unsubscribe.cfm?user=89.70.4
Donations & Support: http://www.houseoffusion.com/tiny.cfm/54