Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it ok to have both static and instance methods all in a class

Tags:

ruby

This is not specific to Ruby, but I happen to be using Ruby at the moment.
Here is a class that provides text printing functionality.

class Printer

  # some static methods

  def self.fancy_print(text)
     # do fancy formatting
  end

  def self.print(text)
     fancy_print(text)
  end

  # some instance methods

  def initialize(text)
    @text = text
  end

  def print
    #somehow call fancy_print(@text)
  end
end

Is it bad design to provide both instance and static methods in a class?

Sometimes I would like to keep several instances of Printer lying around. Other times, I just need to say Printer.print(text) and just grab that text without bothering to store it for later, hence resulting in a static print method and an instance print method.

like image 851
MxLDevs Avatar asked Dec 26 '22 19:12

MxLDevs


1 Answers

No, it's not bad design.

It's completely normal–some methods are class methods, some are instance methods. I'm not sure what the perceived issue might even be. It's somewhat difficult to even find classes with only one or the other, although in Java you frequently see static utility classes.

Edit IMO the question is misleading; you're actually asking if it's bad design to have static and instance methods of the same name.

It's tricky if both are public because it isn't necessarily obvious how to use the class. In other words, is it designed to be used via the static, or instance method? Both? What's different about them? Should that difference be... differentiated by a name?

Ultimately it depends on context and usage–there's no single answer.

like image 102
Dave Newton Avatar answered Apr 13 '23 01:04

Dave Newton