Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory methods and private variables

I'm using a factory class to create instances of another class, say the Product class.

How do I set private variables within the Product class from the factory class? Should I even be doing so?

What I'm planning to do is to public setter methods and then freezing or locking the instance once I have finished with it. But I get the feeling this is the Wrong Way to do things.

How would you approach such a problem?

EDIT:

Yes I would like to use @derekerdmann's method of immutable objects. But I probably should give more info first.

I am writing a parser in php for an HTML-like language so you get nodes, which in turn can contain other nodes. So the factory is a parser producing a hierarchy of nodes. If you are curious here is the code http://http://bazaar.launchpad.net/~rhlee/band-parser/dev/view/head:/src/bands.php

The thing is that I don't know what the child nodes will be until I walk down the rest of the document. So I can't pass then to the constructor.

Sometimes I think that even though I want it to be read only after parsing, why should it be? I take for example php's DOMDocument parser. You can parse a HTML file, and then still modify the structure. However this is so that you can reproduce the HTML after again with the new changes. My parser is a one-way parser, so the need to edit the structure after parsing is non-existent.

like image 729
rhlee Avatar asked Oct 23 '22 16:10

rhlee


1 Answers

The typical way to do this is to create immutable objects. In an immutable object, all private fields are set by passing values into the object's constructor. Immutable == unmodifiable.

If you do need a way to change the private fields, the setter methods would actually create a new instance with the changed fields.

An example Java class:

class ImmutableDuck {

    private final String name;
    private final int age;

    /**
     * Constructor - sets the read-only attributes of the duck
     */
    public ImmutableDuck( String name, int age ){
        this.name = name;
        this.age = age;
    }

    public String getName(){
        return name;
    }

    public int getAge(){
        return age;
    }

    /**
     * Creates a new ImmutableDuck with the current object's age 
     * and the given age
     */
    public ImmutableDuck setName( String name ){
        return new ImmutableDuck( name, age );
    }

}
like image 188
derekerdmann Avatar answered Oct 27 '22 10:10

derekerdmann