Do I need Open and Close methods with a IDisposable class? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm working on a simple repository class on top of a ADO.NET SQL connection. The class is sealed and implements the IDisposable pattern.
I intended to keep it simple so I open the SQL connection in the constructor and closed through the Dispose() method so it can be used with the using statment.
using (var r = new MyRepository(connectionString))
{
...
}
I originally had a pair of Open/Close method for this class but I found it makes the class much harder to implement and also more confusing to use.
Do you typically have Open/Close methods for your repository class? If so why?

MSDN Dispose Pattern guideline says:
CONSIDER providing method Close(), in addition to the Dispose(), if
close is standard terminology in the area. When doing so, it is
important that you make the Close implementation identical to Dispose
and consider implementing the IDisposable.Dispose method explicitly
So, taking into account that open-close terminology is often used in database interactions, your idea to have them is good and quite viable.
But, if their implementation and use makes your classes much more complex to no or minimal advantages then do not create them. In the end you always know your system and requirements better, so you should base your decisions on your concrete situation, not on abstract guidelines and principles.
P.S.: Whether you have these methods or not, your system should open connections for smallest possible amount of time and close them as soon as they are no longer needed. And it is often difficult to accomplish when you have to put some special disposal code in the end of each use.

I suggest not implementing IDisposable directly on your repository class.
Instead, obtain and release resources as necessary within each method of the repository.
public class MyRepostory : IRepository
{
public IEnumerable<Foo> GetFoos()
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
// ... get the data, etc. ...
return foos;
}
}
}

Related

Is it ok/necessary to unsubscribe from Events outside dispose method? Possibly wrong code design [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
I'm in a situation where I have to new up a ViewModel that has an event and based on the view chosen by the user I might need to swap back and forth between this one and other ViewModels with the same interface, every time they have to get the updated data.
These ViewModel contains a list of ViewModels that I need to display.
Is it ok to do detach and attach to the event this way outside the usual Dispose method?
if (_animalsListVm is not null)
{
_animalsListVm.MyEvent -= Handle_MyEvent;
}
_animalsListVm = MakeListViewModel();
_animalsListVm.MyEvent += Handle_MyEvent;
await _animalsListVm.InitializeAsync();
Granted this code might be messy, I'm using Blazor and I was trying to find an alternative to have enums or booleans to show a component, so I decided to switch view based on the concrete type of the current ViewModel.
Attaching and detaching events outside dispose methods is generally fine.
In some cases a pattern like this might be preferable:
public IDisposable RegisterForEvent(Action<EventArguments> eventHandler);
This follows the typical dispose pattern. This pattern might be preferable if you need to do some work when registering or unregistering events. You could do the same with a regular event, but I would typically not expect an event registration to do any time consuming work.
I am however not a fan of initialization methods. While they can be hard to avoid, I prefer objects that are completely constructed when the constructor returns, perhaps something like:
_animalsListVm?.Dispose();
_animalsListVm = await MakeListViewModel(Handle_MyEvent);

C# Changing an Existing class - Best Practice Open/Closed Principle [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to figure out the best way to change an existing class.
So the class is called ExcelReport and it has one method Create(data,headings).
This is live and used in many places.
Now recently I want to change the method so I can format columns in excel.
Create(data,headings,columnformats)
So as not to upset my existing programs the best I can come up with is to add another method
Create2(data,headings,columnformats) to the class.
o.k I got a lot of suggestions saying I should modify the existing class with a overloaded method, which I did.
But does this not break the Open/Close Principle as my existing class was in production. Should I have created a new class ExcelReport2(and Interface) with the new improved method and passed this into my new program using dependency injection ?
Regards,
Niall
As the comments suggest the best approach is likely to use an overload method. In most cases I would approach this with the idea of implementing the overload method as a pass-through if possible.
Create(data, headings, columnformats)
would transform the data using the column formats and call:
Create(data,headings)
at the end of the method. This means in all cases of the Create method call the version with 2 parameters while the cases that need 3 are handled as a pass-through. This keeps to a rule of least disturbance and avoids confusion if the code needs to be maintained in the future since you are not duplicating the logic in:
Create(data,headings)
Edit: One important consideration with this approach is that if columnformats does not modify the data or headings you may not be able to practically use this as outlined. In that case you would use Create(data, headings, columnformats) as the base method with Create(data,headings) acting as a pass-through to that function. In this case Create(data,headings) would set a default value that is then passed to Create(data, headings, columnformats)

organization of helper methods [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have some methods in a class which get called by only one method in the same class. Where is the best practice to put such methods? Private at the end of the class?
Comming from gcc's C implementation I would define those helper methods in the method they are needed for, but that doesn't seem to work in C#.
I often use Private methods at the end of the class, as you mention. But if those helper methods are closely related to the calling method, you could place them right after the calling method and surround it all in a #region to visually group them, as well as allow for expanding/collapsing as a unit in Visual Studio.
#region Range Checking
public void CheckRange(int lowerBound, int upperBound)
{
CheckRangeValue(lowerBound);
CheckRangeValue(upperBound);
}
private void CheckRangeValue(int value)
{
//...
}
#endregion
In Bob Martin's excellent book Clean Code, there is a chapter on vertical formatting, with a section titled "The Newspaper Metaphor". I'll post an excerpt (emphasis mine):
Think of a well-written newspaper article. You read it vertically. At the top you expect a headline that will tell you what the story is about and allows you to decide whether it is something you want to read. The first paragraph gives you a synopsis of the whole story, hiding all the details while giving you the broad-brush concepts. As you continue downward, the details increase until you have all the dates, names, quotes, claims, and other
minutia.
We would like a source file to be like a newspaper article. The name should be simple but explanatory. The name, by itself, should be sufficient to tell us whether we are in the right module or not. The topmost parts of the source file should provide the high-level concepts and algorithms.
Detail should increase as we move downward, until at the end we find the lowest level functions and details in the source file.
And a few pages ahead:
If one function calls another, they should be vertically close,
and the caller should be above the callee, if at all possible. This gives the program a natural flow. If the convention is followed reliably, readers will be able to trust that function definitions will follow shortly after their use.
(...) [T]he topmost function calls those below it and (...) they in turn
call those below them. This makes it easy to find the called functions and greatly enhances the readability of the whole module.
Besides this specific topic, the book contains a ton of other very, very useful well-funded information about these sometimes neglected aspects of code construction.

How is "using" statement supposed to work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to take advantage of the using statement in the following code:
Uri uri = new Uri("http://localhost:50222/odata");
var container = new CourseServiceRef.Container(uri);
CourseServiceRef.NotNeeded newTempUser = new CourseServiceRef.NotNeeded()
{
Email = model.UserName,
Username1 = model.UserName
};
container.AddToNotNeededs(newTempUser);
container.SaveChanges();
However this doesn't compile. Why?
using statement - not to be mingled with using directive - is meant for objects that implement the IDisposable interface so that they're disposed of automatically at the end of the code block:
using (var toto = new MyDisposableClass())
{
// do stuff
}
If any of your classes do implement this interface (or inherit from something that does), you may use the above syntax to ensure call to Dispose() method. You cannot use using blocks for objects that does not implement this interface, it simply won't compile.
Essentially, this will be doing the same as the following:
var toto = new MyDisposableClass()
try
{
// do stuff
}
finally
{
if (toto != null) ((IDisposable)toto).Dispose();
}
The only difference here would be that in the first scenario, toto's scope dies at the end of the using block.
The purpose of "using" is to ensure Dispose() is called on an object that implements IDisposable. Therefore, the best way to use using keyword in your code is, like in any other code, on objects that implement IDisposable. This could be, for example, your "newTempUser" or your "container". Since we do not have access to their definitions, only you can answer this question.
There aren't really good and bad uses of using. Either you use it or you don't. If you don't use it when instantiating a class implementing IDisposable then you've likely made a mistake (unless you have some good reason for calling Dispose yourself elsewhere which is a very small percent of use cases).
If you fail to use it then the point when the resource is disposed of is less predictable and it will likely have negative effects on your applications performance. There aren't different ways of using it, there is only one;
using (ClassImplementigIDisposable instance = new ClassImplementigIDisposable())
{
// code that uses instance
// at the end of this block `Dispose` will be called on instance
}

Using related functions in one class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a class with two related functions (methods):
public class class1
{
public void SubscribeToListOfEvents()
{
// ....
}
public void UnSubscribeFromListOfEvents()
{
// ....
}
}
What's the best practice to use related functions in one class ?
Do you know of any implementations of related functions as one function ? Are they good ? In what situations are they good ? If so, can hyou give me an example?
Any available options of code above will be appreciated.
If the functions belong to the class, logically, then they are fine that way.
A class should be cohesive and methods that do an operation normally should have the mirror operation defined as well (Subscribe/Unsubscribe, Add/Remove etc...).
You have named them well, as they are very descriptive of what they do - how would you name a merged one? It is better to leave them separate, as this way they are self documenting and will not confuse users of the class.
With the example you provided, they are related - but only because they may work with the same set of data or objects.
Personally i would NEVER merge these into a single function. While it may be more typing, it is easier both to read and to maintain to keep them separate. When either of those two functions are being called it is obvious what is going to happen - if you were to merge them then it becomes not so obvious. This is a simple example though - if you were to merge two functions that were more complicated then things could get very murky, and you could end up having unintended side effects from calling the merged function.
Remember KISS - Keep It Simple, Stupid :) For every function, try and follow SRP - Single Responsibility Principle. While Wikipedia talks about SRP at the class/object level, there is no reason to not also apply it at the function level where practicable.
dont merge them, make an interface that will force you implement both methods
interface ISubscriber
{
void Subscribe();
void Unsubscribe();
}

Categories

Resources