Variable/function naming for 2-D and 3-D grouped objects - naming-conventions

I am working on a UI where the top level, logical grouping of display objects is 2-D or 3-D (variety of objects can be displayed either two dimensionally or three dimensionally.)
My language of choice does not allow for numeric characters to be the first character of an identifier (not actually aware of any that do) so I'm looking for a sane and legible prefix to use. I have thought of:
Ddd (e.g. DddObject or DdObject)
ThreeD (e.g. ThreeDObject or TwoDObject)
But both options look ugly and weird to me. Has anyone come up with a cleverer replacement to 2-D and 3-D object naming?

I have used 'TD' once (for 3D), but that's not very intuitive. I think you should use a 3D or 2D suffix where required, as suggested by SigTerm above, for example Point2D and Point3D. In other cases, like TriMesh, where it is obvious that the object is 3D, there is no need for either a prefix or a suffix.
I have personally found it best to avoid prefixes and suffixes as far as possible. Not only does this save you some typing effort, but the code also becomes more readable. Of course, the convention will also depend on the context. For example, if you have a scene object that can hold both 2D and 3D object, you would like to name it just 'Scene'. However, your problem might dictate having two separate structures for the 2D and 3D scenes, in which case you might want to name them 'Scene2D' and 'Scene3D'.
Using something more abstract is not good in the long term, because there is just no way that you can fully convey the logic behind the choice to others, and over time it will become more and more open to misinterpretation. For example, someone, someday might end up adding a class called Loggin3D, for log errors :)

Related

Should I use OOP when encapsulation is essentially ignored?

I am making a Mathematics web program which allows the user to compute and prove various quantities or statements, e.g. determinant of a matrix, intersection of sets, determine whether a given map is a homomorphism. I decided to write the code using the OOP paradigm (in PHP, to handle some of the super heavy computations that a user's browser might not appreciate), since I could easily declare sets as Set objects, matrices as Matrix objects, etc. and keep some of the messy details of determining things such as cardinality, determinants, etc. in the background. However, after getting knee-deep in code, I'm wondering if deciding on OOP was a mistake. Here's why.
I'll use my Matrix class as a simple example. Matrix has the following attributes:
name (type String) (stores name of this matrix)
size (type array) (stores # rows and # columns of this matrix)
entries (type array) (stores this matrix's entries)
is_invertible (type Boolean) (stores whether this matrix can be inverted)
determinant (type Int) (stores the determinant of this matrix)
transpose (type array) (stores the transpose of this matrix)
Creating a new matrix called A would be done like so:
$A = new Matrix("A");
Now, in a general math problem concerning matrices, it could be that we know the matrix's name, size, entries, whether it's invertible, its determinant, or its transpose, or any combination of the above. This means that all of these properties need to be accessible, and certainly any of these properties can be changed by the user, depending on what's given in the problem. (I can give examples of problems for any of these cases, if needed.)
The issue I'm having, then, is that this would break the encapsulation "rule" of OOP ("rule" in quotes since, from what I understand, it's not a hard-and-fast rule, just one that should be upheld to the greatest extent possible). I did some searching on when getters and setters should be used, or even IF they should be used (seems odd to me that they wouldn't, in an OOP setting...), but this did not seem to help me much, as I found many contradictory answers and case-specific opinions.
So, my overall questions are: when the user needs access to modify many (if not all) of an object's attributes, but a class-oriented design seems to be ideal for addressing the programming problem,
Is OOP the best way to structure the code, despite essentially ignoring encapsulation altogether?
Is there an alternative to OOP which allows high user access while maintaining the OO "flavor" (i.e. keeping sets, matrices, etc. as objects)
Is it ok to break the encapsulation rule altogether once in a while, if the problem calls for it? Or is that not in the spirit of OOP?
What you are trying to do is not necessarily outside the scope of OOP. The thing is that you have a different model than what would usually be described in programming textbooks (where, for example, the values of the matrix would be always present and all of the functions could be simple methods). (Perhaps this is why the question was unfairly downvoted.) Nothing prevents you from storing values like "is_invertible" internally and implementing setter and getter methods. Doing this might make sense if you are trying to learn OOP. But I think other problems (see coding textbooks) might be easier for learning purposes. I see that a remote goal would be to capture some of mathematics as an OOP framework. But the whole mathematical universe is immensely richer than any fixed architecture (results like Gödel's theorem put a theoretical limit). You can only succeed in developing a framework for a very narrow application, for example solving certain equations. That's what symbolic algebra programs do: you can look at how, for example, SymPy or perhaps parts of Maple and Mathematica are implemented. In my view, the OOP paradigm can be both very useful and too restrictive / unnecessary depending on the task (you can certainly find more about shorcomings of OOP in Wikipedia or elsewhere). Also, your problem can be seen as writing a small programming language - in many of them you have sets, numbers, etc as objects.
You can use only rudimentary OOP or no OOP at all. You can use functional programming.
You should Google/read more about this on this or other sites. Is it OK to sometimes walk across the road when the red traffic light is on?

How should I model pathfinding in the object oriented paradigm

My goal is to implement a (very simple) strategy game.
For the moment, I'll start with the map and two characters (I want the terrain to affect them differently) to experiment with pathfinding
The problem is that I have very little or no experience in object oriented design. I've used C++ classes before, but it was pretty straightforward: for instance, a class Graph implemented using an array of sets, with a method AStar. I didn't have in mind the concept of "several players".
I've thought of the following elements/classes: Game, Map and Character. Eventually a Pathfinder class.
First question: the position of a character is something the game should know? The map? or each character?
( I think the game should )
Second question: where would it be a good choice for a "findPath" method?
The Game?
Should a pathfinding algorithm be a method of Map? Something like map.findPath(character, srcpos, dstpos)
In the Character class? It makes more sense to do character1.findPath(map, srcpos, dstpos)
If I added a Pathfinder class, it would have to build its own representation of the map in order to determine the shortest path. And before doing that, it would have "to ask" the map how the terrain affects each player.
( I prefer the latter )
It seems the construction of an auxiliary structure (and asking the map) to apply, let's say, A* is something that I can't avoid.
Making things object-oriented is not a goal, it's a tool to be used when it makes sense. C++ is a language with lots of functionality that you can easily drown yourself with, so my advice is to keep things simple and easy.
This can mean keeping data and logic tightly together sometimes, or separating it completely other times.
First question: My initial reaction is that the character should know its position. But how you represent it with data depends on how you intend to use it, so both the game, the character and potentially also the map needs to know where the character is.
Second question: It depends on what the Map class is. Is it an object representing the map itself with necessary functionality exposed to the rest of your program, or is it a toolbox of functions that works on a simple data representation of the map?
If the Map class represents the map, it should have the necessary functionality exposed for a Pathfinder class to work on it (the pathfinding algorithm will need to have some additional data derived from the map, maybe temporary, maybe persistent).
If the Map class does not represent the map, you can put the pathfinding functionality in it. I think it would belong there in that case. If the pathfinding code causes the Map class to get too big, you should separate it into its own class anyway.
First Question: The position of the character should be a part of character itself (makes sense this way) for me.
Second Question: Finding a path logically cannot be a part of Map. Then you would be violating one of OOP principles i.e. Single Responsibility.
According to me you should create the PathFinder class. You can design it in this way
class PathFinder{
PathFinderAlgorithm algorithm;
//other required values according to your design
Path findPath(){
algorithm.apply();
}
//other required methods according to your design
}
PathFinderAlgorithm is an interface.
Using this you can also change the algorithm that you are using to find the path. Like if you in future need to find the longest path, all you have to do is create another class which will find the longest path and replace it in the PathFinder class.

Non-object-oriented game tutorials

I've been tasked with writing an essay extolling the virtues of object oriented programming and creating an accompanying game to demonstrate them.
My initial idea is to find a tutorial for a simple game written in a programming language which does not follow the OOP paradigm (or written in an OOP language but not in an OOP way) and recreate it in an OOP way using either C# or Java (haven't yet decided). This would then allow me to make concrete comparisons between the two.
The game doesn't have to be anything complex; Tetris, Pong, etc. that sort of thing. The problem I've had so far is finding a suitable tutorial, any suggestions?
Let's say that you found source code for a game not in OOP. There are some OOP virtues that you can point out in your essay:
Organization.
Since a game has many tasks, it is a good idea to assign a responsibility to one class. This means write one class that keeps score, one class that does file access (reading and writing game state, for example), classes to represent your characters, etc. Otherwise, you will have one huge text file with thousands of lines of code. It would be a nightmare to even look at it, let alone find what you need and fix it.
Encapsulation.
This is grouping together properties and functions for better organization. We used to have a different array to store each property - (example) one array for aircraft names, one array for firepower, another array for top speed, etc. That sucks because you need to make sure that the same index across all those arrays actually describes the correct aircraft. It's better to create an Aircraft object and give it those property names. You'll then have one array that holds aircraft - no need to keep track of too many arrays.
Reusability.
As you write more games (and even other apps), you will come across the need to reuse classes. For example, you would use the same Card class in your Solitaire game as any card game you'll write in the future.
Polymorphism/Inheritance.
Say that you want to display each character - both heroes and villains in some sort of a grid. You will want both Hero and Villain to inherit Character. Character will have common properties and even a[n abstract] Display() function. You would then write the custom Display() function for Character and Villain (that access class-specific data for drawing). You then create an array of Character objects, and you may store either a Villain or Hero in each slot. When the game goes through that list to display, each item.Display() call will automatically pick the correct Display() function based on the Character's actual type. Try to do this without OOP and you'll end up with a long if-else (and probably even nested) statement and all drawing routines in one place.
That's just from the type of my head from experience in general programming that you can definitely apply in game programming. There are probably more OOP aspects than mentioned, so you may want to research. Best of everything for your essay!
You can try grabbing a (simple) TI-Basic game from TICalc, Omnimaga, or most other calculator programming websites and try to understand its code.
Try a BASIC game from this site:
http://www.atariarchives.org/basicgames/

Naming a dictionary structure that stores keys in a predictable order?

Note: Although my particular context is Objective-C, my question actually transcends programming language choice. Also, I tagged it as "subjective" since someone is bound to complain otherwise, but I personally think it's almost entirely objective. Also, I'm aware of this related SO question, but since this was a bigger issue, I thought it better to make this a separate question. Please don't criticize the question without reading and understanding it fully. Thanks!
Most of us are familiar with the dictionary abstract data type that stores key-value associations, whether we call it a map, dictionary, associative array, hash, etc. depending on our language of choice. A simple definition of a dictionary can be summarized by three properties:
Values are accessed by key (as opposed to by index, like an array).
Each key is associated with a value.
Each key must be unique.
Any other properties are arguably conveniences or specializations for a particular purpose. For example, some languages (especially scripting languages such as PHP and Python) blur the line between dictionaries and arrays and do provide ordering for dictionaries. As useful as this can be, such additions are not a fundamental characteristics of a dictionary. In a pure sense, the actual implementation details of a dictionary are irrelevant.
For my question, the most important observation is that the order in which keys are enumerated is not defined — a dictionary may provide keys in whatever order it finds most convenient, and it is up to the client to organize them as desired.
I've created custom dictionaries that impose specific key orderings, including natural sorted order (based on object comparisons) and insertion order. It's obvious to name the former some variant on SortedDictionary (which I've actually already implemented), but the latter is more problematic. I've seen LinkedHashMap and LinkedMap (Java), OrderedDictionary (.NET), OrderedDictionary (Flash), OrderedDict (Python), and OrderedDictionary (Objective-C). Some of these are more mature, some are more proof-of-concept.
LinkedHashMap is named according to implementation in the tradition of Java collections — "linked" because it uses a doubly-linked list to track insertion order, and "hash" because it subclasses HashMap. Besides the fact that user shouldn't need to worry about that, the class name doesn't really even indicate what it does. Using ordered seems like the consensus among existing code, but web searches on this topic also revealed understandable confusion between "ordered" and "sorted", and I feel the same. The .NET implementation even has a comment about the apparent misnomer, and suggests that it should be "IndexedDictionary" instead, owing to the fact that you can retrieve and insert objects at a specific point in the ordering.
I'm designing a framework and APIs and I want to name the class as intelligently as possible. From my standpoint, indexed would probably work (depending on how people interpret it, and based on the advertised functionality of the dictionary), ordered is imprecise and has too much potential for confusion, and linked "is right out" (apologies to Monty Python). ;-)
As a user, what name would make the most sense to you? Is there a particular name that says exactly what the class does? (I'm not averse to using slightly longer names like InsertionOrderDictionary if appropriate.)
Edit: Another strong possibility (discussed in my answer below) is IndexedDictionary. I don't really like "insertion order" because it doesn't make sense if you allow the user to insert keys at a specific index, reorder the keys, etc.
I vote OrderedDictionary, for the following reasons:
"Indexed" is never used in Cocoa classes, except in one instance. It always appears as a noun (NSIndexSet, NSIndexPath, objectAtIndex:, etc). There is only one instance when "Index" appears as a verb, which is on NSPropertyDescription's "indexed" property: isIndexed and setIndexed. NSPropertyDescription is roughly analogous to a table column in a database, where "indexing" refers to optimizing to speed up search times. It would therefore make sense that with NSPropertyDescription being part of the Core Data framework, that "isIndexed" and "setIndexed" would be equivalent to an index in a SQL database. Therefore, to call it "IndexedDictionary" would seem redundant, since indices in databases are created to speed up lookup time, but a dictionary already has O(1) lookup time. However, to call it "IndexDictionary" would also be a misnomer, since an "index" in Cocoa refers to position, not order. The two are semantically different.
I understand your concern over "OrderedDictionary", but the precedent has already been set in Cocoa. When users want to maintain a specific sequence, they use "ordered": -[NSApplication orderedDocuments], -[NSWindow orderedIndex], -[NSApplication orderedWindows], etc. So, John Pirie has mostly the right idea.
However, you don't want to make insertion into the dictionary a burden on your users. They'll want to create a dictionary once and then have it maintain an appropriate order. They won't even want to request objects in a specific order. Order specification should be done during initialization.
Therefore, I recommend making OrderedDictonary a class cluster, with private subclasses of InsertionOrderDictionary and NaturalOrderDictionary and CustomOrderDictionary. Then, the user simply creates an OrderedDictionary like so:
OrderedDictionary * dict = [[OrderedDictionary alloc] initWithOrder:kInsertionOrder];
//or kNaturalOrder, etc
For a CustomOrderDictionary, you could have them give you a comparison selector, or even (if they're running 10.6) a block. I think this would provide the most flexibility for future expansion while still maintain an appropriate name.
I vote for InsertionOrderDictionary. You nailed it.
Strong vote for OrderedDictionary.
The word "ordered" means exactly what you are advertising: that in iterating through a list of items, there is a defined order to selection of those items. "Indexed" is an implementation word -- it talks more to how the ordering is achieved. Index, linked list, tree... the user doesn't care; that aspect of the data structure should be hidden. "Ordered" is the exact word for the additional feature you are offering, regardless of how you get it done.
Further, it seems like the choice of ordering could be at the user's option. Any reason why you couldn't create methods on your datatype that allow the user to switch from, say, alphabetical ordering to insertion-time ordering? In the default case, a user would choose a particular ordering and stick with it, in which case implementation would be no less efficient than if you created specialized subclasses for each ordering method. And in some less-used cases, the developer might actually wish to use any of a number of different orderings for the same data, depending on app context. (I can think of specific projects I've worked on where I would have loved to have such a data structure available.)
Call it OrderedDictionary, because that's precisely what it is. (Frankly, I have more of a problem with the use of the word "Dictionary", because that word heavily implies ordering, where popular implementations of such don't provide it, but that's my pet peeve. You really should just be able to say "Dictionary" and know that the ordering is alphabetical -- because that's what a dictionary IS -- but that argument is too late for existing implementations in the popular languages.) And allow the user to access in what order he chooses.
Since posting this question, I'm starting to lean towards something like IndexedDictionary or IndexableDictionary. While it is useful to be able to maintain arbitrary key ordering, limiting that to insertion ordering only seems like a needless restriction. Plus, my class already supports indexOfKey: and keyAtIndex:, which are (purposefully) analagous to NSArray's indexOfObject: and objectAtIndex:. I'm strongly considering adding insertObject:forKey:atIndex: which matches up with NSMutableArray's insertObject:atIndex:.
Everyone knows that inserting in the middle of an array is inefficient, but that doesn't mean we shouldn't be allowed to on the rare occasions that it's truly useful. (Besides, the implementation could secretly use a doubly-linked list or any other suitable structure for tracking the ordering if needed...)
The big question: is "indexed" or "indexable" as vague or potentially confusing as "ordered"? Would people think of database indexes, or book indexes, etc.? Would it be detrimental if they assumed it was implemented with an array, or might that simplify user understanding of the functionality?
Edit: This name makes even more sense given the fact that I'm considering adding methods that work with an NSIndexSet in the future. (NSArray has -objectsAtIndexes: as well as methods for adding/removing observers for objects at given indexes.)
What about KeyedArray?
As you said in your last paragraph, I think that InsertionOrder(ed)Dict(ionary) is pretty unambiguous; I don't see how it could be interpreted in any way other than that the keys would be returned in the order they were inserted.
By decoupling the indexed order from the insertion order, doesn't this simply boil down to keeping an array and Dictionary in a single object? I guess my vote for this type of object is IndexedKeyDictionary
In C#:
public class IndexedKeyDictionary<TKey, TValue> {
List<TKey> _keys;
Dictionary<TKey, TValue> _dictionary;
...
public GetValueAtIndex(int index) {
return _dictionary[_keys[index]];
}
public Insert(TKey key, TValue val, int index) {
_dictionary.Add(key, val);
// do some array massaging (splice, etc.) to fit the new key
_keys[index] = key;
}
public SwapKeyIndexes(TKey k1, TKey k2) {
// swap the indexes of k1 and k2, assuming they exist in _keys
}
}
What would be really cool is indexed values...so we have a way to sort the values and get the new key order. Like if the values were graph coordinates, and we could read the keys (bin names) as we move up/down along the coordinate plane. What would you call that data structure? An IndexedValueDictionary?
At first glance I'm with the first reply -- InsertionOrderDictionary, though it's a bit ambiguous as to what "InsertionOrder" means at first glance.
What you're describing sounds to me almost exactly like a C++ STL map. From what I understand, a map is a dictionary that has additional rules, including ordering. The STL simply calls it "map", which I think is fairly apt. The trick with map is you can't really give the inheritance a nod without making it redundant -- i.e. "MapDictionary". That's just too redundant. "Map" is a bit too basic and leaves a lot of room for misinterpretation.
Though "CHMap" might not be a bad choice after looking at your documentation link.
Maybe "CHMappedDictionary"? =)
Best of luck.
Edit: Thanks for the clarification, you learn something new every day. =)
Is the only difference that allKeys returns keys in a specific order? If so, I would simply add allKeysSorted and allKeysOrderdByInsertion methods to the standard NSDictionary API.
What is the goal of this insertion order dictionary? What benefits does it give the programmer vs. an array?

Variable Naming Conventions For Maps/Lists in Dynamically-Typed languages

I am getting into Groovy language, which has dynamic typing (as well as optional static typing). It also has native support for Lists, Maps, and Ranges, so I find myself using lists and maps a lot, especially lists of lists, lists of maps, maps of lists, etc.
In static languages (esp with Generics) you always have an idea of what your type is. I am fairly new to dynamic languages, and it's getting a bit difficult to keep track of what my variable is supposed to be, so I was wondering if other people use some kind of variable naming conventions to keep these straight.
For example, suppose I have a map of dates as key and integers as values. Or List of integers, or List of Maps that contain strings as keys and account objects as values.
It seems like creating a clear convention behind variable names will help me keep track of what data type structure I am dealing with without having to look it up.
Any tips?
This is a common beginner's lament. You could use a naming convention, but odds are you'll drop it before too long and focus on what the variable represents (its meaning in relation to the rest of the code) rather than worrying about how it's represented (it's "type").
The name of your variable should explain to someone reading the code what it is supposed to be, what it stands for. If you have a map of dates to integers, does it represent, for example (suggested variable names are in brackets):
a number of payments due on that date (paymentsDue)
a number of days between mapped date and some other point in time (daysPassed)
a number of messages posted on that date on Stack Overflow (numberOfPostedMessages)
In languages where variable type is not readily available, you might want to append a prefix of suffix, such as paymentsDueMap. I would, however, advise against encoding any additional type information inside a variable name, such as datesToInts - that routinely does more harm than good.
Finally, if you have a complex data structure, such as a list of maps between strings and accounts, the best thing would be to encapsulate that into a separate class, and name it according to its intent.
In static languages (esp with Generics) you always have an idea of what your type is.
After a while of programming in dynamic languages, you learn that using types this way is a crutch. Two pieces of advice:
Use good variable naming. For instance, if you have a map of dates to ints, you can name it something like BirthdateToTotalLookup.
Learn what visual clues to look for. It may seem obvious, but it took me a while to get in the habit of looking for clues like this:
sum += x['10-16-92']
From the piece of code above, I can tell that x is a map that has a date as a key and returns a number of some kind.
If the names can be kept short, then I tend to name maps something like "nounToNoun". So using your example of dates mapping to integers, I would name that "dateToCount" (if the integers are counters for something). That way its obvious that it is a map, and its obvious what is being mapped to what. The problem is that sometimes it is difficult to keep these sort of names short and readable. For example, "userToLoginHistory" starts getting a little unwieldy.
For lists I generally use a plural for the variable name. So "user" would be a single user, and "users" would be a list of users.
To be honest, I am not sure what a good name would be for a list of maps.
One of the benefits of dynamic languages is that even if you're using an object as a Map - it doesn't HAVE to be a map. All it has to do is support whatever messages are sent to it. In Groovy, if I know that a given method expects a map so it can look up things by a String key - I can give it the full map, a stripped-down map, an Expando with a property named the same thing as the key, or any other object that has a property named the same thing as the key. This is because someObject["keyname"] and someObject.keyname are the same thing. (Of course if the code calls someObject.get("keyname") I've got to wire that method up somehow.)
The point is, in a dynamic language like Groovy you think less about TYPES and more about SUPPORTED MESSAGES. If it's conceptually a map, fine - naming it birthdateToTotal would make sense (though I prefer to call it 'totals', because totals[birthdate] looks better than birthdateToTotal[birthdate]) - but if it doesn't have to be specified, don't specify it. You leave yourself flexibility later.
This is something you'll outgrow over time. Not to say I don't know a 20-year programmer still using Hungarian, but he's coding in a static-typed language, so it's almost understandable.
Consider this. That variable you're naming might be a HashMap, so what type do you add to the name? Map? This is a middle-of-the-road answer. Why not Collection? Since that way if you decide to change the WAY the data is stored, you don't have to change the variable name. Why not HashMap, if you really want to let the reader know what's going on.
As you may suspect, none of these are necessary. The point of a dynamic language (and even of polymorphism) is that you don't need to know the exact type of the variable being presented, only the data itself is important. While you might like a hint as to how to interface to that data, you'll soon find you already know in most cases, or can easily put that info in the variable without specifying types: addressesByZipCode, totalByBirthdate, etc.