TOPIC: Converting a Function to a Class with Instance
#730
Converting a Function to a Class with Instance 3 Years, 5 Months ago
Category: Coding

Ingredients

- function, class, CallClass, New, this
- Refactor > Convert Function To Class

Problem

You start with a function, but then it gets big so you convert it to a class using Refactor > Convert Function To Class (or by hand). But then you find you are passing a lot of arguments around so you want to create an instance so you can put shared values in members.

Recipe

There are several ways to do this, but there are some potential problems with some methods.

We start with:

Code:

Sample

class
    {
    CallClass(...)
        {
        ...



One way to do it would be:

Code:

Sample

class
    {
    CallClass(args)
        {
        new Sample(args)
        }
    New(args)
        {
        ...



One problem with this is that you can no longer return a result because New always returns the new object.

The other problem is that because we specifically created a Sample instance, it will not work if we inherit/derive from this class (unless we redefine CallClass). It would also "break" if we renamed the record without also remembering to change the CallClass.

Here is a better solution:

Code:

class
    {
    CallClass(args)
        {
        instance = new this
        return instance.Run(args)
        }
    Run(args)
        {
        ...



which we can shorten up to:

Code:

class
    {
    CallClass(args)
        {
        return (new this).Run(args)
        }
    Run(args)
        {
        ...



This is what I would normally use.

But if you inherit/derive from this class it can sometimes be useful to separate the initialization:

Code:

class
    {
    CallClass(args)
        {
        return (new this(args)).Run()
        }
    New(args)
        {
        .args = args
        }
    Run()
        {
        ...



PS. We should probably add a Refactor > Convert Function To Class With Instance
 
 
andrew