# Class design

**URL:** <https://www.ruby-forum.com/t/class-design/80394>\
**Category:** Ruby\
**Created:** [December 25, 2006, 8:56pm UTC](https://www.ruby-forum.com/t/class-design/80394 "2006-12-25T20:56:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![spitfire](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/a5b964/32.png) [@spitfire](https://www.ruby-forum.com/u/spitfire)\
**Post date:** [December 25, 2006, 8:56pm UTC](https://www.ruby-forum.com/t/class-design/80394/1 "2006-12-25T20:56:11Z")

</div>

How do I design a class such that it can never be instantiated? Say  
for example a class containing static members alone, which requires no  
instantiation!

---

<div class="post-metadata">

**Author:** ![spitfire](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/a5b964/32.png) [@spitfire](https://www.ruby-forum.com/u/spitfire)\
**Post date:** [December 25, 2006, 9:02pm UTC](https://www.ruby-forum.com/t/class-design/80394/2 "2006-12-25T21:02:13Z")

</div>

On 25.12.2006 20:54, Spitfire wrote:

> How do I design a class such that it can never be instantiated? Say  
> for example a class containing static members alone, which requires no  
> instantiation!

You can apply some tactics to make it harder but AFAIK there is no safe  
way to completely prevent instantiation. Typically something like this  
will suffice

class Foo  
def self.new(\*a,&b) raise “Must not instantiate!” end  
end

irb(main):004:0\> Foo.new  
RuntimeError: Must not instantiate!  
from (irb):2:in `new’  
from (irb):4  
from :0

Other than that you can also use module Singleton, which is probably  
better documentation wise:

irb(main):005:0\> require ‘singleton’  
=\> true  
irb(main):006:0\> class Bar  
irb(main):007:1\> include Singleton  
irb(main):008:1\> end  
=\> Bar  
irb(main):009:0\> Bar.new  
NoMethodError: private method `new’ called for Bar:Class  
from (irb):9  
from :0

Kind regards

```
robert
```

---

<div class="post-metadata">

**Author:** ![spitfire](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/a5b964/32.png) [@spitfire](https://www.ruby-forum.com/u/spitfire)\
**Post date:** [December 25, 2006, 9:04pm UTC](https://www.ruby-forum.com/t/class-design/80394/3 "2006-12-25T21:04:13Z")

</div>

On Dec 25, 2006, at 1:55 PM, Spitfire wrote:

> How do I design a class such that it can never be instantiated?  
> Say for example a class containing static members alone, which  
> requires no instantiation!

Just use a module for this:

module Static

# … defined constants and methods here …

end

James Edward G. II
