2017-05-10 5 views
0

Ich habe eine eckige Komponente, die einen Typ verwendet, was wäre eine leicht lesbare Lösung, um eine Daten in einem Fall und den anderen in einem anderen zu bekommen?Wie würde man einen staatsabhängigen Getter vereinfachen, vorzugs weise auf eine SOLID-Weise?

Die Komponente könnte auch in zwei Komponenten getrennt werden, die Telefonkomponente und die E-Mail-Komponente, aber die meisten der Logik, wenn auch klein, würden dupliziert werden.

var getContactInfo, hasContactInfo; 
if(type === 'email') { 
    getContactInfo = function (profile) {return profile.getEmail()}; 
    hasContactInfo = function (profile) {return profile.hasEmail()}; 
} else if(scope.type === 'phone') { 
    getContactInfo = function (profile) {return profile.getPhone()}; 
    hasContactInfo = function (profile) {return profile.hasPhone()}; 
} 

Antwort

1

Ich würde wahrscheinlich ein Objekt verwendet haben, die Methoden Abbildung je nach Typ:

const buildContactInfo = (getContactInfo, hasContactInfo) => ({ getContactInfo, hasContactInfo }); 

const contactInfoByType = { 
    email: buildContactInfo((profile) => profile.getEmail(), (profile) => profile.hasEmail()), 
    phone: buildContactInfo((profile) => profile.getPhone(), (profile) => profile.hasPhone()) 
}; 

dann beim Aufruf:

const contactInfo = contactInfoByType[type]; 
if (!contactInfo) { 
    throw new Error(`No contact info matched type '${type}'`); 
} else { 
    contactInfo.hasContactInfo(profile); 
    contactInfo.getContactInfo(profile); 
} 
+0

Ich denke, das ist in Ordnung, es verwendet :) –

Verwandte Themen