Conversion between classes
Let's say we have a class called A and another called B. and we want to have a conversion method that converts A to B.
In a software architecture point of view, which one is preferable?
- to write
A.export()
- to write
B.import()
- write a converter class i.e.
convert(A, B)
orConvert(A)
or ...
if language matters i use c ++
a source to share
It depends entirely on how you are going to use it, but in many cases the cleanest way to do it is to implement a conversion constructor:
class B { };
class A
{
A(const B& b) { }
};
B b;
A a = b; //< calls converting constructor
(of course you can implement a conversion constructor to convert from A
to B
))
a source to share
First of all, decide if the conversion between them is really natural and intuitive. In this case, you can use a constructor or member function.
However, if the connection is not too natural, you can go with a separate ConversionUtils class with conversion methods or something like that. You don't want to start creating too many dependencies between classes or end up implementing n * n conversions.
It is also important to be careful with "conversion constructors" as they can be called if you are not aware of it. For example, if I have an a
and b
, and I write something like a==b
, having a constructor in or B that takes another could lead to successful compilation without warning and possibly interesting run-time results. I highly recommend that you make your constructor explicit
in these cases.
a source to share
If we take a quick look at Java (just for information, even if you are using C ++):
Suppose class A is String and class B is integer (or Double, Boolean, et c). The Java library designers put a static method in Integer ("B") called getInteger ("import"), which takes a string ("A") and creates an Integer ("B"). This will be your case 2.
On the other hand, in every class (call them "A") there is a toString ("export") method that returns a string ("B"). This will be your case 1.
Therefore, even for such base classes, they decided to use different methods. I guess it means the same thing @James McNellis said: it depends.
a source to share
I would use your third suggestion. Separate converter class for conversion. So you don't directly associate AB or B with A. A and B will fulfill their responsibilities no matter what it is.
Converter class C is purely a conversion. Each class will be responsible for one thing, which in my opinion is a good thing. I believe that this is S in the SOLID design principles (principle of single responsibility).
a source to share