Don't use the nouns "Object", "Manager", "Handler", or "Data" in class names. These words say nothing about the responsibility of the class, leading maintenance programmers to lump all kinds of irrelevant crap into the class. Think instead about what the class is actually supposed to do and name it after that.
Simple solution: Just replace all occurrences of these words with "Thing". -- AnonymousDonor
I agree about Object and Data (and would probably add other null-words like "Value" and "Item"), but "Manager" and "Handler" seem too useful to let go. Some examples from a web server I wrote a while back:
Easiest to follow the DesignPatterns names. This sounds like a CommandPattern, so I'd use GetCommand, PostCommand, etc.
Or, since this is an EventDispatcher?, you could use methods like onGet or onPost. This, to me, clearly states that they are called in response to an event. -- JeffPanici
- Each HTTP request supported by the server has an associated handler "GetHandler", "PostHandler" etc. What else should I call these?
OK. In conjunction with comments below about the use of a 'get' prefix, I would be prepared to use the likes of HTTPGetCommand, but I still feel that the objects I'm describing are really "handlers", in the spirit of event handlers and so on.
Again following DesignPatterns, call it a CommandInterpreter?. One of the best things about the pattern books is they give us good names for almost any occasion.
- When the server starts up, all the supported handlers are registered with a "HandlerManager" object which delegates requests to the appropriate handler or to a default handler if none of the registered handlers own up to supporting that request type. What do you recommend this be called?
Except that in this case it isn't. The "manager" only knows about "handlers", in particular that each has a supports(String) method and a handle (R
equestContext) method. The manager allows handlers to be added and removed, and iterates through the available handlers in order asking each one if it supports the supplied request until one does, then calls its handle method.
, this is nearest to ChainOfResponsibilityPattern
, but that's the clumsiest name in the book! Would you prefer 'Chainer' or some other neologism? And note that the GangOfFour
refer throughout chain of responsibility to 'Handler' objects, so I'm in illustrious company.
You certainly have a good point. Perhaps then call them Command and ChainOfCommand??
Your manager is dispatching incoming requests to the appropriate handlers, so how about "M
essageDispatcher"? It can also be seen as demultiplexing requests based on their HTTP headers, so "HTTPDemultiplexor" might be descriptive. Also, Demux is a widely used abbreviation of Demultiplexor, so HTTPDemux is convenient and descriptive. -- Anon
It's amazing how many patterns could be appropriate: may I suggest "Listener"? -- DaveWhipp
Looking at these examples, I can't see how the alternatives of 'Interpreter' or 'Dispatcher' are any better. I think it would be unwise to completely ban the use of 'Handler' or 'Manager', but rather encourage programmers to put effort into thinking up more suitable alternatives. -- MikeWeller
I can't think of a good reason for using Data in a name, but there are instances when Object is acceptable - java.lang.Object, or org.omg.CORBA.Object, for example. In these cases, the name Object means "anything, but you should subclass to use it". (See ObjectSystemPatterns
) To me, the name Data suggests a ParameterBlock
Although I admit that Object and Data are weak names, I cannot encourage the banning of identifier names in such a general way. Sure as eggs, if I accept DontNameClassesObjectManagerHandlerOrData
, next month there will be DontNameClassesEntityComponentElementOrItem?
and then DontNameClassesNodeInterfaceExceptionOrTools?
and soon enough I will have to be writing my code in some other language to avoid banned words. -- JohnFarrell
This is an excellent point. Care must be taken to avoid having the DesignPatterns
names become so ubiquitous that they become as meaningless as the semantic nulls warned of here. In the right context, Handler could be as meaningful as Listener. (Perhaps used in a naming scheme as a suffix for callbacks.) -- DavidConrad
Regarding the use of Data: There is a common term in telecommunication protocols: Payload Data Unit. When implementing such protocols, everyone would kill you, if you don't name the object representing the payload data unit something like PayloadDataUnit. Period. No exception.
We just use PDU. It is so well understood that even the managers talk about PDUs.
Maybe you should just walk down the hall and talk to someone on an unrelated project. If someone asks me what G
etHandler is responsible for I'll tell them it sounds like a method that returns a handler - probably a factory method. Tell me it's a class and I'll say that it probably handles some kind of "get" command. Personally I'd just name the thing H
ttpGet. "handler" is one of about a gazillion words that has little or no semantic meaning. It would be nice to have a tech writer hanging around the project to help out with these kinds of naming problems. -- PhilGoodwin
I'm trying hard not to argue for the sake of it, but I can easily envisage a situation where H
ttpGet would be a relatively static description of the characteristics of a GET request, and H
ttpGetHandler would be the object which handles the request. Surely in this case the "Handler" provides useful semantics. -- FrankCarver
Let's put this constructively. Name your classes anything you want. Then delete words that don't add any meaning. Examples of words that are unlikely to add meaning are Object, Manager, Handler, Data, Entity, Component, Element, Item, and Thing. If deleting a nothing word would result in a clash (Drawing and DrawingObject?), find a SystemOfNames that helps you resolve the conflict (Drawing and Figure).
A note on "Manager". When you're designing systems with large-grained objects (components), you often need to provide objects that manage a set of (smaller) instances. I don't think it's a problem to call these managers. For example, a C
ustomerManager manages a set of Customers. It's not just a factory, it's more a facade. Often the manager is exposed remotely, the instances are passed around as parameters. [I await to be told I should call the manager a facade, then! - This GOF political correctness is becoming tiresome.] -- JohnDaniels
Perhaps the one that pisses me off the most is "IClassFactory". This was probably the largest mental block I had to overcome in learning COM programming. What do you get when you instantiate a C
oClass? An IClassFactory, of course! Now, is it a Class, or a Factory? After I overcame that hurdle, I started to wonder if there was a standard Interface named "IFloorWaxDessertTopping". -- JohnDuncan
More notes on Manager, from Taligent's Guide to Designing Programs:
... For example, suppose you want a function to apply to multiple windows, such as CloseAllOpenWindows. The wrong way to do this is to have clients call a TWindowManager class. The correct way is to make CloseAllOpenWindows a static member of TWindow. It is associated with the class it applies to, and its multiobject function is reflected by its being static.
This is the top level link, the quote is from the "Managers aren't Objects" section.
Yes, a class with Manager in the name is generally procedural code written in an object-oriented language. It's code acting on data,
which is why it was called a manager. It's acting on something external rather than acting on itself. To me, this is one of the CodeSmell
One issue I found with web stuff is that a command could appear in 2 forms: once on output embedded in HTML pages, and once on input as an HTTP request. In a fairly strong sense these were "the same thing" and so needed the same name, and "handler" seemed a good suffix to distinguish between the former and the latter. Eg I might have Vote
Command and Vote
Handler. A "handler" to me is more dynamic then "command", patterns book notwithstanding. -- DaveHarris
Two classes, three nouns... Maybe your code is telling you that it needs a Vote class. ;)
It has one; a Vote is the thing acted upon by a vote command. It is concerned with vote semantics and has nothing to do with HTML/HTTP.
It now occurs to me that ModelViewPresenter
terminology would probably work. Vote is like a model and the HTML renderer could be Vote
View. This has the virtue of consistency with the patterns book. Prior standards aside, Command and Handler are pretty similar. -- DaveHarris
So my class named DataObjectHandler
is a no-no, then? To be fair, it wraps the COM IDataObject interface.
I think the "DataObject" part falls within a predefined SystemOfNames owned by COM in this case. The Handler part I'm not so sure about: since it wraps, why not Wrapper? -jh
The real world is filled with managers. Managers are real and fill a real purpose. Don't throw the baby out with the diaper. It's not the name that stinks it's the class.
Eh? Where do you work? Here, the managers are definitely phony and purposeless. They don't even have a clue.
(Seriously, such a name is a flag that there may be a problem. Think about why you can't come up with a more specific name for the class.)
The definition of manager is:
- One who handles, controls, or directs, especially:
- One who directs a business or other enterprise.
- One who controls resources and expenditures, as of a household.
This is a very common job of higher layer objects. All I see is the assertion that manager is the sign of a problem with no proof offered.
General terms are often more useful than specific terms. To me, what explains the specific meaning of a word like, say, "Manager", is the context in which it's found! It seems to make little sense to go out of one's way to give classes names like: ClassInChargeOfAllocatingAndUpdatingAndDeallocatingLittleStructuresCalledWilliam.
That's why you name it WilliamFactory?
Most uses of Manager can be replaced with something more specific. Manages creation or a pool of objects? FooManager?
. Manages a strategy selection policy that furnishes different algorithms for different input sizes? FooManager?
. And so on.
I come to think of the -er-er
principle, stated by PeterCoad
], that is to challenge any class name that ends in -er
. If it has no parts, change the name of the class to what each object is managing. If it has parts, put as much work in the parts that the parts know enough to do themselves.
IMHO classes named like managers, administrators, handlers etc, are usually introduced quite early in a design and are signs of poor "object think". They could be valid in highly generic use, as in frameworks etc. -- MagnusNyberg?
Again an assertion without a base. Handlers are usually abstract interfaces between layers. It's the derived classes that produce instances that have specific names. The abstract layers are more like roles and have more generic names. Managers are usually higher layer objects the make use of sequence many resources to implement a behaviour. Manager is also often a collection and would be responsible for instantiating its instances from the database, for example. It would also implement the filter on the collection etc. It may do a lot of other things to the collection as a whole. Manager seems a perfectly good name. Most of the other names just sound silly and artificial and seem to be even more confusing. Works like Command, Facade, Chainer, and Get are so general as to confuse.
The correct way is to make C
loseAllOpenWindows a static member of TWindow. It is associated with the class it applies to, and its multiobject function is reflected by its being static.''
This is exactly the wrong way in C++ or java. Static methods can't be overridden and thus cannot provide polymorphic behaviour or replacable/configurable behaviour. A manager/container implementing collective behaviours is far more powerful. -- AnonymousDonor
If you're using Java, you just may have to give up on decent OO code. Doctor, it hurts when I do that. -- francis (ducking)
IMHO, this is exactly the right way in C++. You don't need your static members to be overridden because your static members operate on static data that tells the static members how to do their jobs. It's pretty trivial to come up with a way to nearly-automagically register derived classes into the static class factory that lives in the base class, for instance.
Also, why would you want something like C
loseAllOpenWindows to be polymorphically replaced? You don't, that's the point. The TWindow class has a static list of open windows, and C
loseAllOpenWindows marches through that list calling Close on each TWindow. You do the polymorphic work in Close.
A static TWindow.CloseAllOpenWindows smells funny to me. It makes more sense as an instance method on TWindowStation. It makes even more sense when you're talking about an application that displays windows on more than one station. Then again, I tend to find any class methods outside of constructors rather whiffy, and I'm tempted to write up StaticSmell?. -- JeffreyHantin
IMHO again, this is completely proper OO code. TWindow is a class that manages itself. You don't need a TWindowManager because anything it needs to do could just get tossed into the static interface of TWindow. I suppose I should come clean and think that SingletonsAreEvil
, and manager classes seem to have a predisposition for being singletons or otherwise globally-available objects.
The way I see it, SingletonsAreEvil in the same manner as class methods that are independently aware of instances: static access to mutable state. They complicate test setup/teardown, make all kinds of race conditions possible, and leak causality which creates problems for techniques like ObjectCapabilityModel and PrevalenceLayer. This also seems to be like a purely ObjectOriented variation of the FirstGreatBlunder: treating the class as the collection of its instances. -- jh
Managers also seem to lead to the antipattern of, "C
reateObject() new's the object and then fills in all of its members." Again, if the object can properly construct itself (say, for example, you think that RAII brings any benefit whatsoever), then you don't need the manager to know how to construct the object. That's not to say that factories aren't useful, but still they've got to restrict themselves to creating the object and not get into initializing the object.
Eh? Where do you work? Here, the managers are definitely phony and purposeless. They don't even have a clue. --AnonymousDonor
I feel that management has a place. However, consider the difference between management that was internal to the team and management external to the team. In my experience, management that was internal to the team was much more effective. --TomPlunket
I don't think that SingletonsAreEvil
. But they may be overused. I'd recommend making a singleton that serves as some sort of factory or policy object a regular, many-instances-allowed class an instance of which gets passed to wherever it needs to do its stuff. Even at the expense of longer argument lists, in many cases. All of a framework's policy objects that are relevant to a common goal Foo can be gathered into a single FooPolicies?
object -- admittedly a curried pure-data object but it shortens the method name list and lets new policy arguments lots of methods would need just to pass to their own callees be instead a relatively painless field add that only forces changes to the client code that sets up the instance and the code that actually uses the new policy object. The policy object can also include standalone parameters like int fooTimeout, Bar defaultBar, etc. that might otherwise become global variables.
Single, site-wide singletons are still useful for two cases. One is a "special value" constant, such as a bignum NaN, with special behavior that's easily implemented polymorphically. This can be a singleton. The other is a factory for polymorphic objects that vary in implementation by host platform. On any given platform, the right subclass should be instantiated at startup and assigned to a global constant. Example (one of the few OO things AWT got right): java.awt.Toolkit and the singleton returned by the factory method getDefaultToolkit. All the platform-dependent code is localized in one place.
Any other use of singletons tends to be an attempt to sneak global variables in by the back door.
From above, "[e]ach HTTP request supported by the server has an associated handler "GetHandler?
Maybe this is begging for a
rhetorical bloody nose, but how about methods called
Why do these need to be separate classes at all? -- BillTrost
Actually, let me answer my own question.
I'm putting together a web server kit using
mixins (either via MultipleInheritance
templates). Web servers are created by
combining a class to handle connections, a
class to handle get requests, a class to handle
post requests, a class to handle invalid requests, and
maybe some other classes. A simple web server might be
composed of a
ileRequest server to deal with GETs,
ostRejecter to deal with POSTs. A wiki would be
based on classes
Anyhow, so, what classes are the abstract
ebServer class derived from? Why,
etHandler, for starters.
is a parent of
How about use of "Helper" in a class name? I hate that; there has got to be way of describing how
the class is helping. --KrisJohnson
If I see xxxHelper, then I assume it has static functions, usually something that would go in some standard library class were the language allow them to be added there.
What does xxxHandlerHelper do then?
What about classes with 'Controller' in the name. There are specific, good cases for this, but I've seen it just as abused as 'Manager' or 'Handler'. When I see 'Controller', I see procedural usually. -ChadMyers?
'Controller' makes me nuts. Are you trying to tell me your object controls some code, perhaps?! They all do. That's *all* they *ever* do.
I have to mention the sinking feeling I got at a new job when I first saw the "M
You people are clearly clueless about how to name classes, or even instances of various types. I recommend this instead:
(dead link replaced with an archive.org link 2009-07-14)
After adopting these conventions, I found my productivity quadrupled. Especially in Java!
Scary. Given that this is from 1984 and about AssemblyLanguage, I can't tell whether this is supposed to be parody or not. See also ThelopDictionary and the LOP pages it links to.
No; that document is serious.
And, in 1984, your assemblers only had 6 bytes of textual storage, because the other 2 bytes were used to set its value. See the pattern? Take your symbol, hash it, mask off the lower 3 bits (or shift if you require), and that's the address/offset of your symbol table entry. Ever wonder why most of the C library has functions which are 6 or fewer characters in length? That's why. Not only that, but storage media averaged 160KiB to 320KiB back then, maximum
. You often lacked subdirectories. And, CP/M and DOS imposed the venomous 8.3 filename limitations, due in large part for these reasons (although Commodore, Apple, and Atari all supported greater than this length; the minimum was 16 characters, via Commodore DOS). So, combined with source code size limitations (it must fit inside a 64K space, along with the compiler and symbol table), the symbol table size limitations, and the filenaming limitations, is it any wonder why entire articles are written dedicated to naming conventions?
Long symbol names are a recent
phenomena, made possible only with systems that granted greater than 64K to a process. I remember using my Amiga's C compiler (my first C compiler in fact), and 32 character symbols were considered god-sent. Today, you can't even code a trivial GTK application with that kind of limitation. --SamuelFalvo?
(and my own peeve: too many "Engine" classes.)
That document is atrocious man. I'm sure you're a very talented programmer, but requiring people to come up with mnemonics for things like "NAME" = prefixed with "NA" is not only ridiculous, but time consuming given that each new member of your team will have to learn your mnemonics! HOW could you possibly justify naming a variable NA, when you could type NAME? That's idiocy at worst and archaic at best.
I created a page for what I consider an even more prevalent antipattern - DontCreateVerbClasses
What about classes (with only static methods) with the name Something Utility. When I first got up to speed on writing code that interfaces with databases, I found a lot of duplicated code in my first attempt that I pulled away into DBUtility. Later I had ASPUtility for tricky problems that were ASP.NET relevant but not really part of the domain.
However, recently I've gone against this and started pulling things out of DBUtility. That class became a beast with 30+ methods. I've extended List<T> in the .NET API with my own list that handles a large chunk of List relevant code that was in DBUtility. I now have DBUtility for code specific to Jet Access Sql, StringUtility?
for stuff that I would make string extension methods once I get .NET 3.5 and CryptoUtility?
for special crypto and security related stuff. Of course Static Classes themselves are a smell to many people, but string is sealed so I can't do what I'd prefer.
What does adding "Utility" to those class names tell the next developer about the class? I don't have the full context, but from your description, I don't see what it adds to my understanding. The point on this page that I agree with is that names should be used to help the next developer understand what your code is doing. It is however better than a name which hurts understanding. For example, the WilliamFactory advocated above. A factory is for creating objects, not (ahem) managing the use and lifetime of objects. Finding code to do such in a factory would be quite surprising.
Well it turns out, at least some of that code now looks like it could go into a SQL related class high in my hierarchy. Inheritance has always been my weak point in OO programming, and I'm much more familiar with generics, delegates and things like that. But, for some of my SQL stuff, a hierarchy worked out well, and the DBUtility class had basic methods like putting quotes around a string value, and separating a list of values with a delimiter (kinda the opposite of tokenize.) For the delimiter methods, I extended List<T> and implemented them there, replacing all my lists that needed that functionality with the new class. And with the SQL stuff, I will be able to join several classes into one hierarchy that will allow them all to use the utility methods. So it turns out, Utility was really only a transitional name I used when I was first pulling out common functionality.
I have an Entity class in a simulation. It's an abstract base class that represents any simulated entity (something that has location, velocity, owner, etc.). All instantiable classes derived from it have meaningful names, but it's stuck with the generic. I suppose I could call it S
imulatedObjectThatHasLocationVelocityMassEtc, but that doesn't seem sensible. I could make a dozen interfaces that each have a get and set function for a single property, and make sure that all of the iterators and methods test to be sure that their parameters implement all relevant interfaces, but that seems much worse. The generic base class just seems natural, as does a generic name for it. I don't like it, but there it is, reflecting an abstract concept in reality with an abstract name. Maybe I should rename it Picasso.
To give an example of renaming a FileManager?
class to something more descriptive: The class in question open and saves xaml files to the OS file system. So in thinking about "what the class is supposed to do and name after that" it finally dawned on me that if it is 'managing' xaml files, call the class XamlFile?
and have Open and Close methods on it. XamlFile?
.Open(path) is certainly more semantic then FileManager?
.Open(path). The first tells you it is opening a xaml file (and that is the only type it handles) whereas FileManager?
.Open() looks like it would open any type of file.
Just for the record, your last argument seems invalid to me for we'd still know it's supposed to handle Xaml files, had it been called XamlFileManager?
. I think this is a great article though ; my only problem is the respect of the Single Responsability principle : an object representing data and an object handling it shouldn't been coupled. For instance, a File should represent a file object and its content, but it shouldn't write itself or read itself. There should be a reader or something more general that does this.
This is the same thing that has been said in the article about verb-classes. But I don't think it's a socket responsibility to send itself, nor is it a shape's to draw itself.
Now, that being considered, what would you call such a thing? What would you call something that allows file reading, writing, transforming? Perhaps a FileFilter?
? *Buzz* it's a verb and it doesn't bring anything.
In fact the role of a class like that is so generic (it does whatever it is you can do with files/shapes/sockets) — because this sounds more useful than having a class for each method, which would lead to having a FileReader?
etc. — that any name you'd come up with wouldn't be more clear than "Manager" or "Handler". Hence what is a lost cause imho. My 2 cents.
-- Pierre Arlaud