Skip to content

Use Module instead of Class #6

@tilo

Description

@tilo

It's not good practice in Ruby to do this:

v = DomainNameValidator.new
v.validate('a.com')

Creating an instance of a class, just to call a method on some given data.
This should not be a class, because it does not have to be keeping state per instance.
Also, someone could create multiple instances of this, which would be wasteful.

A better way to do this is this:

module DomainNameValidator
  def self.validate(dn, errs =[])  # or `valid?`
    ...
   end
end

and then it's called as follows:

      DomainNameValidator.validate("something.com")

btw. this might be a nicer interface:

module DomainNameValidator
  def self.errors(dn)
    ...
      return errs
   end

   def self.valid?(dn)
      errors(dn).empty?
   end
end

then the call would be:

  DomainNameValidator.valid?("-a.com")
=> false

  DomainNameValidator.errors('-a.com')
=> ["Domain label contains an illegal character"]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions