0

I'm writing a very simple program with only one class. I also want to derive my own exception but I don't want to have to use a new file. Is this okay or is it bad coding to have multiple not exactly related classes in one file?

Ben
  • 51,770
  • 36
  • 127
  • 149
user1136342
  • 4,731
  • 10
  • 30
  • 40
  • I believe this is a repost: http://stackoverflow.com/questions/4528362/where-to-define-exception-classes-inside-classes-or-on-a-higher-level – optikradio Feb 16 '13 at 00:16

2 Answers2

2

It's okay for small projects, but can quickly turn into a maintenance headache for anything bigger then that.

Categorizing classes inside both files and namespaces helps with organization, is more intuitive to where you can find what you're looking for, and is much much easier to keep track of changes (in version control).

There's also the matter of dependencies, which is probably the most important one - what if you want to use that exception somewhere else? You can't include the implementation file, and even if you keep it an a header shared with other unrelated classes, you'd be polluting the new translation unit with unneeded symbols.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

I think the answer, like many things, is that it depends. In this case, the question would be how tightly coupled the exception is to the class. If your class is called FooBarBaz and your exception is called FooBarBazException the it seems unlikely that anyone would want to use it elsewhere and I think it's alright to package it with the class. (In fact, you might argue that it should be a nested class of FooBarBaz.)

That said, when I write exceptions I try to tie them to causes rather than specific classes. For example, if I'm writing a compression library and I have support for several different algorithms, I may write a single DataCorruptionException class to convey detection of corruption. Then I can use the exception message to provide more detailed information, such as what class/function the exception came from.

Chris Hayden
  • 1,104
  • 6
  • 6