[fpc-pascal] methods of an object to create others objects

Marcos Douglas md at delfire.net
Mon Jul 5 21:51:54 CEST 2010

On Mon, Jul 5, 2010 at 4:07 PM, spir <denis.spir at gmail.com> wrote:
> On Mon, 5 Jul 2010 15:48:40 -0300
> Marcos Douglas <md at delfire.net> wrote:
> Questions of style: just a personal opinion.
>> We can to use methods of an object to create others objects, or this
>> is a bad programming practice?
>> eg:
>> var
>>   obj1, obj2: TmyObject;
>> begin
>>   obj1 := tobj1.create; //ok
>>   obj2 := obj1.createObj; // is this recommended?
>>   try
>>   //...
>>   finally
>>     obj1.free;
>>     obj2.free;
>>   end;
>> end;
> How else can one program using object orientation?
>    t1, t2 : Text ;
>    t1 := Text('abcdefghi') ;
>    t2 := t1.section(3,7) ;
>    t2.write ;       // 'cdefg', if I'm right ;-)
> Or do you mean to copy a (referenced) object?
>> Why I ask this:
>> If not exists the variable obj2 in call obj1.createObj will happen a
>> memory leak, right? Because there is not variable to release.
> Do you mean using a function as a statement? (for its so-called "side effect")
> *This*, in my opinion, is very bad programming practice. But it's just an opinion.
> First, a function that has effects is already bad, except for recording data
> on the object (eg metadata, or memoization).

What do you mean "a function has effects is already bad"?
A function/procedure always has effects, don't?

> Second, if you really want it to *do*
> something in addition to *making* its return value, you should make this "anomaly"
> obvious by writing the effect in an external proc (called by the func). So that, when you
>  need the effect but not the value, just call the proc.

Well... I think something is smell bad with this code :)
But I will try a better example:
Imagine a text file. Each line correspond an object. A parser creates
these objects. So, in a loop:

for I := 0 to Lines.Count-1 do
  line := Lines[I];
  obj := Parser.GetObj(line);

The object Parser creates obj through the line string.
If the *line* is broke, Parser do not can create an object and an
Exception is created; the *obj* never is nil because there are
exception handling.

Do you have a better idea for this example?

Marcos Douglas

More information about the fpc-pascal mailing list