views:

53

answers:

1

Greetings,

I am writing a short simple script, but has became too crowded. Stuff has to do quite a few things

class Stuff

  attr_accessor :config # stores configuration
  attr_accessor :dbh    # stores database handle
  attr_accessor :logger # general logger to use

  def command_do_job_1
  end

  def command_do_job_2
  end

  def command_do_job...n

end

I know, this isn't a proper command pattern

The issue that comes about, is that each command needs

1. Configuration
1. Logger
1. Set of parameters
n. database handles
m. supporting methods/functions

Ok, now I'm not happy, because if I put the commands into proper objects, then I'm creating a lot of configuration entries, parameters, handles, and there is a lot of supporting methods/functions I want to re-use for different commands!

Something also seams really hookey about doing this way:

class Stuff
  attr_accessor :dbh, :logger, :config

end

class Command
  attr_accessor :parent

  def initialize(parent)
    @parent = parent
  end

  def config
    @parent.config
  end

  ad-nausiem for logger, dbh, other "joint" resources etc...
end

stuff = Stuff.new
cmd = Command.new stuff # so, I can carry the same logger, dbh, configs, etc..

So, if I break out the "commands" into proper objects and do it right, I have to make some sort of "framework/services" to execute the commands in and supply, logger, dbh, config etc..

verses

If I put the commands into methods (not a command pattern then), I get to reuse all my existing resources (config, logger, database handles, etc...), but at a cost of all these functions and methods being mixed up in 1 class.

What code structure would give me a better "resource/methods/functions" usage, but also allow me to keep my code nice and simple?

This isn't that big of a program either...

-daniel

+1  A: 

One change you could make is to put the joint resources into an ExecutionContext class, and the base Command class could contain a property to house that object. Then, when the application constructs Command sub-class instances, it could populate that context property with the shared data.

Jacob
I like this, the ExecutionContext doesn't solve all the problems, but does get a lot of them!-daniel
Daniel