473,387 Members | 1,423 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,387 software developers and data experts.

Best Practices: always use new() with objects?

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.

FIRST WAY:

void somemethod
{

SomeClass X; //declares X as an object but does not instantiate it

X = Y // where Y is a reference passed by another method of type
SomeClass

// work with X within 'somemethod', and when the method 'somemethod'
ends, X is local and will disappear

}

SECOND WAY:

void somemethod
{
SomeClass X = new SomeClass(); // instantiated X

X = Y

// X will also disappear once void somemethod ends

}

Which is "better"? I say FIRST WAY. Which is safer? Perhaps SECOND
WAY, since it's less likely that X is a null reference, though if Y is
null then X can be null, so you have to check for it anyway.

Aug 12 '07 #1
8 1568
"raylopez99" <ra********@yahoo.comwrote in message
news:11**********************@o61g2000hsh.googlegr oups.com...
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.

FIRST WAY:

void somemethod
{

SomeClass X; //declares X as an object but does not instantiate it

X = Y // where Y is a reference passed by another method of type
SomeClass

// work with X within 'somemethod', and when the method 'somemethod'
ends, X is local and will disappear

}

SECOND WAY:

void somemethod
{
SomeClass X = new SomeClass(); // instantiated X

X = Y

// X will also disappear once void somemethod ends

}

Which is "better"? I say FIRST WAY. Which is safer? Perhaps SECOND
WAY, since it's less likely that X is a null reference, though if Y is
null then X can be null, so you have to check for it anyway.
Not sure why you believe avoiding a null reference is safer?

If Y is already inscope why would you want to do X = Y in the first place?

If there is a possibility that Y may be null you should write your code with
that in mind and take an appropriate action if it is. In some cases that
may be to use a new instance of the Y's type but I suspect there will be a
lot of cases where that isn't the right thing to do.

--
Anthony Jones - MVP ASP/ASP.NET
Aug 12 '07 #2
raylopez99 wrote:
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.

FIRST WAY:

void somemethod
{

SomeClass X; //declares X as an object but does not instantiate it

X = Y // where Y is a reference passed by another method of type
SomeClass

// work with X within 'somemethod', and when the method 'somemethod'
ends, X is local and will disappear

}

SECOND WAY:

void somemethod
{
SomeClass X = new SomeClass(); // instantiated X

X = Y

// X will also disappear once void somemethod ends

}

Which is "better"? I say FIRST WAY. Which is safer? Perhaps SECOND
WAY, since it's less likely that X is a null reference, though if Y is
null then X can be null, so you have to check for it anyway.
I'm assuming you mean this:

class SomeClass { }
class FIRST_WAY
{
void somemethod(SomeClass Y)
{
SomeClass X;
X = Y;
}
}
class SECOND_WAY
{
void somemethod(SomeClass Y)
{
SomeClass X = new SomeClass();
X = Y;
}
}

I think the first is the best way to write this. And it can be made even
clearer (or at least one less line of code) like this:

SomeClass X = Y;

This means that X will now hold the same reference that Y holds, so
there are now at least two references to the same object that the GC
will keep track of. When somemethod exits, the reference in X will no
longer hold and the object will have one less reference. And once the
calling code's reference (communicated using Y) goes out of scope then
the object will not have that reference anymore. Assuming nothing else
has a reference to that same object then the GC can get rid of the
object at this point.

The second one doesn't make any sense to me. The first problem I see is
that you may not have the required information to create an instance of
SomeClass from within the somemethod method. And if you do, you simply
needlessly instantiate a SomeClass then immediately free up any
references to it by assigning Y to X and the GC will simply get rid of
the object on its next pass. So you've basically done a big NOOP.

I kinda have a feeling you are trying to ask a different question here,
or I have misinterpreted what you are asking.

--
-glenn-
Aug 12 '07 #3
raylopez99 wrote:
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?
You don't create copies of objects that way in .NET.
Since I may be using the wrong lingo, to put it more concretely.

FIRST WAY:

void somemethod
{

SomeClass X; //declares X as an object but does not instantiate it

X = Y // where Y is a reference passed by another method of type
SomeClass
That will only create a copy of the reference, not a copy of the object.
As Y already is a copy of the reference that you used in the call to
somemethod, it's pointless to make another copy of it.
// work with X within 'somemethod', and when the method 'somemethod'
ends, X is local and will disappear
The variable X is local, but it's referencing the same object as Y and
as the variable you used in the call. The reference X is local, but the
object is not.
}

SECOND WAY:

void somemethod
{
SomeClass X = new SomeClass(); // instantiated X

X = Y
That is even more pointless. You create an instance of the object and
put the reference to it in the X variable. Then you overwrite the
reference with the reference in the Y variable. You have only created an
object that is never used.
// X will also disappear once void somemethod ends

}

Which is "better"? I say FIRST WAY. Which is safer? Perhaps SECOND
WAY, since it's less likely that X is a null reference, though if Y is
null then X can be null, so you have to check for it anyway.
Neither. You are just making a copy of a copy of the reference. That
doesn't protect anything at all.

--
Göran Andersson
_____
http://www.guffa.com
Aug 12 '07 #4
raylopez99 wrote:
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.

FIRST WAY:

void somemethod
{

SomeClass X; //declares X as an object but does not instantiate it

X = Y // where Y is a reference passed by another method of type
SomeClass

// work with X within 'somemethod', and when the method 'somemethod'
ends, X is local and will disappear

}

SECOND WAY:

void somemethod
{
SomeClass X = new SomeClass(); // instantiated X

X = Y

// X will also disappear once void somemethod ends

}

Which is "better"? I say FIRST WAY. Which is safer? Perhaps SECOND
WAY, since it's less likely that X is a null reference, though if Y is
null then X can be null, so you have to check for it anyway.
Actually the two codes does the same thing except that the second one
create an object that you do not use for anything.

No difference for null handling.

None of them has anything to do with shallow clone.

Arne
Aug 12 '07 #5
On Aug 12, 6:44 am, GlennDoten <gdo...@gmail.comwrote:
>
I kinda have a feeling you are trying to ask a different question here,
or I have misinterpreted what you are asking.

--
-glenn-
No, you answered my question glenn.

But I posted this before I realized that in C# there is never any
implicit shallow copying (unlike C++), therefore, SomeClass X = Y; is
somewhat pointless, since you can use Y instead in the body of the
function. However, as I type this I realize that if you pass by value
rather than by reference, that is, if you do NOT use the 'ref'
keyword: void somemethod(ref SomeClass Y) // i.e. DON'T do this, but
rather, as in your example, void somemethod(SomeClass Y), then you can
use SomeClass X = Y; for code clarity, if you do stuff in the method
that returns SomeClass (to give a reader of your code some idea that
you're not returning Y as modified, but X, though one can argue that
the lack of the 'ref' keyword should clue in the reader that this is
the case.

Come to think of it, now that I see C# is like old-fashioned C in that
you are keeping track of passing a pointer (or reference) around, why
would you ever use SomeClass X = Y; ? Just use Y directly in your
method. All this time in C# I've been doing either "FIRST WAY" or,
(rarely, but in a few instances) "SECOND WAY" above, and this has
needlessly been somewhat slowing down my programs, though how much is
debatable with all the stuff going on behind the scenes in C#.NET
anyway.

RL

Aug 12 '07 #6
raylopez99 wrote:
But I posted this before I realized that in C# there is never any
implicit shallow copying (unlike C++), therefore, SomeClass X = Y; is
somewhat pointless, since you can use Y instead in the body of the
function.
Right.
However, as I type this I realize that if you pass by value
rather than by reference, that is, if you do NOT use the 'ref'
keyword: void somemethod(ref SomeClass Y) // i.e. DON'T do this, but
rather, as in your example, void somemethod(SomeClass Y), then you can
use SomeClass X = Y; for code clarity, if you do stuff in the method
that returns SomeClass (to give a reader of your code some idea that
you're not returning Y as modified, but X, though one can argue that
the lack of the 'ref' keyword should clue in the reader that this is
the case.
But that doesn't add any clarity. You are just copying the reference,
not the object, so it's still the same object.

If you change the object and return it, you have changed the original
object, which might be confusing as the signature of the method implies
that it should return a copy and leave the original unchanged.
Come to think of it, now that I see C# is like old-fashioned C in that
you are keeping track of passing a pointer (or reference) around, why
would you ever use SomeClass X = Y; ? Just use Y directly in your
method.
Exactly.
All this time in C# I've been doing either "FIRST WAY" or,
(rarely, but in a few instances) "SECOND WAY" above, and this has
needlessly been somewhat slowing down my programs, though how much is
debatable
Not much for the "first way". Another local variable only increases the
stack frame for the method, and that only costs a few bytes of stack
space, there is no extra code for that. The copying of the reference is
just a single instruction, so that doesn't take much time.

If the method is simple enough, the compiler might even be able to
completely optimise the extra variable away, just keeping the reference
in a processor register.
with all the stuff going on behind the scenes in C#.NET
anyway.
Besides the garbage collector, there isn't much going on behind the
scenes in .NET. There is no reference counting, so there is no extra
code added when references are copied, replaced or goes out of scope.
There no extra code added to run destructors when objects become
unreachable.

When you assign a reference, the only thing that happens is that four
bytes (on a 32 bit system) is copied, nothing else. When a reference
goes out of scope, nothing at all happens. I just goes silently into the
night.
Aug 12 '07 #7
raylopez99 wrote:
Now I'm confused again. Are you saying that local variables indeed
preserve copies of Y, depending on the value of Y during the
"assignment"?
It depends on what you mean specifically. Local variables can be used
to preserve a copy of the _reference_ to the object Y. The object
remains the same, but you can replace the reference with a difference
reference, and as long as you still have a reference to the original
object is available in some other variable, then you can still get to
the original object.
(This is the way it works in C++, since SomeClass X=Y is
actually equivalent to SomeClass X(Y), where the copy constructor is
used for X).

An example:

LocalMethod (SomeClass Y) // pass by value
{

SomeClass X = Y;

// work with and change Y now, i.e. "Y++", etc

SomeClass Z = Y;

//work with and change Y now

SomeClass W = Y;

/*
Are we saying that: X != Z != W; //?!?
No. In that example all of the references still point to the same
original object, and after all the copying of the references, the
references are equal to each other. They are equal with respect to the
reference itself, and so of course the objects to which they refer are
identical as well.
I thought this is contrary to the philosophy of C#?

Wait... I will write a quick demonstration program rather than simply
post...hold on now...
[Ten minutes later...]
I think from your sample program, you see what I'm talking about. But
please feel free to ask for clarification if it's still not clear.

Pete
Aug 13 '07 #8
On Aug 13, 10:21 am, Peter Duniho <NpOeStPe...@NnOwSlPiAnMk.com>
wrote:
raylopez99 wrote:
>
Wait... I will write a quick demonstration program rather than simply
post...hold on now...
[Ten minutes later...]

I think from your sample program, you see what I'm talking about. But
please feel free to ask for clarification if it's still not clear.

Pete
Thanks for that clarification.

RL


Aug 13 '07 #9

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

Similar topics

16
by: D Witherspoon | last post by:
I am developing a Windows Forms application in VB.NET that will use .NET remoting to access the data tier classes. A very simple way I have come up with is by creating typed (.xsd) datasets. For...
11
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...
136
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...
10
by: jojobar | last post by:
Hello, I am trying to use vs.net 2005 to migrate a project originally in vs.net 2003. I started with creation of a "web site", and then created folders for each component of the site. I read...
0
by: David Helgason | last post by:
I think those best practices threads are a treat to follow (might even consider archiving some of them in a sort of best-practices faq), so here's one more. In coding an game asset server I want...
4
by: Collin Peters | last post by:
I have searched the Internet... but haven't found much relating to this. I am wondering on what the best practices are for migrating a developmemnt database to a release database. Here is the...
10
by: Ren | last post by:
Hi All, I'm still rather new at vb.net and would like to know the proper way to access private varibables in a class. Do I access the variable directly or do I use the public property? ...
9
by: Phlip | last post by:
Newsgroupies: Good guidelines keep source code within a "comfort zone". Programming languages provide extraordinarily wide design spaces, much wider than hardware designs enjoy, with many tricks...
4
by: trullock | last post by:
Hi, Can anyone suggest the best way to go about the following... I'm tracking clicks (mouse down x,y coordinates) on a web page by using some javascript to create an XHR which sends the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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...

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.