Best Practice for Code
good day,
have written 1st c# console application. have tried looking answer question, have not found helps answer it, here turning help. i'm trying incorporate many different items in small appl. can refer develop other programs, included case structure, parse method include if else, had though type of module haven't gotten there yet.
it not let them continue. think use if elseif elseif elseif structure accomplish task, isn't there more concise way this? don't know if while loop in order isolating string f = console.readline(); line better or what. suggestions appreciated. thank you.
namespace consoleapplication1
{
class program
{
static void main(string[] args)
{
console.writeline("enter first #:");
int x = int.parse(console.readline());
console.writeline("which mathematical operation going do?");
string f = console.readline();
console.writeline("enter second #:");
int y = int.parse(console.readline());
switch (f){
case "+": // addition block
int = x + y;
console.writeline("the answer is: " + a);
break;
case "-": //do subtraction block
int b = x - y;
console.writeline("the answer is: " + b);
break;
case "*": // multiplication block
int c= x * y;
console.writeline("the answer is: " + c);
break;
case "/": //do division block
int d = x / y;
console.writeline("the answer is: " + d);
break;}
console.readline();
}
}
}
there more concise , simple way write program using dictionaries , extracting methods.
the following program same things yours.
using system; using system.collections.generic; namespace mathapplication { class program { static void main() { var x = readint("enter first #:"); var f = readstring("which mathematical operation going do?"); int y = readint("enter second #:"); var operation = getoperation(f); var result = operation(x, y); console.writeline("the answer is: " + result); console.readkey(); } private static int readint(string message) { return int.parse(readstring(message)); } private static string readstring(string message) { console.writeline(message); return console.readline(); } private static func<int, int, int> getoperation(string f) { var operations = new dictionary<string, func<int, int, int>> { { "+", (x, y) => x + y }, { "-", (x, y) => x - y }, { "*", (x, y) => x * y }, { "/", (x, y) => x / y }, }; return operations[f]; } } }
in terms of best practices, should consider:
- use names namespaces, variables, methods , on. makes code more clear , easy understand , maintain.
- avoid duplications. dry. extract methods best refactoring.
- use dictionaries of func to avoid switch statements , chain of ifs
- consider using console.readkey wait key press user
hope helps.
andrea angella
Visual Studio Languages , .NET Framework > Visual C#
Comments
Post a Comment