Created
July 26, 2022 22:32
-
-
Save vrogueon/96b1c164a39cfb464d39b614f63b2a16 to your computer and use it in GitHub Desktop.
Data Class Code Smell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Data Class | |
class Address { | |
public street: string; | |
public city: string; | |
public state: string; | |
public zip: string; | |
public coordinates: Array<number>; | |
constructor(street: string, city: string, state: string, zip: string, coordinates: Array<number>) { | |
this.street = street; | |
this.city = city; | |
this.state = state; | |
this.zip = zip; | |
this.coordinates = coordinates; | |
} | |
} | |
class X { | |
public address = new AddressFixed('123 Main St', 'Anytown', 'CA', '12345', [1, 2]); | |
public buildAddress(): string { | |
return this.address.getStreet() + ' ' + this.address.getCity() + ' ' + this.address.getState() + ' ' + this.address.getZip(); | |
} | |
} | |
// Data Class Fixed | |
class AddressFixed { | |
private street: string; | |
private city: string; | |
private state: string; | |
private zip: string; | |
private coordinates: Array<number>; | |
constructor(street: string, city: string, state: string, zip: string, coordinates: Array<number>) { | |
this.street = street; | |
this.city = city; | |
this.state = state; | |
this.zip = zip; | |
this.coordinates = coordinates; | |
} | |
// Encapsulate Fields | |
public getStreet(): string { | |
return this.street; | |
} | |
public getCity(): string { | |
return this.city; | |
} | |
public getState(): string { | |
return this.state; | |
} | |
public getZip(): string { | |
return this.zip; | |
} | |
// Move and Extract Method | |
public buildAddress(): string { | |
return this.getStreet() + ' ' + this.getCity() + ' ' + this.getState() + ' ' + this.getZip(); | |
} | |
// Encapsulate Collection | |
public getCoordinates(): string { | |
return this.coordinates[0].toString() + ' ' + this.coordinates[1].toString(); | |
} | |
public addCoordinate(coordinate: number): void { | |
this.coordinates.push(coordinate); | |
} | |
public removeCoordinate(): void { | |
this.coordinates.pop(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment