DRY – Don’t Repeat Yourself
ControlSignUp and ControSignIn are nearly identical. I’ve commented a “here” on the only 4 lines which are different. How can I combine this common functionality?
Actually it seem obvious..I can just pass in a single variable through the constructor…just a sec.
Answer:
/**
* ControlSign
*/
var ControlSign = function( type )
{
var form_element = document.getElementById( type );
var response_element = document.getElementById( type + '_response' );
var text_object = new Text( form_element );
var message_object = new Message( response_element );
this.invoke = function( )
{
if( Global.validate_input_on === 1 )
{
if( !text_object.checkEmpty() )
{
message_object.display( 'empty' );
return false;
}
if( type === 'signup' && !text_object.checkPattern( 'name' ) )
{
message_object.display( 'name' );
return false;
}
if( !text_object.checkPattern( 'email' ) )
{
message_object.display( 'email' );
return false;
}
if( !text_object.checkPattern( 'pass' ) )
{
message_object.display( 'pass' );
return false;
}
}
AjaxNew.repeatUse( ajaxSerialize( form_element ) + '&ajax_type=' + type + '_control', function( server_response_text ) { ajaxType( server_response_text, response_element, 'respond' ); } );
}
};
ControlSign.in = function()
{
new ControlSignIn( 'signin' ).invoke();
};
ControlSign.up = function()
{
new ControlSignUp( 'signup' ).invoke();
};
Simple solution: Make it a function
ControlSignwith a parameter, invoked with"in"or"up". You could call this “factory pattern”.Complex solution: you use a
factoryfunction to create the two constructors. OK, what I meant is the use of a closure to create constructors:I guess this should neither be called “factory pattern” nor “abstract factory pattern”.