I wrote a simple tag manager class in matlab, and I’m struggling (or maybe over-thinking 😉 with naming my class methods appropriately. The class is called tag_manager. Here are my question regarding a clear API and implementation:
- for adding a tag, should I call the method
addoradd_tag? same goes for removing. - for renaming a tag, should I call the method
rename_tagorrename?
I always feel like adding the _tag suffix, so that it is clear what a method is acting upon.
nbr_tagsis a counter that keep track on the number of tags that are currently stored. I sometimes need to access this number, and so instead of going through the list of tags and calculating the number of entries, I thought to return this value through a class method. Isreturn_nbr_tagsthe way to go, or could this be named more succinctly?- Very often, I need to know the index of a tag, which is in turn used to look up some elements in some other matrix. In order to prevent code to become to long, I called this method simply
inx()which is supposed to be an abbreviation forreturn_tag_index. I’m aware that today I do know whatinx()stands for, but in two weeks from now I’ll probably won’t be able to remember. So what is the best way of naming these kind of methods?
here’s the class definition:
properties (SetAccess = private, GetAccess = public)
tag_names = {}; % store the tags
tag_rel_indx = []; % the relative tag index
tag_abs_indx = []; % the absolute tag index
end
properties (SetAccess = private, GetAccess = public, Hidden = true)
nbr_tags = 0;
abs_tag_counter = 0;
end
methods
% add single tag to list. should be 'add' or 'add_tag'?
function obj = add_tag(obj, name)
end
% remove single tag from list
function obj = remove_tag(obj, name)
end
% short-cut for 'return_tag_index'
function indx = inx(obj, name)
indx = return_tag_index(obj, name);
end
% rename tag
function obj = rename_tag(obj, old_name, new_name)
end
% re-order tags by name
function obj = reorder_by_name(obj)
end
% return number of tags stored in tagmanager
function nbr_tags = return_nbr_tags(obj)
nbr_tags = obj.nbr_tags;
end
end
Thanks a lot!
There is always a trade-off between using highly explicit function names (which is really helpful to understand code) and creating code that’s easy to develop and use. If you need to make shortcut names for methods, it’s a sign that you have moved to far toward explicit function names.
In your case, since you’re creating a tag manager, I would drop
tagfrom the methods, and instead start the convention of instantiating your tag manager class astags = tagManager;, such that the method of adding tags is written eithertags.add(...)oradd(tags,...). Adding more explicit method names will help, though, when you’re adding something other than tags, e.g.tags.addGroup. Your index method then becomesindex(tags,name), which is, in my eyes, both short and clear.PS: Why have a
returnNumberOfTagsmethod? You can just read from the property, and add set/get methods if necessary.