views:

44

answers:

2

Is setX() method name appropriate for only for setting class property X?

For instance, I have a class where the output is a string of an html table. Before you can you can call getTable, you have to call setTable(), which just looks at a other properties and decides how to construct the table. It doesn't actually directly set any class property -- only causes the property to be set. When it's called, the class will construct strHtmlTable, but you can't specify it.

So, calling it setTable breaks the convention of get and set being interfaces for class properties.

Is there another naming convention for this kind of method?

Edit: in this particular class, there are at least two ( and in total 8 optional ) other methods that must be called before the class knows everything it needs to to construct the table. I chose to have the data set as separate methods rather than clutter up the __construct() with 8 optional parameters which I'll never remember the order of.

A: 

Yes, setX() is primarily used for setting a field X, though setX() may have some additional code that needs to run in addition to a direct assignment to a field. Using it for something else may be misleading to other developers.

I would definitely recommend against having a public setTable() and would say that setTable() could be omitted or just an unused private method depending upon your requirements.

It sounds like the activity to generate the table is more of a view of other properties on the object, so you might consider moving that to a private method on the object like generateHtmlTable(). This could be done during construction (and upon updates to the object) so that any subsequent calls to getTable() will return the the appropriate HTML.

Rob Tanzola
To answer your other question about a naming convention for the method you described, I have not come across one. I am interested to see if someone else responds with one, though.
Rob Tanzola
+1  A: 

I would recommend something like generateTable() instead of setTable(). This provides a situation where the name of the method clearly denotes what it does.

I would probably still use a setTable() method to actually set the property, though. Ideally, you could open the possibility of setting a previously defined table for further flexibility.

EricBoersma
I agree, using a private setTable() to actually set the value of the field from within generateTable() sounds right to me.
Rob Tanzola