简体   繁体   中英

Instance Methods vs. Class methods For a Helper Class - Ruby, Rails

I am working on a rake task which creates new records in local db based on a query submitted to an external db ( MS SQL ). Connection, querying and record creating happens in a helper I created called ExternalDatabaseConnector . Rake tasks simply calls methods and operates as controller of sort.

My question is whether methods in my helper class (I have establish_connection , execute_query , create_hash and store_records ) should be called on self (ie be class methods) or each be called on an instance of my helper?

I am thinking that there will only be one connection and the rake task will only fire once per its schedule, and there is no need to create separate instances of my helper class?

If you don't need to customize the state of each instance (via initialize and instance variables), it makes sense to make class methods instead. If you're going with class methods, you could make your Class a Module and it would have the same effect.

If you're using a purely functional paradigm when programming, you wouldn't ever use instance methods. Instead, you'd pass all your needed data as arguments. I'm not recommending this approach because OOP simply makes things easier in many cases, but for this situation, class methods make sense to me. Functional programming is useful (methods like map , reduce , or the proc shorthand ), but I don't see any reason to use it instead of OOP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM