Solved

declare objects Globally  in a class and dissociate it

Posted on 2007-11-20
14
242 Views
Last Modified: 2013-12-17
I am declaring object instance = null; at top of the class  and setting it to NEW in function and  Dissociate object used to NULL in Finally Block... Is this right way or is there better apporach
 public class CHistory
    {
        CEmployee ObjEmp = null; ------ I have declared it  here On the top of the class
           {
        }
        public int GetHistory(int EmpID)
        {
           
            try
            {
             
              ObjEmp = new CEmployee();
              ObjEmp.GetHistory(EmpID);
              }
            catch (Exception ex)
            {
                throw (ex);
            }
           finally
               {
                   ObjEmp = null';
        }
0
Comment
Question by:dotnet0824
  • 6
  • 5
  • 3
14 Comments
 
LVL 11

Expert Comment

by:Babycorn-Starfish
ID: 20319430
do you use that object globally?it's not very OOP.

If you weren't it would make sense to only construct it within your method/property and let it be destroyed when it goes out of scope.
0
 
LVL 11

Expert Comment

by:Babycorn-Starfish
ID: 20319440
Basically you

1)instantiate it,

2)Use it,

3) Set it to null,

So it never gets used outside of your method so it would be best to declare it in your method.
0
 

Author Comment

by:dotnet0824
ID: 20319441
can it be more clear.... I couldnt get you... As per the code given can you modify it and put how it would be the best way to handle it
0
 
LVL 7

Expert Comment

by:multithreading
ID: 20319447
First, eliminate the "finally". This is not needed at all in this case, and does nothing but slow down your system.
Second, unless you were trying to hide information about your calling sequence for obfuscating your internal architecture in a highly secure environment, your try catch is buying you nothing. (Even if you were doing this, the try catch isn't buying enough, as there is no handling of the exception in your catch.)
Third, you never actually return the history from the method.
Fourth, you don't keep the employee record that you use in GetHistory, so there is no need for a member variable.

Those changes get to here:

public class CHistory
{
  public int GetHistory(int empId)
  {
     return new CEmployee().GetHistory(empID);
  }
}

With the extranious stuff removed from your class, it appears your class shouldn't exist at all. GetHistory already exists in your CEmployee class. CHistory is adding nothing.
0
 

Author Comment

by:dotnet0824
ID: 20319452
What could be a professional way .. can the code be posted doing all those
1)instantiate it,

2)Use it,

3) Set it to null,   (IS THERE ADVANTAGE IN USING THIS
0
 
LVL 7

Expert Comment

by:multithreading
ID: 20319517
You -would- want to set the variable to null as you had originally constructed the class, but that is because you had hoisted the reference too high. It was a member variable that was being used as a temporary variable in your method.

Had the variable been used only within the method, there would be no need to set it to null, as the object can be collected once the reference(s) go(es) out of scope. Indeed (as you see above) you often don't even need a variable at all. You can just instantiate the object and use it with no reference.
0
 

Author Comment

by:dotnet0824
ID: 20319887
What is the advantage of this (I understand what u said dont need variable at all)
 (as you see above) you often don't even need a variable at all. You can just instantiate the object and use it with no reference.... (Is there any performance improvement in this) AS I want to implement the same everywhere in my classes calling directly like this

return  New Object.Method(Parameters)

Can the Advantage be explained clearly
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 11

Expert Comment

by:Babycorn-Starfish
ID: 20319941
If you look at this:

return new CEmployee().GetHistory(empID);

He's created a new CEmployee object and used it without having to first create a reference variable to refer to it.
for example he could have done this:

CEmployee c = new CEmployee();
int history = c.GetHistory(empID);
return history;

so this removed the need for c and the seperate line of code call GetHistory by doing it all on an anonymous (no named variable for it) object instance. It saves the need for the memory for the named variable.
The problem with this style however is if you go to deep the code can often be unreadable.

0
 
LVL 7

Expert Comment

by:multithreading
ID: 20319974
The purpose of the example is not so much to show how you should -always- program. It is intended to amplify the fact that you don't need to create a reference solely for the purpose of setting it to null after the object is used.

The advantage of concise writing has little to do with performance. In this case, the c# compiler will create a (hidden) reference variable anyway. The resulting MSIL (and machine) code is the same as if you had used a variable. The "advantage" (to the extent that there is one) is strictly for human readers of your code:  A variable is one more detail for a (human) reader to track. If the variable is never used again, why create it?
0
 

Author Comment

by:dotnet0824
ID: 20320476
The other advantage i feel that no Memory is allocated to variable isnt it
is that not an advantage again
0
 
LVL 7

Accepted Solution

by:
multithreading earned 250 total points
ID: 20320601
The MSIL emitted by the compiler will contain a reference variable. This is not a performance issue.

If you want to improve performance, a more meaningful thing is to eliminate the need for a reference to the object when the method is inherintly static. Taking your class one more step results in this:

public static class CHistory
{
  public static int GetHistory(int empId)
  {
     return new CEmployee().GetHistory(empID);
  }
}

Note that GetHistory is now static. This eliminates the need push the reference to a CHistory object onto the stack on each call, but much more importantly, it eliminates the need to even create a CHistory instance.

Looking more closely at heap allocations, you could eliminate the need for the constant creation and destruction of CEmployee instances (which -may- be better, depending on other things).

public class CHistory
{
  private static CEmployee employeeSingleton = new CEmployee();

  public static int GetHistory(int empId)
  {
     return employeeSingleton.GetHistory(empID);
  }
}

This might seem like where you started, but in this approach the CEmployee instance is kept around between calls, which gives it a reason to exist at the class level.

From here, you can go in many directions. You could instantiate CEmployee only on first use. You could keep a weak reference to it if it is used in bursts and then not used for hours. etc. etc., but the first question you should be asking yourself is "does this CHistory class even have a reason to exist".

This CHistory class has no meaningful state. Its only method is a "helper" method which is identical to a method on the underllying class. Unless there is some special reason that you want to hide the CEmployee class, CHistory has no reason to exist.
0
 
LVL 7

Expert Comment

by:multithreading
ID: 20320867
On the other hand, if the CEmployee object has some kind of expensive -pooled- resource, like a database connection, then it is best not to go too far. In that case the static approach would be optimizing heap at the expense of a more expensive resource.
0
 

Author Comment

by:dotnet0824
ID: 20322061
Hi Babycorn-Starfish: As per ur posting earlier.. I do agree its unnecessary to create a variable for the class in the current context ..
As per ur statement "instance. It saves the need for the memory for the named variable."

Thats what I also though as BobyCorn Said.. Dont u agree upon this  MultiThreading...............

If  does it mean  if  a Class A Uses instance of ClassB, Class C then make Class B and Class C static so that there is no need of reference in Class A ..... Can we follow that approach
0
 
LVL 7

Expert Comment

by:multithreading
ID: 20322520
I'm in the odd position of trying to convince you that my code snippet isn't as useful as you think it is. Not knowing how good the optimizer is when it comes time to actually produce the machine code, I'll stipulate that not using the local variable is more "efficient", in addition to being easier to read. It is possible that the optimizer doesn't eliminate the unnecessary local variable, but that wasn't the original point.

With regard to your classes A,B, and C, yes, if B and C are static, then A needs no reference, however, if C holds a database connection, then you have minimized heap allocations while maximizing the hold on the database resource, unless your GetHistory method in your Employee class opens and closes the database each time. (And if it does work that way, class B is of questionable value, unless it is there strictly as some kind of abstraction layer the details of which you have omitted from your question.) If you are using B as an intermediate layer, it is for flexibility and maintainability, not for performance.

The best advice I can give you is this: Forget, completely, absolutely, and aggressively, about performance. Instead of asking the question "which way is faster", ask "which way makes more sense" and "which one is easer for someone else to read and understand". Get a good book on object oriented design.

Performance is an issue, but right now it is just confusing you, clouding your thinking. It isn't that performance doesn't matter or that "machines are so fast now that you can waste resources". I say "don't worry about it" because performance is harder than this, and you have other more important things to learn first.

The best approach from a performance standpoint is subtle. Performance is rarely optimized by these kind of small issues. Performance programming is an art unto itself, and comes after you have a thorough understanding of the basics, not before. Forget everything anyone has told you about performance (including things like "foreach is slower than for" and all the other rot that you have ever been told). 90% of what you have heard about performance is absolute rubbish. Almost all of it has counter examples, and most of it has an almost immeasurable true impact. If you follow the various dictums, instead of writing quality code, you will be focused on irrelevant nonsense that mostly isn't even true. (There is often a microscopic grain of truth, but usually from a myopic context that is irrelevant to production code, sometime producing the opposite effect in real systems.)

The question you need to be asking is not whether you can save a local variable in physical memory. The question for that section of code is "which one is easier to read". The question regarding your classes is not "which one is most efficient". It should be "which one makes the most sense". What is class B doing for you? What abstraction is it providing? If your code is logical, it will naturally be reasonably efficient for a first cut, and if you need more performance than that, for now, hire an expert. Later, you can learn the performance part.

Software is poetry. Rather than picking words with fewer letters to save ink, pick words because they say something.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now