I am trying to write code for a class that has a couple of attributes that will can only be known upon creation. Because I think accessor functions (e.g. getSomething()) are outdate, I declared my attributes as "public readonly" in order to protect the attributes from getting modified yet still accessible by the parent class. I am not convinced that this is the best practice for this. Implementing properties seem like a bit of a waste of time to me. (refer to this article to see what I mean)
Another issue of mine is how trapping exceptions during class creation. I know having a blank catch statement is bad, but I do not want my class to thrown an exception if something went wrong. I have no problems with this because the default values of the properties will already tell me that the class was not properly created, but again I do not think this is the best practice.
To explain further, please see my code below: - class MessageObject
-
{
-
public readonly int Length = 0;
-
public readonly int Sequence = 0;
-
public readonly bool Duplicate = false;
-
public readonly string Data = "";
-
public readonly string Message = "";
-
-
public MessageObject(string message)
-
{
-
try
-
{
-
Message = message;
-
Length = int.Parse(message.Substring(0, 3));
-
Sequence = int.Parse(message.Substring(3, 6));
-
Duplicate = message.Substring(9,1).ToLower() == "y" ? true : false;
-
Data = message.Substring(10, Length);
-
}
-
catch
-
{
-
// Do something
-
}
-
}
Help!
6 1183
I just realized that if I do a try ... catch some properties may get set while some won't, so I decided to eliminate the try ... catch block. Am I stuck with having to catch possible exceptions in the parent class?
Hi
I can agree with your decision to not use properties, though I always do use properties to expose private members to the outside world. But that 's a personal decision.
About your code. To save me a lot of blabla I rewrote your class in a way I would write it. Ofcourse it is not THE solution, but in my opinion it does what you want and it is "cleaner" - class MessageObject
-
{
-
private int length = 0;
-
public int Length
-
{
-
get { return length; }
-
}
-
-
private int sequence = 0;
-
public int Sequence
-
{
-
get { return sequence; }
-
}
-
-
private bool duplicate = false;
-
public bool Duplicate
-
{
-
get { return duplicate; }
-
}
-
-
private string data = string.Empty;
-
public string Data
-
{
-
get { return data; }
-
}
-
-
private string message = string.Empty;
-
public string Message
-
{
-
get { return message; }
-
}
-
-
public MessageObject(string message)
-
{
-
this.message = message;
-
-
// I never write logic in my constructor
-
// call a method
-
ParseMessage();
-
}
-
-
// this method parses the message injected in the constructor
-
private void ParseMessage()
-
{
-
// For every parsing line I first check if the message string
-
// is actually long enough to get the substring
-
// you could also do this at once by using 10 as the min value
-
if (message.Length >= 3)
-
{
-
// the try parse method, does the same as parse,
-
// but it returns false instead of throwing an exception
-
// the integer to store the parsed value in, is parameter with //the OUT keyword
-
int.TryParse(message.Substring(0, 3), out length);
-
}
-
if (message.Length >= 6)
-
{
-
int.TryParse(message.Substring(3, 6), out sequence);
-
}
-
if (message.Length >= 10)
-
duplicate = message.Substring(9, 1).ToLower() == "y" ? true : false;
-
-
if (message.Length >= 10 + Length)
-
data = message.Substring(10, Length);
-
}
-
}
extra tips: - for every hardcoded int (message length, and ints for substring) make it a const at the top of your class, or add it as a setting, so these values can be edited without changing code.
- instead of calling the ParseMessage from the constructor, you could set it public and give it a return value (true for successful parsing, false otherwise)
Hope this helps
Kind regards
Wim
Hi Wim. I realy appreciate what you did. Am I correct in assuming that your reason for separating logic from the constructor is in to make it easier to add alternate constructors?
Thank you.
I find all this alarming. The decision for whether or not to use a property must come from the problem specification. Is length a property of a Message object? So it's not really about what is easier to write or what looks clean but rather, what is the situation that we are trying to model.
And everything you've heard about blank catches is correct.
I find all this alarming. The decision for whether or not to use a property must come from the problem specification. Is length a property of a Message object? So it's not really about what is easier to write or what looks clean but rather, what is the situation that we are trying to model.
And everything you've heard about blank catches is correct.
What is so alarming about that? Variables pretty much serve the same purpose as properties. When I wrote JAVA code 10 years ago I had to make use of private variables and modify them through set and get functions.
What is so alarming about that? Variables pretty much serve the same purpose as properties. When I wrote JAVA code 10 years ago I had to make use of private variables and modify them through set and get functions.
What's alarming is the criteria the OP is using for deciding when to use properties and when not to use.
I use Java myself sometimes but I don't make my properites private and provide getters and setters for them as a rule. The problem I'm solving decides whether a property should be "settable" through a public method or not.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: DrUg13 |
last post by:
In java, this seems so easy. You need a new object
Object test = new Object() gives me exactly what I want.
could someone please help me understand the different ways to do the
same thing in C++. I find my self sometimes, trying
Object app = Object();
Object *app = Object();
Object app = new Object();
|
by: Matt Kruse |
last post by:
http://www.JavascriptToolbox.com/bestpractices/
I started writing this up as a guide for some people who were looking for
general tips on how to do things the 'right way' with Javascript. Their code
was littered with document.all and eval, for example, and I wanted to create
a practical list of best practices that they could easily put to use.
The above URL is version 1.0 (draft) that resulted. IMO, it is not a
replacement for the FAQ,...
|
by: 42 |
last post by:
Hi,
Stupid question:
I keep bumping into the desire to create classes and properties with the
same name and the current favored naming conventions aren't
automatically differentiating them... (both are "Pascal Case" with no
leading or trailing qualifiers).
For example... I'll be modelling something, e.g. a computer, and I'll
|
by: |
last post by:
Hi can someone send or point me to Any nice Material on .NET Best Practices
-regards
|
by: Amelyan |
last post by:
Could anyone recommend a book (or a web site) that defines best practices in
ASP.NET application development?
E.g.
1) Precede your control id's with type of control btnSubmit, txtName, etc.
2) Group relevant .aspx files into subfolders within your project
etc.
| |
by: Nate |
last post by:
I am in a slight predicament trying to determine the most efficient and
effective way to connect/disconnect from a database within a business object
(c# dll). I'm also keeping in mind the concept of connecting late and
disconnecting early.
Background:
- multi-tier application (code-behind uses properties and methods of the
business object, the business object handles the data layer)
For instance (in an ASPX code-behind file):
|
by: Nick |
last post by:
I'm looking for any guidelines along the lines of XSD Best practices
for the following issues.
If you are modelling something like interest rates, there is a choice
of how you represent that interest rate. For example you could
represent an interest rate of 5.125% as "5.125", or you could represent
the rate as "0.05125".
Somewhere you need to have some information about what 'style' is being
used
|
by: Jim |
last post by:
Hi guys,
I have an object which represents an "item" in a CMS "component" where
an "item" in the most basic form just a field, and a "component" is
effectively a table.
"item" objects can be created and then added to "component" objects to
build up the component definition.
My dilemma comes in deciding how to read/write data to the "item"
|
by: raylopez99 |
last post by:
Hi,
Best practices question.
When receiving an object passed from another method, is it a good idea
to use a shallow copy with a temporary object received on the RHS
(right hand side of =), or to use a instantiated object to receive the
object on the RHS?
Since I may be using the wrong lingo, to put it more concretely.
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |