473,395 Members | 1,656 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

constructor question

I am trying to create a class where I will validate each parameter sent
to the contructor. I need to know which of the parameters (if any) were
invalid, so do I need to throw a user defined exception at that point so
that I know exactly which parameter had an invalid value?

I am new to creating class objects so I'm unsure about where I should do
my validation and how to trap errors. Here is my code :

private string strCardType;
private string strCardNumber;
public creditcard(string strCardType, string strCardNumber, etc...)
{
try
{
this.CardType = strCardType;
}
catch
{

}

this.CardNumber = strCardNumber;
}
public string CardType
{
get
{
return this.strCardType;
}
set
{
if ((this.strCardType.ToUpper() != "VISA") &&
(this.strCardType.ToUpper() != "MASTERCARD")
&& (this.strCardType.ToUpper() != "SWITCH") &&
(this.strCardType.ToUpper() != "DELTA")
&& (this.strCardType.ToUpper() != "SOLO") &&
(this.strCardType.ToUpper() != "JCB")
&& (this.strCardType.ToUpper() != "VISA ELECTRON") &&
(this.strCardType.ToUpper() != "MAESTRO"))
{
this.strCardType = value;
}
else
{
throw new Exception();
}
}
}

public string CardNumber
{
get
{
return this.strCardNumber;
}
set
{
this.strCardNumber = value;
}
}
Any assistance would be really appreciated.
Cheers,

Mike

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
10 1021
Mike P <mr*@telcoelectronics.co.uk> wrote:
I am trying to create a class where I will validate each parameter sent
to the contructor. I need to know which of the parameters (if any) were
invalid, so do I need to throw a user defined exception at that point so
that I know exactly which parameter had an invalid value?


The best thing to throw would be ArgumentException, which allows you to
specify which argument is invalid.

By the way - in your CardType setter, you're testing whether the
*existing* value is valid or not, rather than the value you're about to
set. Is that what you intended? It would also be a good idea to call
ToUpper *once*, and either use a Hashtable of valid values, or perhaps
a switch statement.

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

I'm not sure where I should be testing the value coming in, in the
contructor, the get or the set. I would've thought that if the value
sent through is invalid then I should be trapping it in the set, so that
I catch it in the constructor?
Regards,

Mike
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #3
Mike P <mr*@telcoelectronics.co.uk> wrote:
I'm not sure where I should be testing the value coming in, in the
contructor, the get or the set. I would've thought that if the value
sent through is invalid then I should be trapping it in the set, so that
I catch it in the constructor?


You shouldn't be catching it at all. You should be testing it in the
property, and throwing an exception there.

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

[...snip...]
You shouldn't be catching it at all. You should be testing it in the
property, and throwing an exception there.

[...snip...]

Well, I'm sure you meant the OP should catch the exception _somewhere_ ;-)
Catching it inside the constructor wouldn't be appropriate. I'd catch the
exception wherever I tried to instanciate the CreditCard instance:

try
{
CreditCard something = new CreditCard("MASTER", "1234123412341234"...);
}
catch (ArgumentException e)
{
MessageBox.Show(this, "Credit card data invalid: " + e.Message);
};
Nov 16 '05 #5
Thanks Mike. Yes, this is what I am doing now :

public class CreditCard
{
private string strCardType;
private string strCardNumber;
private string strExpiryMonth;

//#region constructors
public CreditCard(string strCardType, string strCardNumber, string
strExpiryMonth,
string strExpiryYear)
{
this.CardType = strCardType;
this.CardNumber = strCardNumber;
this.ExpiryMonth = strExpiryMonth;

}
//#endregion

//#region public properties
public string CardType
{
get
{
return this.strCardType;
}
set
{
if ((value.ToUpper() != "VISA") && (value.ToUpper() != "MASTERCARD")
&& (value.ToUpper() != "SWITCH") && (value.ToUpper() != "DELTA")
&& (value.ToUpper() != "SOLO") && (value.ToUpper() != "JCB")
&& (value.ToUpper() != "VISA ELECTRON") && (value.ToUpper() !=
"MAESTRO"))
{
throw new CardTypeException();
}
else
{
this.strCardType = value;
}
}
}

public string CardNumber
{
get
{
return this.strCardNumber;
}
set
{
Match mthCardNumber;
Regex objCardNumber = new
Regex("^[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]{12}$");

mthCardNumber = objCardNumber.Match(value);

if (mthCardNumber.Success == false)
{
throw new CardNumberException();
}
else
{
this.strCardNumber = value;
}
}
}

public string ExpiryMonth
{
get
{
return this.strExpiryMonth;
}
set
{
if ((value != "01") && (value != "02")
&& (value != "03") && (value != "04")
&& (value != "05") && (value != "06")
&& (value != "07") && (value != "08")
&& (value != "09") && (value != "10")
&& (value != "11") && (value != "12"))
{

}
else
{

}
}
}
//#endregion


}

And I am instantiating the class here :

try
{
CreditCard ccPackage = new CreditCard(strCardTypePackage,
strCardNoPackage, strExpiryMonthPackage, strExpiryYearPackage);
}
catch (CardTypeException)
{
intErrorNumber = 211;
strErrorDescription = Get_Error_Description(intErrorNumber);
Create_XML_Error_Package(bytMessageID, strCUG, intErrorNumber,
strErrorDescription);
Print_XML_Result_To_Screen();

return;
}
catch (CardNumberException)
{
intErrorNumber = 212;
strErrorDescription = Get_Error_Description(intErrorNumber);
Create_XML_Error_Package(bytMessageID, strCUG, intErrorNumber,
strErrorDescription);
Print_XML_Result_To_Screen();

return;
}

One thing I still don't get is why would I want to use a hashtable
rather than my if statement :

if ((value.ToUpper() != "VISA") && (value.ToUpper() != "MASTERCARD")
&& (value.ToUpper() != "SWITCH") && (value.ToUpper() != "DELTA")
&& (value.ToUpper() != "SOLO") && (value.ToUpper() != "JCB")
&& (value.ToUpper() != "VISA ELECTRON") && (value.ToUpper() !=
"MAESTRO"))
{
}

Maybe somebody could enlighten me on this, and show me an example.
Cheers,

Mike

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #6
Michael Voss <mi**********@lvrREMOVE.deCAPS> wrote:
[...snip...]
You shouldn't be catching it at all. You should be testing it in the
property, and throwing an exception there. [...snip...]

Well, I'm sure you meant the OP should catch the exception _somewhere_ ;-)


Not necessarily, and certainly not necessarily specifically.
Catching it inside the constructor wouldn't be appropriate. I'd catch the
exception wherever I tried to instanciate the CreditCard instance:

try
{
CreditCard something = new CreditCard("MASTER", "1234123412341234"...);
}
catch (ArgumentException e)
{
MessageBox.Show(this, "Credit card data invalid: " + e.Message);
};


I wouldn't. I'd put an exception handler far further up, almost
certainly.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7
Mike P <mr*@telcoelectronics.co.uk> wrote:
One thing I still don't get is why would I want to use a hashtable
rather than my if statement :

if ((value.ToUpper() != "VISA")
&& (value.ToUpper() != "MASTERCARD")
&& (value.ToUpper() != "SWITCH") && (value.ToUpper() != "DELTA")
&& (value.ToUpper() != "SOLO") && (value.ToUpper() != "JCB")
&& (value.ToUpper() != "VISA ELECTRON") && (value.ToUpper() !=
"MAESTRO"))
{
}

Maybe somebody could enlighten me on this, and show me an example.


It's easy enough to do:

class Foo
{
static readonly Hashtable ValidCardTypes = new Hashtable();

static Foo()
{
string[] types = {"Mastercard", "Switch", "Solo"}; // etc
foreach (string x in types)
{
string type = x.ToUpper();
ValidCardTypes[type]=type;
}
}

string strCardType;
public string CardType
{
get
{
return this.strCardType;
}
set
{
if (!ValidCardTypes.ContainsKey(value.ToUpper()))
{
throw new CardTypeException();
}

strCardType = value;
}
}
}

Advantages:
1) If you have a lot of card types in the future, a hashtable look-up
can end up being faster than testing each value
2) You can very easily go from the code above to loading the initial
list from a resource or whatever
3) You're only upper-casing the value once :)

Using just a string array would be fine too, although it would lose
advantage 1. The difference probably wouldn't be significant until you
had many, many card types though.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
I have one more question...my finished class is going to have 5 optional
parameters, which will mean 31 different overloads of this class
(optional credit card details like issue number etc). Surely there must
be an easier way of instantiating my class than having a massive switch
statement with all the different possible overloads??
Thanks,

Mike

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #9
Thanks for the example Jon, I'll definitely look into using hashtables
further!
Cheers,

Mike

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #10
Mike P <mr*@telcoelectronics.co.uk> wrote:
I have one more question...my finished class is going to have 5 optional
parameters, which will mean 31 different overloads of this class
(optional credit card details like issue number etc). Surely there must
be an easier way of instantiating my class than having a massive switch
statement with all the different possible overloads??


Well, you don't need *all* the permutations - just commonly used ones,
documenting what you should pass instead of the optional parameter if
you don't want to really specify it.

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

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

Similar topics

10
by: cppaddict | last post by:
Hi, I am writing a program and needs to know one of its object members before it can be initialized. It doesn't really matter for my question (which a C++ question, not a windows question), but...
24
by: slurper | last post by:
i have the following class sequence { public: sequence (const sequence& mysequence, const int newjob) { job_sequence(mysequence.job_sequence) job_sequence.push_back(newjob); ... }
6
by: Fred Zwarts | last post by:
Hello, I am trying to debug some complex debug code. In order to track the use of dynamically allocated memory, I replaced the standard global new and delete operators. (Not for changing the...
45
by: Ben Blank | last post by:
I'm writing a family of classes which all inherit most of their methods and code (including constructors) from a single base class. When attempting to instance one of the derived classes using...
2
by: david | last post by:
Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway, although Ollie's answer makes perfectly sense when dealing with classes, it doesn't seem to me to apply as well if you have to...
16
by: plmanikandan | last post by:
Hi, I have doubts reg virtual constructor what is virtual constructor? Is c++ supports virtual constructor? Can anybody explain me about virtual constructor? Regards, Mani
74
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the...
19
by: Jeroen | last post by:
Hi guys, I have a simple question. If I have a class like: class A { A(); ~A(); A(A& a); A(int i);
1
by: Bob Johnson | last post by:
Please note that this question is NOT about the merits of Microsoft certification (no need to get into that here). While taking a MS certification exam, I came across a question where it was...
4
by: Rahul | last post by:
Hi Everyone, It is well known that the input parameter which is passed to the copy constructor is passed as reference and not as as object. Because passing an object is as good as making another...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...

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.