Chris Kennon wrote:
Hi,
If my understanding of encapsulation is misguided, please correct. In
the following code snippet, should in the interest if encapsulation,
the "Good Morning/Afternoon" strings be called from another function?
That depends on exactly how you interpret "formatTime". The point of
encapsulation is not that your code embodies an ideal, but that it
separates unrelated functions in a way that is useful to you.
In the case of a time formatting function, I would argue that you might
wish to put a string representation of the current time into many
contexts. Maybe a character in a game says "It is now 12:34PM. Good
morning!" Or maybe a desktop clock displays only mm:ss. Maybe a logging
application displays a timestamp before every log message. It isn't
likely you'll want to say "The current time is:" or "Good morning!" in
all of these cases.
It would probably be more useful to have a function, formatTime, which
returns only a string representing the time itself; and then construct
strings like this: "It's " + formatTime(myDate) + "! Time to make the
donuts!"
Or if you want the best of both worlds, do this:
function formatTime(date:Date):String
{
// return the time string
}
getTimeGreeting(date:Date):String
{
var timeString:String = formatTime(date);
var greeting:String = "The time is now " + timeString + ".";
if (date.getHours() < 12)
{
greeting += " Good morning!";
}
else
{
greeting += " Good afternoon... or night.";
}
return greeting;
}
This way, you have two functions, each of which does only what it
should, no more or less. Just remember that "should" is always based
strictly on the needs of your application... with a little room for
future expansion or revision. A lot of the main point of encapsulation
-- and object orientation itself -- is that it makes it easier to alter
or re-use code later.
_______________________________________________
Flashcoders mailing list
Flashcoders@chattyfig.figleaf.com
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders