now I'm worried about using up too much memory
You are not talking about a real program, just some "feeling" your programs might use up too much memory? Why? Ask this question when you have a written a program which uses too much memory, not beforehand.
My question is if one should avoid instantiating objects then whenever possible
Short answer: no, not "whenever possible", not "most times", maybe "in some rare cases". The decision to create classes and objects should be guided first and almost by the question if they form proper abstractions for your task or algorithm. Performance or memory optimizations on that level you have in mind should be done when needed, never beforehand.
should I have example(int x,int y)
or is it okay to have example(Point p)
Actually, that example might be a little bit misleading, since it will lead to calls
example(new Point(5,5))
vs.
example(5,5)
and the latter one looks more readable than the first on a first glance. In a real world program, however, you will probably not have to write something like example(new Point(5,5))
too often, instead you have to process a set of points in a way like this:
foreach(Point p in setOfPoints)
example(p);
which is more comprehensive than example(p.X,p.Y)
. And if you have really lots of calls with hard-encoded literals like example(new Point(5,5))
, you could provide both example
variants as some syntactic sugar. Note that the primary question here is "what makes the program more readable?", not "does this make a slight difference in memory usage on a micro scale level?".
Imagine what happens if you have lots of functions with more than one Point
parameter, like
bool doPointsFormATriangle(Point p1, Point p2, point p3)
vs
bool doPointsFormATriangle(double x1, double y1, double x2, double y2,double x3, double y3)
you get twice the number of parameters in the second case, and readability of calls to that function decreases by the same factor of two.
Indeed, where I work, I still have to maintain some older programs which were written by a beginners guy some years ago in the style like the second doPointsFormATriangle
, with hundreds of function calls passing all 3D points as primitive coordinates. From that experience I can tell you its horrible - so do yourself a favor and avoid that style.