Todavía me considero un aprendiz de programador, por lo que siempre busco aprender una "mejor" forma para la programación típica. Hoy, mi compañero de trabajo ha argumentado que mi estilo de codificación hace un trabajo innecesario y quiero escuchar las opiniones de otros. Normalmente, cuando diseño una clase en lenguaje OOP (generalmente C ++ o Python), separaría la inicialización en dos partes diferentes:
class MyClass1 {
public:
Myclass1(type1 arg1, type2 arg2, type3 arg3);
initMyClass1();
private:
type1 param1;
type2 param2;
type3 param3;
type4 anotherParam1;
};
// Only the direct assignments from the input arguments are done in the constructor
MyClass1::myClass1(type1 arg1, type2 arg2, type3 arg3)
: param1(arg1)
, param2(arg2)
, param3(arg3)
{}
// Any other procedure is done in a separate initialization function
MyClass1::initMyClass1() {
// Validate input arguments before calculations
if (checkInputs()) {
// Do some calculations here to figure out the value of anotherParam1
anotherParam1 = someCalculation();
} else {
printf("Something went wrong!\n");
ASSERT(FALSE)
}
}
(o, equivalente de python)
class MyClass1:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
#optional
self.anotherParam1 = None
def initMyClass1():
if checkInputs():
anotherParam1 = someCalculation()
else:
raise "Something went wrong!"
¿Cuál es su opinión sobre este enfoque? ¿Debo abstenerme de dividir el proceso de inicialización? La pregunta no solo se limita a C ++ y Python, y también se agradecen las respuestas a otros idiomas.