Hi,
I’m writing a utility class to contain common functionality used throughout an app, but that isn’t provided standard by JS (or not widely supported).
The utility class contains methods related to a few different areas. Strings, arrays, url formatting, etc.
The problem I’m having is that of separating namespaces and logically grouping the class.
At the moment my utility class is flat, and methods look like this:
[CODE]
otUtil.arrayContains()
otUtil.arrayRemove()
otUtil.arrayWhatever()
otUtil.stringContains()
otUtil.stringWhatever()
otUtil.urlEncode()
otUtil.urlWhatever()
This seems a bit of a pain though, having the type prefixed on every utility function.
I considered a possibility of creating namespaces, so that you access functions like this:
[CODE]
otUtil.array.contains()
otUtil.array.remove()
otUtil.array.whatever()
otUtil.string.contains()
otUtil.string.Whatever()
otUtil.url.Encode()
otUtil.url.whatever()
This has the benefit that we don’t need to prefix types in function names, and also makes the API more clean by introducing clear namespaces for each group of functions.
I have also seen people implementing functionality directly on the prototype of objects they use. For example you can add the contains() method to the array prototype, so that you can do
[CODE]
var a = []
//do stuff with a
if (a.contains(b) {
//do stuff here
}
This seems reasonable, except it only works for well defined types that are instantiated from that prototype (this is not the case for a lot of objects that I want to call utility functions on).
It also makes it harder to see usages of the utility functions, because if we use the above method you can easily search for “otUtil.methodName(” in the codebase to find places of use.
I am not overly experienced with Javascript, so I do not know the best practices when creating utility classes (I know this isn’t a class, but you know what I mean) in this language.
I would greatly appreciate hearing peoples insight, advice and techniques for doing this elegantly.
Cheers