is it any point to have readonly field in this code

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

In the class DocumentManager below is the generic type Queue<Document> defined as readonly.
As far as I understand this readonly it's not any point to have this definition of the generic type Queue<Document> here.
Do you agree with me ?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;


class Document
{
private string title;
private string contents;

public Document(string title, string contents)
{
this.title = title;
this.contents = contents;
}

public string Contents
{
get { return contents; }
}

public string Title
{
get { return title; }
}
}

class DocumentManager
{
private readonly Queue<Document> documentQueue = new Queue<Document>();

public void AddDocument(Document doc)
{
lock (this)
{
documentQueue.Enqueue(doc);
}
}

public Document GetDocument()
{
Document doc = null;
lock(this)
{
doc = documentQueue.Dequeue();
}
return doc;
}

public bool IsDocumnetAvailable
{
get { return documentQueue.Count > 0; }
}
}


class ProcessDocuments
{
private DocumentManager documentManager;

protected ProcessDocuments(DocumentManager dm)
{
documentManager = dm;
}

public static void Start(DocumentManager dm)
{
ProcessDocuments pd = new ProcessDocuments(dm);
new Thread(pd.Run).Start();
}

protected void Run()
{
while (true)
{
if (documentManager.IsDocumnetAvailable)
Console.WriteLine("processing document {0}", documentManager.GetDocument().Title);
Thread.Sleep(new Random().Next(120));
}
}
}

class Program
{
static void Main(string[] args)
{
DocumentManager dm = new DocumentManager();
ProcessDocuments.Start(dm);

for (int i = 0; i < 2000; i++)
{
Document doc = new Document("Doc " + i.ToString(), "content");
dm.AddDocument(doc);
Console.WriteLine("added document {0}", doc.Title);
Thread.Sleep(new Random().Next(120));
}
}
}

//Tony
 
No. It's fine and useful to declare variables as "readonly" if they in
fact should be read-only.

I can see where he's coming from, though. To me "readonly" suggests that
NOTHING about the variable will ever change (although I'm aware that that's
not what the readonly keyword really means). The fact that items are being
enqueued and dequeued suggests that some sort of change is happening and
therefore it doesn't "feel" readonly.

Tony, in this case readonly simply means that you are never allowed to set
the variable documentQueue to a different instance of Queue<Document> than
the one you originally assigned to it. You can still use and make changes to
all of the variables properties and methods. Basically "readonly" really
means "never reassign."
 
Back
Top