If you are new to coding you might be wondering about best techniques when designing classes. Here are some thoughts on the matter, deemed from a highly talented Developer I work with. The example uses a simple calculator class that takes 2 numbers & performs a calculation on them (e.g. add, subract
RULE 1: Pass values in via a constructor if they are mandatory AND will not generally change Calculator calc = new Calculator(number1, number2, transactionType); double result = calc.GetResult(); The trouble with the code above is you would want to pass in different numbers and calculation types. So in effect your class goes from being a flexible ‘calculator’ class to an inflexible ‘singleCalculation’ class. RULE 2: Don’t allow users to misuse your class or interface Calculator calc = new Calculator(); calc.number1 = 5; calc.number2 = 7; calc.transactionType = TransactionType.Multiply double result = calc.GetResult(); The trouble with the code above is that if the user of your code forgets to set calc.transactionType (which could be easily done since it doesn’t get passed into the constructor or the GetResult() method) then the class will error RULE 3: Save memory Calculator calc = new Calculator(); double result1 = calc.GetResult(5, 7, TransactionType.Multiply); double result2 = calc.GetResult(result1, 7, TransactionType.Multiply); Passing the parameters into GetResults mean we pass both Rules 1 and 2 above and also save on memory since we only have to construct one instance of calculator class.
0 Comments
|
AuthorSeligman Ventures Ltd provide Software Testing & Development Services Archives
March 2018
Categories |