Using verbs in class names - language-agnostic

I'm reading Robert C. Martins book Clean Code. He writes about a convention not using verbs in class names.
The project I'm currently working on we need to validate and process some xml, so I created something like this
public class XmlProcesser
{
public XmlProcesser(string filePathAndName)
{
}
public bool Validate()
{
}
}
But Uncle Bobs recommendation is not to use "Processor" in the class name.
But what should I call it? Xml is no good, because I'm using the .net class xml a lot in the code. I thought about XmlHandler but I guess that is worse than Processor since "handler" is something else for a programmer.
How do you do? Do you use verbs in your class names?

Naming is important. Heck, T.S. Eliot and Andrew Lloyd Webber made fortunes from The Naming of Cats. But Martins' point isn't about not using verbs - it's about object-oriented thinking. Classes are patterns for instantiating objects. Objects are things. Are similar things better described by their behaviors or by their names?
Am I a carnivore? Yup. But I also write programs. Am I a programmer? Yup. But I also voted for Obama. Am I an Obama supporter? Yup. But ... In the end, I am a person. More correctly, I am an instance of the class[1] HomoSapiensSapiens. And HomoSapiensSapiens has many, many, MANY methods, all of which have verb-like names to them. Like HomoSapiensSapiens.EatBacon(). Like HomoSapiensSapiens.WriteGoodCode(). Like HomoSapiensSapiens.VoteDemocratic(). etc.
Martin's big point is that if your classes are best named like verbs, you're thinking about your classes all wrong.
[1] "class" in the OO meaning, not the Kingdom/Phylum/Class biological meaning.

As mentioned in the comments: Processor is derived from a verb, not a verb. Therefore Processor is an Ok name for class.
XmlProcessor doesn't really tell you much about the class. Ok, it is dealing with xml, but what does it do? Validate it? Forward it? Parse it? So it is very likely that there is a way better name around the corner
Taking the SOLID principles seriously you often end up with classes like
XmlProcessor{
public void process(){ ... }
}
or
CalvinTransmogrifier{
public Calvin transmogrify(Calvin c){ ...}
}
At that point you kind of reached the border between OOP and Functional Programming. And one can make an argument that
Transmogrify{
public Calvin do(Calvin c){ ... }
}
is an acceptable way to name things. If this is actually the case depends on your language of choice. E.g. in Scala if you can use 'apply' instead of 'do' and actually call the apply mothed like this
Transmogrify(new Calvin)
which at least I consider nicer then
Transmogrifier.do(new Calvin)

Yeah, it's a bad habit to name a class with verbish words like "Processor". What does the XMLProcessor you made actually process? Hold that thought. You said there's already a class named XML, otherwise you would use that. The problem is exactly that frustration you felt having to come up with a different name. The XML class is looking you right in the face, saying "I am XML, I am awesome, do not try to replace me, because I can process XML despite my short name. Don't think for a moment that I can't "process" something, bucko. " (if classes could talk and were annoying).
So, now, explain what your XMLProcessor class does that the standard XML class does not do. That's the crux of what you are missing. Perhaps you can extended the XML class to do whatever it is that the XMLProcessor does. Or perhaps you can create a new class that derives from the XML class, and name it based on what it processes that the base XML class cannot.
For those that "disagree with Uncle Bob", that just means you don't understand. It doesn't mean you are right.

Related

UML relationships - dashed line vs solid line

What is the difference between these 2 relationships?
Edit: Also if you could provide a simple code example illustrating the difference, that would be really helpful!
I'm trying to give simple examples of the two types of lines.
In the first diagram, the solid line shows an association:
If the classes were declared in Java, this would be like ClassA storing a reference to ClassB as an attribute (it could be passed in to the constructor, created, etc.). So, you might see something like:
public class ClassA {
ClassB theClassB = ...
...
}
In the second diagram, it shows a dependency:
A dependency is much weaker than an association. To quote from UML Distilled:
With classes, dependencies exist for various reasons: One class sends a message to another; one class has another as part of its data; one
class mentions another as a parameter to an operation. [...] You use dependencies
whenever you want to show how changes in one element might alter other elements.
Again, using Java, a couple of examples exist: an argument of type ClassB is passed to a method, or a method declares a local variable of type ClassB:
public class ClassA {
...
public void someMethod(ClassB arg1) {...}
...
public void someOtherMethod() {
ClassB localReferenceToClassB = ...
}
...
}
Other ways ClassA could depend on ClassB without having an association (not an exhaustive list):
ClassB has a static method that ClassA calls
ClassA catches exceptions of type ClassB
Whenever ClassB is modified, ClassA must also be modified (e.g., some logic is shared)
Your question gave me a good chance to learn myself, here is what I found -
Association: Ownership of another type (e.g. 'A' owns a 'B')
//#assoc The Player(A) has some Dice(B)
class Player {
Dice myDice;
}
Dependency: Use of another type (e.g. 'C' uses a 'D')
//#dep The Player(C) uses some Dice(D) when playing a game
class Player {
rollYahtzee(Dice someDice);
}
Here's a crisp ref I found - Association vs. Dependency
This webpage says enough I think
The following text comes from it, but should be enough to understand the difference.
So basically the solid line is an association and the dashed/dotted line is a dependency.
Associations can also be unidirectional, where one class knows about
the other class and the relationship but the other class does not.
Such associations require an open arrowhead to point to the class that
is known and only the known class can have a role name and
multiplicity. In the example, the Customer class knows about any
number of products purchased but the Product class knows nothing about
any customer. The multiplicity "0..*" means zero or more.
A dependency is a weak relationship between two classes and is
represented by a dotted line. In the example, there is a dependency
between Point and LineSegment, because LineSegment's draw() operation
uses the Point class. It indicates that LineSegment has to know about
Point, even if it has no attributes of that type. This example also
illustrates how class diagrams are used to focus in on what is
important in the context, as you wouldn't normally want to show such
detailed dependencies for all your class operations.
Since my reputation is only 8 I can't place the images itself, but they can still be found on the webpage I mentioned at the start.
[EDIT]
I don't have code examples right here, but how I personally would explain it is as simple as a car and a door.
When a car has a door (or more) it's just a car
Car --- has a --> Door
But when you have a door which can be opened the door class will have a function like
public void openDoor(){
this.open();
}
To use the function above the car will have to create an instance of the door
Class Car(){
Door door1 = new Door();
door1.open();
}
In this way you have created a dependency.
So the solid line is just pointing an object(1) to another object(2), but when you start using the object(1) it becomes a dependency.
Okay, since you didn't accept the first answer; let me try.
Arrow 1: A normal association
UML has different types of lines and arrows. Above is the simple association arrow, that means that one class can have a link to the other class. Below I will explain each type WITH code examples.
In the first example, you can see that there isn't really specified who knows who (who is the owner of the relationship). An animal can know the human and the human can know the animal. It's not specified and thus not really helpful for the programmer.
In the second example, the artist can have a guitar. Because there is an arrow and there isn't one on the other side, we know that the guitar doesn't know the artist. A guitar is an object that can totally exist on its own and doesn't need anybody.
In the third example, you see a marriage. Really simple; the husband knows the wife and the wife knows her husband. In our situation, the husband has only one wife and vice versa.
How do we accomplish this usually in code?
class Husband{
Wife bestWomanInTheWorld;
public Husband(Wife theWife){
this.bestWomanInTheWorld = theWife;
}
}
Because the husband always needs a wife, we put the required relationship in the constructor. Because an artist can have a guitar, we would leave the constructor empty like this:
class Artist{
List<Guitar> guitars;
public Artist(){
}
public AddGuitarToCollection(Guitar newGuitar){
Guitars.Add(newGuitar);
}
}
So, that's how we accomplish this in code (most of the time!). You won't usually need different types of lines and arrows if you are new to programming. Keep it simple.
Arrow 2: Dependency
Okay, so we know about normal associations which we will use most of the time. But when will we use the 'dependency' arrow? Well, lets define a dependency (wikipedia):
Dependency is a weaker form of bond which indicates that one class depends on
another because it uses it at some point in time. One class depends on
another if the independent class is a parameter variable or local variable of
a method of the dependent class. This is different from an association, where
an attribute of the dependent class is an instance of the independent class.
Sometimes the relationship between two classes is very weak. They are not
implemented with member variables at all. Rather they might be implemented as
member function arguments.
If there is a connection, relation, association etc. that requires to be present, to the classA to work; it's a dependency. Example: Husband needs the Wife to exist. A car needs a wheel to be a car (and drive). A car factory needs a car class to make an object from it. Your RSSNewsItem class needs an XMLReader class to do anything.
When to use which?
Well, this is the only valid question in my eyes; since google shows alot of valid answers to your question. Try to never use a dependency in a class diagram because it usually means that you aren't specific enough. Always aim for associations, realisations etc. Only use realisations (in my opinion) if there is a required need to use an other class without maintaining a relationship. Example; Utility classes (like the XMLReader).
If you have any questions after reading this full explanation, feel free to ask. :-)
Dotted line indicates dependency to (in the direction of the arrow). Assuming you have assembled your source code neatly into separate files and headers for each class
- the give away is simply that the code includes the line #include ClassB.h.
HOWEVER The fact of the matter is that all class relationships (generalisation, realisation, composition, aggregation, association etc) all inherit the dependency relationship. For this reason I never use dotted arrows when documenting code. Where possible I would aim to document the relationship in more specific terms eg. diamonds, triangles etc. If I don't know the exact relationship my starting point is a solid line with arrows (an association, with (implicit) dependence).
Notwithstanding this the dotted arrow notation can be useful in other aspects of UML modelling eg. showing dependencies to requirements in Use Case analysis for example.
NOTE The Thought Police would have us reduce coupling & dependencies between classes by using interfaces (pure virtual classes) as far as practical.
Whilst pure virtual classes offer the prospect of multiple inheritance and tightest coupling of all between classes as is possible. Interface classes have the advantage that they are made entirely out of dark matter and so totally invisible to the police. With this in mind it is possible to write c++ code with apparently zero coupling between classes -which they love because they never really did understand all those funny looking symbols anyway.
dotted mean implements (an interface)
solid means extends (a base class)

Abstract in programming

The word abstract is when we talk about a queue class or any class. A class is abstract right? How's the word abstract used in programming. Somehing that is abstract? What does that mean?
Abstract in OO is used to indicate that the class cannot be instantiated directly and must be inherited from before instantiation. Wiki explains this nicely.
Abstract means that you are discussing an idea one or more levels away from any specific example that you can actually point to or create.
As far as classes are concerned, an abstract class is abstract because it can't be instantiated. A specific class that can be instantiated is concrete, and it may be an example of a certain abstract class.
Similarly, if your data structures class discusses an 'abstract' data type such as a Queue, the teacher means Queue as 'a FIFO data structure'. Slightly less absract is Java's AbstractQueue. A concrete queue that you can "point to" (not in the sense of pointers and memory, but in the sense "THERE is a queue!") could be Java's LinkedBlockingQueue
`Abstract` ... ... ... ... ... ... ... ... ... `Concrete`
a queue AbstractQueue LinkedBlockingQueue
a group an infinite group positive integers
a car a Ford 1995 Ford Taurus My 1995 Ford Taurus VIN# 3489230148230
The term "abstract" can mean a whole bunch of different things, depending on the context.
The two most common uses of "abstract" pertain to object-oriented programming. A method is called "abstract" (or, in C++-speak, "pure virtual") if the method does not have an implementation. The purpose of an abstract method is to indicate that classes that inherit from the given class will all have a method with the given signature, but there is no reasonable default behavior for that method. A common example is, in a class hierarchy of shapes, that the base class for shapes might have an abstract method that draws the shape on the screen. There is no good default behavior for drawing "a shape" - what shape it it? - but any individual shape will have a concrete implementation of this function.
A related term is an "abstract class," which is a class that contains an abstract method. Because the class contains this abstract method, you can't have a concrete object of that class type. Otherwise, if you tried calling the abstract method, you'd find out that there was no implementation associated with it.
In an entire different context, the word "abstract" sometimes shows up in the term "abstract data type," which is a term used to describe an object supporting some set of mathematical operations without necessarily explaining how those operations are implemented. For example, "stack," "queue," and "list" are all abstract data types, since they describe what behaviors are expected of a given type of object without giving implementation (e.g. dynamic array? linked list? hash table?)
The term "abstract" also comes up in "abstraction," which is some simplification of a complex system into something more managable. For example, network routing is usually broken down into a different number of "layers," each of which are responsible for handling some part of the end-to-end communication. Each layer is tasked with a specific job, and must take in input and produce output in a predetermined fashion. This lets programmers work on one layer treat all the other layers as "black boxes" that magically get the job done, since provided that you give input to the layer in the right form or read the output of some layer in a specific manner, you don't need to worry about the details of how that layer works.
Hope this helps!
Well a good example in OO is an Animal, you'd have an abstract class like so:
abstract class Animal
{
public AnimalType Type { get; set; }
}
Now you can't declare an animal outright, you must have a class that inherits from an animal, like a cat:
class Cat : Animal
{
public Cat()
{
Type = AnimalType.Feline;
}
}
So this wouldn't work:
Animal a = new Animal();
But this would:
Animal a = new Cat();
So in essence, what you're saying, is this is a base class, you can't make one on it's own, you need more information, say a class that inherits from it. Kind of hard to explain, so hope the example helps!
Abstract classes cannot be instantiated and instead are inherited from by other classes, generally concrete ones. They usually contain code that is common to inheriting classes to minimize code duplication.
I think it can mean a couple of things related to programming. But, for me, I think of it related to virtual methods, which may perform different tasks depending on the underlying object type. That would be in contrast to a method that always does the same, fixed set of operations.
In fact there are "abstract classes", where one or more methods are pure virtual, which means they are not implemented by that class. Such a class cannot be instantiated. Instead, you must derive a new class from it that implements the pure virtual methods, and then you can instantiate the second class.
Abstraction is a way of building compound objects from simpler ones. A function for example can be seen a form of black box abstraction ..where the inner workings of the function are hidden from the user.
Data abstraction in general is a methodology that enables programmers to isolate how a compound data object is used from the details of how it is constructed from more primitive data objects.

Is-a, extends, 'inherits': What is your preferred term for "inheritance" and why?

A subjective question, hence if there are complaints I'll wiki, but I'd like to know what people's takes are on the different terms that are used for inheritance almost interchangeably.
We have "is-a", "extends", "derives", "subclasses" and simply "inherits"
The words we choose have a lot of meaning packed into them. What is your preferred term for "inheritance" and why?
Be compelling!
I most often uses "A subclasses B" (very direct) or "A inherits from B" (modestly more circumlocutory). "extends" is fine in languages where it's a keyword such as Java, but using it for (say) C++ or Python seems to be a bit of a stretch, for some reason. "IS-A" is a relationship constraint that inheritance must respect (Liskov's principle) and holds between instances (left side) and classes (right side) -- so you can say "x IS-A Foo" (when x is an instance of Foo or any subclass of Foo), but "Bar IS-A Foo" (where they're both classes) seems wrong, it would cause confusion in languages where classes are also instances of (meta)classes such as Python.
I like to say derived because it strongly implies the class / subclass relationship, but would be reasonably accurate in the more exotic cases, like multiple inheritance, interface implementation, and mixins.
I have various secondary arguments. For one thing, "parent" and "child" strongly imply a specific structural analogy that may clash with the actual relationship. For another, the entire point is the reuse of both code and also the abstraction itself. If memory was free and we all typed one million words per minute, it still would not be a good idea to copy and paste code, because that would hide the relationship between the various abstractions. Derived makes it clear that what you are doing is sharing at least a part of the abstraction you started with.
I was tought to consider that if you can connect to classes A and B between an "A is a B" (whale is a mammal) relationship, then they are bound by inheritance.
So i prefer IS A
There are differnet terminoligies in different languages.
"is a" suits dynamic languages and relects the chimeric qualities of perl/php/python and javascript objects. Lassie is a Dog, is a Mammal, is a Pet, is a Movie Star is also an asset of MGM.
"extends" suits the declarative, strict typing of nature of Java (and its lack of multiple inheritance!). "Lassie extends Dog", Lassie can walk and bark but cannot star or perform when she is implemneted in Java!
There are two ways to think about inheritance:
is-a : Polymorphism is when an interface is defined by a base class, but the implementation can be provided by an inherited class.
public class Polygon
{
public abstract int Points();
};
public class Triangle : Polygon
{
public override int Points() { return 3; }
}
void Foo( Polygon p )
{
int points = p.Points();
}
main()
{
Foo( new Triangle() );
}
extends - a way of capturing shared implementation.
public class iTouch
{
// cool pda features
}
public class iPhone : private iTouch
{
// phone features
// cool pda features comes from the base class
}
The preferred terminology usually depends greatly on the language, but I find that most OO developers understand each other regardless of the terms. (That being said, I definitely agree that word choice is important for maximizing effectiveness of communication.)
My preferred terminology is "subclasses" or "extends" for classes, and "implements" for interfaces. (In Objective-C, one "adopts" or "conforms to" a protocol, the inspiration for Java's interfaces.) Often, I use "parent" and "child" to describe the relationship itself.
I find that "is a" works best when contrasting with "has a" (composition), but it doesn't make sense for all forms of inheritance — sometimes, narrowing specificity makes sense, but not always. Similarly, there are times that "derives" just doesn't seem right — many people will understand it as specialization, but not everyone will. (For example, one can derive a proof, derive chemicals via a reaction, etc. Check out a dictionary entry on the word to see the variety of possible meanings, many of which have to do with a set of steps, which sounds more like an algorithm than inheritance.) On a side note, I've found that "base class" and "derived class" are preferred by many academics, but perhaps not as often in industry.
I'll say here that simplicity is a good thing. I'm all for "A Is a B" when referring to a subclass (A) that is obviously an instance of the parent class (B) (A Dog is a Mammal etc). If the relationship isn't that simple, I prefer to simply say "A is a subclass of B".
Class composition clearly makes the idea of "A Is a B" difficult, so there's obviously a time when "A Has a B" or "A Owns a B" is easier to understand.
For the continued sake of simplicity, I prefer to say a class conforms to a protocol, or implements an interface (although I don't program in java much).
The key as far as I'm concerned, is simplicity and ease of communication. If you're working on a project yourself, and will never have to discuss your design or code to anyone else, call it whatever you want. If you're working on a team, establishing the simplest possible standard of communication saves a lot of headache trying to decipher everyone's different slang for OOP patterns.
Here is the terminology that I prefer:
A inherits from B - This is the simples most precise method.
A derives from B - This is useful to generally describe cases where A inherits B or from some other class which derives from B.
Here is the terminology that I dislike:
A extends B - This is not quite accurate because a class can derive from another class, and just do things differently without literally extending it. It is also often used to describe the relationship between interfaces.
A subclasses B - Inheritance isn't restricted to just classes.
A is a B - If A inherits from B, it isn't necessarily the same things as a B, unless it can be used legally wherever a B can be used. If the design contract preconditions and postconditions of virtual function aren't properly weakened and strengthened in the new class, the A is not technically a B because it violates the Liskov substitution principle.
I like to kick it old-school and say "A implies B" or "A is less than B". These are not ambiguous like the other terms, i.e. they have precise meanings.
Footnote: I sometimes say "better than" and "worse than" to mean supertype and subtype relations, respectively. I do this to disambiguate this relation when it's not clear that the objects in question are types. I inherited this habit from Edward Kmett.
See here.

What is the best practice/coding standard with regard to the "this" scope is AS3?

What is the best practice/coding standard with regard to the "this" scope is AS3? Is there one? I feel it really helps with standardization and my readability, but sometimes it seems like "too much".
For instance, is the use of "this" in the following really necessary (I know it works without "this")?:
private var _item:Object;
private var selectedItem:Object;
public function set item(value:Object):void
{
this._item = value;
if (this._item["label"] == "doodad")
this.selectedItem = value;
}
public function set item(value:Object):void
{
return this._item;
}
"this" is not required unless you want to prevent naming conflicts between locally scoped variables (method params for instance) and instance variables.
In your example you are already using an underscore to mark a private variable, so it's an extra reason not to use "this" since you are really saying twice the same thing.
It certainly isn't necessary, but I agree that it can help with readability. Since I work more in more dynamic languages (e.g. Perl and Python), such conventions can be vital for quickly determining where variables and functions are scoped/located. If this convention works for you, I don't think it's a bad thing, per se.
Thus said, I've spent hours reformatting code which contained awkward conventions which impeded readability.
For example: one person I worked with wrote all assignments like this:
var foo:String= "bar";
This was irritating (I prefer " = " so I can clearly see the operator), and I spent a lot of time cleaning up thousands of lines of code I had to maintain. His convention (which, though we argued about several times, he refused to compromise on) tended to impede my work.
Strive for unity w/others working with you. If they need to support your code and find this aggravating, it's likely not worth it to leave it in. If you don't expect anyone to work directly with the source, use conventions which help you understand your code and document (somewhere) what they mean.
If you're working in a team, stick with the coding conventions of the team.
But personally, I find explicit use of "this", when not required for disambiguation, overkill that negatively affects readability in a statically typed language like AS3 (dynamic languages are another story!).
A class should only really have one responsibility so generally there shouldn't be too many properties on it. Inside a method you generally deal with three types of variables: temporary local variables, method parameters, and properties. Methods shouldn't be too long, so it should be easy to spot the difference between the three types - if it's not defined locally and hasn't been passed as a parameter, then it's a property. If the whole method doesn't fit on your screen then it's probably too long!
I only use "this" when needed to disambiguate between a property and a parameter with the same name.
I prefer not to use "this" too much, but sometimes do in Eclipse, just to get autocompletion (probably the worst reason to do it!)
Would make more sense if your example was:
public function set item(_item:Object):void
{
this._item = _item;
if (this._item["label"] == "doodad")
this.selectedItem = this._item;
}

What is your system for avoiding keyword naming clashes?

Typically languages have keywords that you are unable to use directly with the exact same spelling and case for naming things (variables,functions,classes ...) in your program. Yet sometimes a keyword is the only natural choice for naming something. What is your system for avoiding/getting around this clash in your chosen technology?
I just avoid the name, usually. Either find a different name or change it slightly - e.g. clazz instead of class in C# or Java. In C# you can use the # prefix, but it's horrible:
int #int = 5; // Ick!
There is nothing intrinsically all-encompassing about a keyword, in that it should stop you from being able to name your variables. Since all names are just generalized instances of some type to one degree or another, you can always go up or down in the abstraction to find another useful name.
For example, if your writing a system that tracks students and you want an object to represent their study in a specific field, i.e. they've taken a "class" in something, if you can't use the term directly, or the plural "classes", or an alternative like "studies", you might find a more "instanced" variation: studentClass, currentClass, etc. or a higher perspective: "courses", "courseClass" or a specfic type attribute: dailyClass, nightClass, etc.
Lots of options, you should just prefer the simplest and most obvious one, that's all.
I always like to listen to the users talk, because the scope of their language helps define the scope of the problem, often if you listen long enough you'll find they have many multiple terms for the same underlying things (with only subtle differences). They usually have the answer ...
Paul.
My system is don't use keywords period!
If I have a function/variable/class and it only seems logical to name it with a keyword, I'll use a descriptive word in front of the keyword.
(adjectiveNoun) format. ie: personName instead of Name where "Name" is a keyword.
I just use a more descriptive name. For instance, 'id' becomes identifier, 'string' becomes 'descriptionString,' and so on.
In Python I usually use proper namespacing on my modules to avoid name clashes.
import re
re.compile()
instead of:
from re import *
compile()
Sometimes, when I can't avoid keyword name clashes I simply drop the last letter off the name of my variable.
for fil in files:
pass
As stated before either change class to clazz in Java/C#, or use some underscore as a prefix, for example
int _int = 0;
There should be no reason to use keywords as variable names. Either use a more detailed word or use a thesaraus. Capitalizing certain letters of the word to make it not exactly like the keyword is not going to help much to someone inheriting your code later.
Happy those with a language without ANY keywords...
But joke apart, I think in the seldom situations where "Yet sometimes a keyword is the only natural choice for naming something." you can get along by prefixing it with "my", "do", "_" or similar.
I honestly can't really think of many such instances where the keyword alone makes a good name ("int", "for" and "if" are definitely bad anyway). The only few in the C-language family which might make sense are "continue" (make it "doContinue"), "break" (how about "breakWhenEOFIsreached" or similar ?) and the already mentioned "class" (how about "classOfThingy" ?).
In other words: make the names more reasonable.
And always remember: code is WRITTEN only once, but usualy READ very often.
Typically I follow Hungarian Notation. So if, for whatever reason, I wanted to use 'End' as a variable of type integer I would declare it as 'iEnd'. A string would be 'strEnd', etc. This usually gives me some room as far as variables go.
If I'm working on a particular personal project that other people will only ever look at to see what I did, for example, when making an add-on to a game using the UnrealEngine, I might use my initials somewhere in the name. 'DS_iEnd' perhaps.
I write my own [vim] syntax highlighters for each language, and I give all keywords an obvious colour so that I notice them when I'm coding. Languages like PHP and Perl use $ for variables, making it a non-issue.
Developing in Ruby on Rails I sometime look up this list of reserved words.
In 15 years of programming, I've rarely had this problem.
One place I can immediately think of, is perhaps a css class, and in that case, I'd use a more descriptive name. So instead of 'class', I might use 'targetClass' or something similar.
In python the generally accepted method is to append an '_'
class -> class_
or -> or_
and -> and_
you can see this exemplified in the operator module.
I switched to a language which doesn't restrict identifier names at all.
First of all, most code conventions prevent such a thing from happening.
If not, I usually add a descriptive prose prefix or suffix:
the_class or theClass infix_or (prefix_or(class_param, in_class) , a_class) or_postfix
A practice, that is usually in keeping with every code style advice you can find ("long names don't kill", "Longer variable names don't take up more space in memory, I promise.")
Generally, if you think the keyword is the best description, a slightly worse one would be better.
Note that, by the very premise of your question you introduce ambiguity, which is bad for the reader, be it a compiler or human. Even if it is a custom to use class, clazz or klass and even if that custom is not so custom that it is a custom: it takes a word word, precisely descriptive as word may be, and distorts it, effectively shooting w0rd's precision in the "wrd". Somebody used to another w_Rd convention or language might have a few harsh wordz for your wolds.
Most of us have more to say about things than "Flower", "House" or "Car", so there's usually more to say about typeNames, decoratees, class_params, BaseClasses and typeReferences.
This is where my personal code obfuscation tolerance ends:
Never(!!!) rely on scoping or arcane syntax rules to prevent name clashes with "key words". (Don't know any compiler that would allow that, but, these days, you never know...).
Try that and someone will w**d you in the wörd so __rd, Word will look like TeX to you!
My system in Java is to capitalize the second letter of the word, so for example:
int dEfault;
boolean tRansient;
Class cLass;