tags:

views:

108

answers:

2

Hello

I`ve been wondering how to implement methods in a class. Could someone explain me what means if one does OOP in procedural style?

Here is an example:

class Fld extends Model {

  private $file;
  private $properties = array();

  public function init($file) { 
    $this->file = $file;
    $this->parseFile();
  }

  private function parseFile() {
  // parses the file
    foreach($this->file as $line) {
      //..................
    }
    $this->properties = $result;
  }

}

I mean is it a good thing to have methods like these that do operations for the class properties like that. Or should I pass the class property as method parameter... I mean this would cause error if the file property wouldnt be declared.

+3  A: 

If the file is mandatory for you object, it should be a parameter in your constructor.

class Fld extends Model {

    private $file;
    private $properties = array();

    function __construct($file) {
        $this->file = $file;
    }

    public function parse() {
        foreach($this->file as $line) {
            /* ... */
            $this->properties = $result;
        }
    }
}

When there is a method in your class which does not use any of the class properties, you should think about making that method static or even create a separate class for this method.

eteubert
So it is ok to have methods like that..
PPPHP
Well I know things can be done in dozens of ways..
PPPHP
Ouh, looks like I forgot to put the short answer somewhere up there. Yes, you can do it that way. Nothing wrong :)
eteubert
+1  A: 

I think people describe code as "OOP in procedural style" when the methods inside a class tend to be very long and complex.

Martin Fowler's book 'Refactoring', describes a long method as a 'code smell' that hints that parts of its code could be broken down into smaller methods or separated out into other classes.

see: http://books.google.co.uk/books?id=1MsETFPD3I0C&lpg=PP1&dq=refactoring&pg=PA76#v=onepage&q&f=false

I think your code is perfectly fine. Just bare in mind how disposable the objects of the class are. Generally a 'parsing service' like this should be created, used and thrown away. Then you won't have to worry about old properties causing confusion if it is re-used.

As eteubert suggests, passing the tooling in the constructor helps to let the clients know that the object is being created for a very particular purpose.

JW