Search code examples
oopcoldfusiontostringobject-to-string

toString returning all of an objects getter methods


I'm using ColdFusion, but I'd be interested to know how other languages cope with this.

Is there a better way of returning all of an objects variables (getters) without writing a massive toString() method on the object.

variables.oCity = createObject("component", "_lbr._core._locations.city").init();

variables.oCity.setName(request.parameters.sCityName);
variables.oCity.setCountryID(request.parameters.nLocationCountryID);

if(request.parameters.nStateID eq 0){
    variables.stArgs = {};
    variables.stArgs.sState = request.parameters.sLocationCountry;
    variables.stArgs.nCheckCountryID = request.parameters.nCountryID;
    variables.oCity.setStateID = application.stObj.oLocationBusiness.getState(argumentCollection=variables.stArgs).getStateID();
} else {
    variables.oCity.setStateID = request.parameters.nStateID;
}

My code looks like that. What I'd like is to output everything I have just set (as well as anything that the object defaults too) without writing a giant toString that concatenates all the various variables that might look like this:

Object: StateID = 12, Name = "Argentina", CountryID = 32, CityID = 44

My heart tells me this is unlikely.


Solution

  • This depends on how you are storing your variables within your object. I generally store all of my variables in a variables.instance structure. I then create a get() that simply returns the variables.instance structure:

    public struct function get(){
        return Duplicate(variables.instance);
    }