Please ignore language syntax, I want to discuss only OOPS here.
I will present here 2 code snippets, each of which is a sample of Composition (if I'm not wrong).
Problem Statement: I have an object which keeps the stats of an entity in the system. Let those stats be:
- Name
- LastName
- Salary
*these fields can be anything, I just took these for example. so please dont think in terms of what field is necessary or not. Assume all three are necessary.
I created a class which corresponds to these fields:
public class Stats{
field Name;
field LatsName;
field Salary;
}
Now I came across a situation where i want to have information about a person across time period. Lets see at a point in the workflow system requires that it be presented with information about a person for all three stages
- When he was child.
- When he was young.
- when he got retired.
Point to note here is that name
and lastName
won't change, only salary might change. Because of this, I thought that I can perhaps create a class that can use existing object 'stats'.
I'm goin to present two solutions , Please suggest which one is better and why.
Code Sample 1
public class CompositeStats{
//Adding three more properties and hinding the one already existing.
private objStats= new Stats();
public field FirstName{
get{return objStats.Name;}
set{objStats.Name=value;}
}
public field LastName{
get{return objStats.LastName;}
set{objStats.LastName=value;}
}
public field SalaryChild{get;set;}
public field SalaryYoung{get;set;}
public field SalaryRetired{get;set;}
}
In the above sample code, I did not expose the original field of salary but have created 3 new for each time span.
Code Sample 2
public class CompositeStats{
private objStatsChild= new Stats();
private objStatsYoung= new Stats();
private objStatsRetired= new Stats();
public field FirstName{
get{return objStatsChild.Name;}
set{objStatsChild.Name=value;}
}
public field LastName{
get{return objStatsChild.LastName;}
set{objStatsChild.LastName=value;}
}
public field SalaryChild{
get{return objStatsChild.Salary;}
set{objStatsChild.Salary=value;}
}
public field SalaryYoung{
get{return objStatsYoung.LastName;}
set{objStatsYoung.LastName=value;}
}
public field SalaryRetired{
get{return objStatsRetired.LastName;}
set{objStatsRetired.LastName=value;}
}
}