views:

351

answers:

2

I'm doing this to learn about class creation and to test geometry routines. As I build the class I will add other polygon-related functionality like getting the bounding box, determining convexity, turning the poly into triangles and the like.

Is it best to put that kind of code in functions or in methods of the class?

A: 

If it acts primarily on an instance of a class, it should be an instance method of that class. If its functionality is independent of any particular instance of the class, it should be a class method. I can't think of any especially good general rule for having functions that act on objects — generally such things would be be class methods.

Chuck
+1  A: 

All functionality you mentioned should be implemented as instance methods.
For example:
The operation that determines the bounding box only uses data of an instance (the vertices of the polygon), so it should be implemented as instance method.

- (NSRect)calculateBoundingBox;

I am not entirely sure about "turning the poly into triangles" part, because you might release the polygon after converting it. So this class wouldn't be self-contained. You could implement the "polygon to triangle conversion" in a class method or in a separate controller. Here you can find more about instance and class methods: Learning Objective-C: A Primer (in "Methods and Messaging")

Some scenarios where I would use class methods, static functions or #defines instead of instance methods:

  • Functions to initialize structs (e.g. NSMakeRect, ...)
  • Short snippets that I use often (typically some math-shortcut defines)
  • Factory methods to create instances
weichsel