Note that there are some explanatory texts on larger screens.

plurals
  1. POBest practice for method chaining ("return this")
    primarykey
    data
    text
    <p>I have an abstract class called <code>DatabaseRow</code> that, after being derived and constructed, is mainly loaded from a <code>Load(object id)</code> method.</p> <p>I have lots of code that creates a new instance of the class, loads it from an ID, then returns the class. I'd like to simplify this code into one line of code (just to be neat, there are plenty of classes that will just have lists of properties that return these Loaded instances).</p> <p>There are two ways I can think of doing it, but neither seem 'right' to me.</p> <p><strong>1.</strong> I could <code>return this;</code> at the end of my <code>Load</code> method and use <code>return new Derived().Load(id);</code></p> <p><strong>2.</strong> I could create a generic method to return a loaded method.</p> <pre><code>public static T LoadRow&lt;T&gt;(object id) where T : DatabaseRow, new() { T row = new T(); row.Load(id); return row; } </code></pre> <p>I've seen some other code that uses the same method as number <strong>1</strong>, but I've never seen any experienced developer recommend it, nor have I came across any methods in the .NET framework that do the same thing, so maybe this isn't best practice?</p> <p>Does anybody know of any other solutions that could be better than both of these?</p> <p><strong>Solution:</strong></p> <p>After reading SirViver's answer and comment, I realised that all the properties being returned need to be cached anyway. The solution was sightly different, but similar to option <strong>2</strong> (that I wouldn't expect anyone to come up with this answer as I didn't explain this part of the design)</p> <p>All these instances will be loaded from a value retrieved from another column in the database (database relationships if you like). Instead of trying to load the new instance from this value, I made a method to load the instance from the column name and cache the loaded value in a Dictionary. This works well as this is one of the primary functions of the <code>DatabaseRow</code> class.</p> <pre><code> private Dictionary&lt;string, DatabaseRow&gt; linkedRows; protected T GetLinkedRow&lt;T&gt;(string key) where T : DatabaseRow, new() { if (linkedRows.ContainsKey(key)) return (T)linkedRows[key]; else { T row = new T(); row.Load(this[key]); linkedRows.Add(key, row); return row; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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