Home > Software engineering >  List items added from one class not accessible from another class
List items added from one class not accessible from another class

Time:10-26

I am writing a program which uses a list to store Employee data, following SOLID principlce i am try to move as much functionaity out of the main class into their own classes. I have a repository class which sets out the inital list values as well as contains read and create methods to access and edit the list. my issue is that my new class cannot access anything subsequently added to the list and only sees the intail data presant on boot.

Here is my Repo Class:

public class Repository
{
private List<EmployeeData> myEmployeeData = new List<EmployeeData>()
{
    new EmployeeData()
    {
        EmployeeID = 1,
        FName = "Joe",
        LName = "Bloggs",
        isPermanent = true,
        Salaryint = 40000,
        Bonusint = 5000,
        DayRateint = null,
        WeeksWorkedint = null
    },

    new EmployeeData()
    {
        EmployeeID = 2,
        FName = "John",
        LName = "Smith",
        isPermanent = true,
        Salaryint = 45000,
        Bonusint = 2500,
        DayRateint = null,
        WeeksWorkedint = null
    },

    new EmployeeData()
    {
        EmployeeID = 3,
        FName = "Clare",
        LName = "Jones",
        isPermanent = false,
        Salaryint = null,
        Bonusint = null,
        DayRateint = 350,
        WeeksWorkedint = 40
    }
};

public EmployeeData Create(int IDcount, string fname, string lname, bool isPerm, int? Salary, int? Bonus, int? DayRate, int? WeeksWorked)
{
    var createEmployee = new EmployeeData()
    {
        EmployeeID = IDcount,
        FName = fname,
        LName = lname,
        isPermanent = isPerm,
        Salaryint = Salary,
        Bonusint = Bonus,
        DayRateint = DayRate,
        WeeksWorkedint = WeeksWorked
    };
    myEmployeeData.Add(createEmployee);
    return createEmployee;
}

public IEnumerable<EmployeeData> ReadAll()
{
    return (myEmployeeData);
}

public EmployeeData Read(int employeeID)
{
    return myEmployeeData[employeeID];
}

public EmployeeData Update(int employeeID, string fname, string lname, bool isPerm, int? Salary, int? Bonus, int? DayRate, int? WeeksWorked)
{
    var x = Read(employeeID);
    x.FName = fname;
    x.LName = lname;
    x.isPermanent = isPerm;
    x.Salaryint = Salary;
    x.Bonusint = Bonus;
    x.DayRateint = DayRate;
    x.WeeksWorkedint = WeeksWorked;
    return x;
}

public bool Delete(int employeeID)
{
    myEmployeeData.RemoveAt(employeeID);
    return true;
}
}

here is my new classes which cannot access newly created items:

public class Calculator : Repository
{
public double AnnualPayAfterTax;
public double AnnualPay;

public double CalculateEmployeePay(int employeeID)
{
    bool EmploymentStatus = Read(employeeID).isPermanent;
    if (EmploymentStatus == true) 
    { 
        int Salary = (int)Read(employeeID).Salaryint;
        int Bonus = (int)Read(employeeID).Bonusint;
        AnnualPay = Salary   Bonus;
    }
    else {
        int DayRate = (int)Read(employeeID).DayRateint;
        int WeeksWorked = (int)Read(employeeID).WeeksWorkedint;
        AnnualPay = (DayRate * 5)   WeeksWorked;
    }
    if (AnnualPay < 12570) { AnnualPayAfterTax = AnnualPay; }
    if (AnnualPay > 12570) { AnnualPayAfterTax = (AnnualPay - 12570) * 0.2; }
    return (AnnualPayAfterTax);
}
}

and here is the part of my main method which calls both classes, note read() works fine in this class for newly added list items.

                    bool CalLoop = false;
                while (CalLoop == false)
                {
                    Console.Clear();
                    Console.WriteLine("CALCULATE ANNUAL PAY\n");
                    Console.WriteLine(string.Concat(re.ReadAll()));
                    Console.Write("\nSelect ID of Employee:  ");
                    string Input = Console.ReadLine();
                    bool valid = int.TryParse(Input, out Output);
                    if (valid)
                    {
                        int selectedID = Output;
                        selectedID = selectedID - 1;
                        bool CheckID = (selectedID <= IDcount);
                        if (CheckID)
                        {
                            Console.WriteLine("Employee Name:  "   re.Read(selectedID).FName   " "   re.Read(selectedID).LName);
                            Console.WriteLine("Employment Type:  "   re.Read(selectedID).isPermanent);
                            Console.WriteLine("Annual Pay after Tax:  £"   cal.CalculateEmployeePay(selectedID));
                        }
                        else
                        {
                            Console.WriteLine("Invaild ID.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Invaild ID.");
                    }
                    CalLoop = true;
                }

Any ideas why my new class can't see anything newly added to the list? i thought lists updated dynamically during the whole runtime? Have i missed something?

Appreciate any help or comments, so thank you in advance!

CodePudding user response:

private List<EmployeeData> myEmployeeData = new List<EmployeeData>() is private ... change it to protected so that inherited classes can access it.

CodePudding user response:

You have two classes :

public class Repository
{
    public List<EmployeeData> myEmployeeData = new List<EmployeeData>();
}

public class Calculator : Repository
{ }

When this two classes are instanciated, you can see its don't share the same list :

var rep = new Repository();
var cal = new Calculator();

if(object.ReferenceEquals(rep.myEmployeeData, cal.myEmployeeData))
{
    Console.WriteLine("Repository and Calucaltor share the same liste.")
}
else
{
    Console.WriteLine("Repository and Calucaltor don't share the same liste.")
}

A class is like a plan to build a building. For example, a plan "BaseBuilding" has a reception and a restroom. And a plan "OfficeBuilding" that extends (inherits) from the plan "BaseBuilding" and add some office to work

Next, you construct a building following plan "BaseBuilding" and a other building following plan "OfficeBuilding". In this case, you construct two receptions and restrooms (one by building).

It's the same when you instanciate Repository and Calculator. This create two distinct objects where each has their own list. For more information, see the official documentation about inheritance;

But it's the real problem. When a class A inherit from a class B, then you can subtituate B by A. In your case, Calculator inherit from Repository, then you can subtituate Repository by Calculator.

I use the repository to read employee's informations.
I use the calculator to read employee's informations.

The first sentence is clear, but the second... sounds weird. This is beaucse this break the third SOLID principle (Liskov substitution).

Also why the calculator can read employee's information? This is the repository's responsibility to retreive employee's informations. A calculator should only do calculations. This breack the first SOLID principe (single responsibility).

If you want follow the SOLID principes, then I advise you to avoid inheritance and prefer the composition.

In your case :

class Calculator
{
    private readonly Repository _repository;

    public Calculator(Repository repository)
    {
        _repository = repository;
    }

    public double CalculateEmployeePay(int employeeID)
    {
        bool EmploymentStatus = _repository.Read(employeeID).isPermanent;
        ...
    }
}

So the calculator only calculate and repository only manage employees.

  • Related