I have implemented Object Oriented Programming in my project and I am exploring ways to effectively change the state of an object while ensuring its integrity. Although I have created a code snippet for this purpose, I am curious if there are more optimized methods or established design patterns that can be used in OOP development.
Below is the excerpt of the code I have developed:
export class AccessProfile {
id!: number;
active!: boolean;
name!: string;
createdAt!: Date;
createdBy!: string | null;
createdFrom!: SystemModule;
updatedAt!: Date;
updatedBy!: string | null;
updatedFrom!: SystemModule;
environment!: Environment;
hierarchy!: number | null;
permissions!: Set<string>;
public update(
{
updatedFrom,
updatedBy = null,
name,
active,
hierarchy,
permissions
}: {
updatedFrom: SystemModule,
updatedBy?: string | null,
name?: string,
active?: boolean,
hierarchy?: number | null,
permissions?: Set<string>,
}
) {
const backup = {
name: this.name,
active: this.active,
hierarchy: this.hierarchy,
permissions: this.permissions
};
try {
if (name !== undefined) {
name = AccessProfile.sanitizeName(name);
if (this.name !== name) {
AccessProfile.validateName(name);
this.name = name;
}
}
if (active !== undefined && this.active !== active) {
this.active = active;
}
if (hierarchy !== undefined) {
hierarchy = AccessProfile.sanitizeHierarchy(hierarchy);
if (this.hierarchy !== hierarchy) {
AccessProfile.validateHierarchy(hierarchy);
this.hierarchy = hierarchy;
}
}
if (
permissions !== undefined
&& !permissionsAreEqual(permissions, this.permissions)
) {
this.permissions = permissions;
}
if (this.hierarchy !== backup.hierarchy && this.permissions !== backup.permissions) {
AccessProfile.validateHierarchyAndPermissions({
hierarchy: this.hierarchy,
permissions: this.permissions
});
} else if (this.hierarchy !== backup.hierarchy) {
AccessProfile.validateHierarchyAndPermissions({
hierarchy: this.hierarchy,
permissions: backup.permissions
});
} else if (this.permissions !== backup.permissions) {
AccessProfile.validateHierarchyAndPermissions({
hierarchy: backup.hierarchy,
permissions: this.permissions
});
}
this.updatedFrom = updatedFrom;
this.updatedBy = updatedBy;
this.updatedAt = new Date();
return this;
} catch (err) {
this.name = backup.name;
this.active = backup.active;
this.hierarchy = backup.hierarchy;
this.permissions = backup.permissions;
throw err;
}
}
}