473,655 Members | 3,057 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Good OOP practice?

I'm currently doing a course in C# programming fundamentals.
Please will you check and comment on the following assignment:

Assignment: Create a simple calculator prgram that illistrates good OOP
practice.

I have written the following console program that I hope answers this
question (and it does work), unfortunately I couldn't really find a place
to demonstrate the concept of Encapsulation (or maybe I just dont understand
it : )
Anyway here it is:

1. What is your opinion?
2. Are all my //comments correct?

----------------------------------------------------------------------------
----------------------

using System;

class NumericInput
{
// Declare Class variables
private double convertme;
private string input;
private double converted;

// Conversion Method
public double convertMethod(s tring inputstring)
{
convertme = Convert.ToDoubl e(inputstring);
return convertme;
}

// Get User Input Method
public double getinput(string prompt)
{
Console.Write(p rompt);
input = Console.ReadLin e();
converted = convertMethod(i nput);
return converted;
}
}

class Calculate
{
// Declare Class variables
private double result;

// Sum Method
public double addMethod(doubl e num1, double num2)
{
result = (num1+num2);
return result;
}
}

class Calculator
{
// main Method runs on startup
public static void Main()
{
// Declare Variables
double myresult;
double input1, input2;

// Instantiate Object NumericInput
NumericInput userInput = new NumericInput();

input1 = userInput.getin put("Enter your first number:");
input2 = userInput.getin put("Enter your second number");

// Instantate Object Calculate
Calculate calc = new Calculate();

// Invoke Object Calculate's addMethod
myresult = calc.addMethod( input1,input2);
Console.WriteLi ne("The answer is: " + myresult);
}
}
Nov 16 '05 #1
5 5442
Okay, I'll make some comments on this.

1: where you have "// Declare Class variables", the more accurate
terminology is "fields" not variables.

2: Your convertMethod() function simply converts a string to a double. Why
not change the line:

converted = convertMethod(i nput);
to
converted = Convert.ToDoubl e(input);

That's exactly what convertMethod is doing and your simply adding a layer of
method calls, not to mention ambiguity to the code. convertMethod is a poor
name for the method because it doesn't accurately describe what it does.
Your method names should be descriptive of what the function does.
convertStringTo Double() would be a much better name for it, but in this
case, simply removing it and using Convert.ToDoubl e() is the best idea. I
simply mention the naming because it's important to name your class members
well to make the code readable by you and others.

As a further note on naming, it's a bad idea to use the word "Method" in
your method names unless it's in a sense that descibes a technique like,
MultiplyMatrice sWithStraussenM ethod where Straussen's Method is the
technique you're using to multiple matrices. Programmers will presumably
know already that your method is a method. Naming it somethingMethod is
redundant.

Finally, I would get rid of the Calculate class altogether. All it does is
adds two numbers. Creating a class to do something so simply is excessive
and in the real world, there's a huge performance penalty involved for
creating classes to do something so simple. The time spent instantiating the
class and initializing members is going to cost your more than actually
performing the addition that it exists to perform.

But, I will make one comment about your implementation of the Calculate
class. You have "result" as a field of the class but it's used as a if it
were a local variable by the addMethod method (see the redundancy in
naming?). It would be much better ot implement addMethod as follows:

public double addMethod(doubl e num1, double num2)
{
double result = (num1+num2);
return result;
}

and not have result as a class field.

I hope I don't sound overly harsh. My intention is simply to provide
constructive criticism.

Pete
"altergothe n" <ju******@webne t.za.net> wrote in message
news:mv******** ************@is .co.za...
I'm currently doing a course in C# programming fundamentals.
Please will you check and comment on the following assignment:

Assignment: Create a simple calculator prgram that illistrates good OOP
practice.

I have written the following console program that I hope answers this
question (and it does work), unfortunately I couldn't really find a place
to demonstrate the concept of Encapsulation (or maybe I just dont understand it : )
Anyway here it is:

1. What is your opinion?
2. Are all my //comments correct?

-------------------------------------------------------------------------- -- ----------------------

using System;

class NumericInput
{
// Declare Class variables
private double convertme;
private string input;
private double converted;

// Conversion Method
public double convertMethod(s tring inputstring)
{
convertme = Convert.ToDoubl e(inputstring);
return convertme;
}

// Get User Input Method
public double getinput(string prompt)
{
Console.Write(p rompt);
input = Console.ReadLin e();
converted = convertMethod(i nput);
return converted;
}
}

class Calculate
{
// Declare Class variables
private double result;

// Sum Method
public double addMethod(doubl e num1, double num2)
{
result = (num1+num2);
return result;
}
}

class Calculator
{
// main Method runs on startup
public static void Main()
{
// Declare Variables
double myresult;
double input1, input2;

// Instantiate Object NumericInput
NumericInput userInput = new NumericInput();

input1 = userInput.getin put("Enter your first number:");
input2 = userInput.getin put("Enter your second number");

// Instantate Object Calculate
Calculate calc = new Calculate();

// Invoke Object Calculate's addMethod
myresult = calc.addMethod( input1,input2);
Console.WriteLi ne("The answer is: " + myresult);
}
}

Nov 16 '05 #2
B S
Thanks a Million Pete !!!
Now this is constructive criticism that a newbie like me can really use
and learn from. All your points make alot of sense. Your time and effort
to comment on my code is much appreciated >:)

- thanks again.


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #3
You're welcome, and after re-reading my post, let me apologize for my
atrocious grammar and spelling. Made me wince to read it.

Pete

"B S" <an*********@de vdex.com> wrote in message
news:e%******** ********@TK2MSF TNGP11.phx.gbl. ..
Thanks a Million Pete !!!
Now this is constructive criticism that a newbie like me can really use
and learn from. All your points make alot of sense. Your time and effort
to comment on my code is much appreciated >:)

- thanks again.


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #4
pd******@hotmai l.com <pe**@petedavis .net> wrote:
Okay, I'll make some comments on this.

1: where you have "// Declare Class variables", the more accurate
terminology is "fields" not variables.
Not necessarily. The correct terminology (according to the C# spec) is
"instance variables" or "static variables" depending on declaration.
Both are described as fields in the C# spec.

<snip>
But, I will make one comment about your implementation of the Calculate
class. You have "result" as a field of the class but it's used as a if it
were a local variable by the addMethod method (see the redundancy in
naming?). It would be much better ot implement addMethod as follows:

public double addMethod(doubl e num1, double num2)
{
double result = (num1+num2);
return result;
}


I would go further, and avoid the local variable which serves no real
purpose here:

public double Add(double num1, double num2)
{
return num1+num2;
}

Note the capitalisation of the method name to fit with MS guidelines.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Jon,

You are correct on both points. Thanks for the corrections.

Pete

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
pd******@hotmai l.com <pe**@petedavis .net> wrote:
Okay, I'll make some comments on this.

1: where you have "// Declare Class variables", the more accurate
terminology is "fields" not variables.


Not necessarily. The correct terminology (according to the C# spec) is
"instance variables" or "static variables" depending on declaration.
Both are described as fields in the C# spec.

<snip>
But, I will make one comment about your implementation of the Calculate
class. You have "result" as a field of the class but it's used as a if it were a local variable by the addMethod method (see the redundancy in
naming?). It would be much better ot implement addMethod as follows:

public double addMethod(doubl e num1, double num2)
{
double result = (num1+num2);
return result;
}


I would go further, and avoid the local variable which serves no real
purpose here:

public double Add(double num1, double num2)
{
return num1+num2;
}

Note the capitalisation of the method name to fit with MS guidelines.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3789
by: Erik De Keyser | last post by:
Hi group, I have a couple of projects with up to 8 forms. On most projects I write the code on each form with no modules. The last project I use 1 module and minimal code on each form , in fact just the code for each visual object, and all the subroutines are placed in a module. What is the best practice where I can place my VB code, at each form or in a separate module ? Pro's & con's ? Performance benefit ?
8
2082
by: Sims | last post by:
Hi, I have some small questions that have never been any problems, (for my compiler?), but always make me curious. So here goes... what does the standard sday about the 'if' statement? for example if i have,
13
2191
by: Mel | last post by:
CAN YOU suggest an alternative ? ..heading, heading-R, heading-K, heading-G, heading-W { font-family: arial,helvetica, ms sans serif, sans-serif; font-size: 10pt; font-style: normal; font-weight: bold; text-decoration: none; }
7
2599
by: zalzon | last post by:
Is it good practice in C++ for a member function to return data or is it better that data is stored in private member variable and printed in the member function? should i be using int function1() { .... return i
3
2191
by: Andy Dingley | last post by:
We've all seen this structure many times: <ul> <li><a href="..." >Click here</a></li> <li><a href="..." >Click here</a></li> </ul> Now it's obvious good practice to have sensible link texts, and also sensible use of title attributes on either the<a> or <li> elements. What's a good rule of thumb for these attributes ?
3
1528
by: Andyza | last post by:
In my Global.asa file I have the following 2 subs for opening and closing my db connection: Sub OpenConn() Dim conn Set conn = Server.CreateObject("ADODB.Connection") conn.Open Application("ConnString") End Sub Sub CloseConn()
1
1931
by: wxqun | last post by:
Our company is now trying to make a "standard" of creating a base view for each user table. This initiative is suggested as a good practice by a data modeling consultant who is helping us to build DW logical/physical model. He pointed out that the work and risk of making a database change will be reduced by using the "base view". Since this base view is just a selection of all user table's columns, as DBA, I don't see any reasons for...
66
3687
by: KimmoA | last post by:
Hey! Some questions about C that have been bugging me for a while... 1) Is inline a valid C keyword or not? I was kind of surprised of not finding it in C, to be honest. My "The C Programming Language" book doesn't mention it. 2) I understand that C doesn't care about whitespace that much, but why did they make it impossible to use the minus ('-') char in variable names? I now have to incorrectly name my "hi-score" variable "hiscore"....
6
2555
by: MLH | last post by:
I have frmMainMenu with the following two code lines invoked on a button click... 2420 DoCmd.OpenForm "frmVehicleEntryForm", A_NORMAL, , , A_ADD, A_NORMAL 2440 DoCmd.GoToRecord , , A_NEWREC Is it generally considered good practice to issue the command in line #2440 - intended to go to a new record in the vehicle entry form - from frmMainMenu?
1
3105
by: dan | last post by:
Hi, I think I need a gridview, formview, another gridview, and another formview on a single page. There is a parent-child relationship between the first gridview and the formview and then between second gridview and the second formview. There is also a parent-child relationship between the first formview and the second gridview. Does the above look like a good practice in asp.net?
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8710
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8497
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8598
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7310
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4299
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1598
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.