Click here to Skip to main content
15,896,730 members
Please Sign up or sign in to vote.
1.40/5 (2 votes)
See more:
In this program , I have to make sure that the MAX_CAPACITY value is set to some proper value which is taken as an input from the user. This should be done only the first time when the Cache.GetMaxCapacity() is called. I am using custom console to get inputs from the user.

Program in Cache Class

C#
 private static int MAX_CAPACITY = 0;
                     
public static int GetMaxCapacity()
{
    if (MAX_CAPACITY == 0)
    {
        Console.WriteLine("Enter Max Capacity:");
        MAX_CAPACITY = CustomConsole.ReadInt();
    }

    Console.WriteLine("Returning MAX_CAPACITY");
    return MAX_CAPACITY;
}



Program in Main function

C#
Console.WriteLine("MAX_CAPACITY is " + Cache.GetMaxCapacity());

Console.WriteLine("MAX_CAPACITY is " + Cache.GetMaxCapacity());

Console.WriteLine("MAX_CAPACITY is " + Cache.GetMaxCapacity());

Console.ReadLine();



I solved the problem using the above code but I think it's not logical , the solution should be trickier and optimized. Help me on this.
Posted
Updated 22-Feb-14 19:16pm
v2
Comments
Sergey Alexandrovich Kryukov 23-Feb-14 0:37am    
Why do you think that trivial things should be trickier? Why do you think you need any optimization?
—SA

1 solution

There really is no point in optimizing this but if your idea of optimization is less lines of code...here you go.

C#
//Usage
Console.WriteLie(MAX_CAPACITY == 0 ? "Enter Max Capacity:" : "Returning MAX_CAPACITY");
MAX_CAPACITY = GetMaxCapacity();

//"Refactored" code	
public static int GetMaxCapacity()
{
    return MAX_CAPACITY == 0 ? CustomConsole.ReadInt() : MAX_CAPACITY;
}
 
Share this answer
 
Comments
JBobby 23-Feb-14 3:22am    
thank you. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900