Conversion between classes [closed]
Want to improve this question? Update the question so it can be answered with facts and citatio开发者_高级运维ns by editing this post.
Closed 5 years ago.
Improve this questionLet's say we have a class called A and another one called B. and we want to have a conversion method that converts A to B.
In the software architecture point of view, which one is preferred?
- write
A.export()
- write
B.import()
- write a converter class, i.e.
convert(A, B)
orConvert(A)
or ...
if the language matters, I'm using C++
It entirely depends on how you intend to use it, but in many cases, the cleanest way to do this is to implement a converting constructor:
class B { };
class A
{
A(const B& b) { }
};
B b;
A a = b; //< calls converting constructor
(of course, you could implement a converting constructor for converting from A
to B
, as well)
First of all, decide whether a conversion between them is really natural and intuitive. In that case, you could use a constructor or a member function.
However, if the connection is not too natural, you may want to go with a separate ConversionUtils class with conversion methods or something like this. 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 invoked without you realizing it. For example, if I have an a
and a b
and I write something like a==b
, the presence of a constructor in A or B that takes the other could result in successful compilation with no warning, and possibly interesting results at runtime. I would strongly encourage you to make your constructor explicit
in these cases.
If we take a short look at Java (just for information, even though you are using C++):
Say that class A is String and class B is Integer (or Double, Boolean, et c). The Java library designers have put a static method in Integer ("B") called getInteger ("import") that takes a String ("A") and produces an Integer ("B"). That would be your case 2.
On the other hand, in every class (call them "A") there is a method toString ("export") that returns a String ("B"). That would be your case 1.
So even for such basic classes, they decided to use different ways. I guess that means the same thing as @James McNellis said: it depends.
You can overload cast operators, i.e., operator T () { .. return a T value }. Whether or not you should is another matter.
I would use your third suggestion. A separate converter class for the conversion. This way you don't directly coupled A to B or B to A. A and B will have their own responsibilities whatever it is.
The converter class C its responsibility is purely conversion. Each class will be responsible for a single thing which in my opinion is a good thing. I believe this is the S in the SOLID design principles (Single Responsibility principle).
精彩评论