Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it expensive to create objects in .Net?
    text
    copied!<p>I have just refactored a colleague's code that, roughly, looked like this...</p> <pre><code>public class Utility public void AddHistoryEntry(int userID, HistoryType Historytype, int companyID) { // Do something... } public void AddHistoryEntry(int userID, HistoryType historyType, int companyID, string notes) { // Do something... } } </code></pre> <p>To this...</p> <pre><code>public class HistoryEntry { public long UserID { get; private set; } public HistoryType HistoryType { get; private set; } public long CompanyID { get; set; } public string Notes { get; set; } public HistoryEntry(long userID, HistoryType historyType) { this.UserID = userID; this.HistoryType = historyType; } } public class Utility { public void AddHistoryEntry(HistoryEntry entry) { // Do something... } } </code></pre> <p>}</p> <p>Now, this is much better code design and is an Uncle Bob favourite. However, my colleague argues that it is so much more expensive to new-up an object every time we want to call this method.</p> <p>Is he correct?</p> <p><strong>Further Explanation</strong></p> <p>Thanks for all the responses so far. I left out many details in the hope of brevity, but some of them have caused issues with the answers.</p> <ul> <li>Utility class doesn't exist. I just wanted to put the methods in a class for you all to see. In actuality it's in a sensible class.</li> <li>There were, in fact, 5 AddHistoryEntry methods in the original code. All of which took a lot of int parameters. One reason for the refactoring was that <code>AddHistory(0, 1, 45, 3);</code> doesn't really tell you much!</li> <li>AddHistoryEntry is not called from a tight loop, but it is widely used throughout the application.</li> </ul> <p><strong>Corrections</strong></p> <p>I've now updated the code examples as I had made a mistake with some of the parameters.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload