473,698 Members | 2,796 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1591
"raylopez99 " <ra********@yah oo.comwrote in message
news:11******** **************@ o61g2000hsh.goo glegroups.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(Some Class Y)
{
SomeClass X;
X = Y;
}
}
class SECOND_WAY
{
void somemethod(Some Class 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.c omwrote:
>
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(Some Class 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(Some Class 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...@Nn OwSlPiAnMk.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
3027
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 example dsParts.xsd and including that in the data tier. I then will create a class that looks like this Public Class CPart Inherits dsParts
11
9252
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();
136
9379
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,...
10
3453
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 somewhere that each folder under the "web site" is compiled in separate assembly. I however, did not find that the "web site" creation in vs.net 2005 created any AssemblyInfo.cs file.
0
793
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 to keep a large number of file revisions of varying sizes (1Kb-50Mb) inside the database. Naturally I want to avoid having to allocate whole buffers of 50Mb too often.
4
2620
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 simplest example of my situation (real world would be more complex). Say you have two versions of your application. A release version and a development version. After a month of developing you are ready to release a new version. There have...
10
2988
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? public class MyClass private _variableName as integer public property VariableName as integer
9
1792
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 and backdoors that could provide hours of pleasant diversion writing obfuscated code. Don't write like that on the job. Always write similar, obvious statements to do similar, simple things. Engineers learn their working vocabulary from...
4
1529
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 coordinates to a recording service, such as: /Record.ashx?X=123&Y=456
0
8683
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, 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...
0
8609
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,...
0
9031
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
8901
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
7739
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
6528
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
5862
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
4371
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.