Using related functions in one 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 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();
}

Related

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.

Do I need Open and Close methods with a IDisposable 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 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;
}
}
}

Way of coding in C# [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 years ago.
Improve this question
Sometimes I have to write big code in a class, so what I do is something like this,
Class ABC //it's a web service class
{
Public void Method-1() //used "-" for easy to read
{
//DoSomething and get something from database
Method-2(pass parameters that i got from database);
}
Public void Method-2(parameters)
{
DoSomething again and get data from another database. and some other source
do some processing by calling web services (just as example)
Method-3(parameter);
}
Public void Method-3(parameters)
{
DoSomething again and get data from another database. and some other source
do some processing by calling web services (just as example)
Method-4(parameter);
}
// and it keeps going
}
Another way
Class ABC //it's a web service class
{
Public void Method-1() //used "-" for easy to read
{
Method-2();
Method-3();
Method-4();
// so on....
}
}
Is this the right way of doing it and if not then what would be best way of doing it ?
Edit
#Sayse I am trying to get information from different sources and trying to build a big XML file which made me get use 4, 5 foreach loops to get data from sql etc.. so using nested methods
Both ways are good in different cases. If you have single functionalities, you should keep them separate. Second approach - calling method from method should be used when one method is part of 'outer' functionality.
Examples:
repairVehicles() {
repairCar();
repairBike();
repairTrain();
}
... but:
repairCar() {
...
repairEngine();
...
}
repairEngine() {
...
takeEngineOut();
....
}
takeEngineOut() {
...
unscrewBolts();
...
}
There cannot be a straight forward answer to your question.
First of all you should note that one method should perform one functionality. If it is true, then you can call it either way depending on your requirement.
Example:
If you have a base method takes a mathematical expression as input. And that expression contains Add, Subtract, Multiply and divide then you will call it the first way.
public int GetExpressionResult(string someExpression)
{
Divide();
Multiply();
Addition();
Subtraction();
return result;
}
in the above example the result is dependant on all four methods, so it is fine to call it like this.
now in your example 2 if the methods are totally independant of each other than you should the way you have done.
Conclusion:
There is no hard and fast rule for this, You should call the way your application demands.
As far as I understood your question, what you are describing is basically a pipeline. There is a very interesting blog (in two parts here and here) about how to elegantly tackle situations as yours.
At the end, it depends on what you're trying to do and applies, IMHO, not only to C#.
Your first option should be applied when method<i+1> is a helper for method<i>, or is included in it. I can't find an example for such a scenario.
Your second example, which is far more readable to me, should be applied when you have a long sequence of actions that need to take place. Let say:
void mainMethod()
{
ConnectToDB(); //if can't connect, log it and exit
GetUserInfo(...); //if null, log it and exit
ShowUserInfo(...);
}
In the example above, it's hard (for me) to imagine a division to methods like in your first scenario.

C# Where should my collection of data objects be instantiated? [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 years ago.
Improve this question
I am using C#, but I think this applies to most programming languages.
Philosophical question here. When I write windows form applications, I try very hard to keep UI and data structures separate. But I wonder if I am doing it the best way, OO-wise.
For instance, if I have MyClass, and my application requires many of them, perhaps stored in a List, should I make that List a member of the Form1 (with Form1 being the "main" form)? If not, where should I instantiate the List? Any opinion on public vs. private declaration, or is it just a matter of whatever is needed?
public partial class Form1 : Form
{
private List<MyClass> myClassList; // good idea? Bad idea?
public Form1 ()
{
InitializeComponent();
}
}
It depends. If your list stores things related to the UI, like form controls, then yes, that could probably be the best place for it.
Otherwise, it would depend on the context - which we can't see whole here.
Edit: at some point, your form will have to hold a reference to an instance of one of your non UI classes. I think (though again, without more context, can't be 100% sure) that one of these objects should be the one keeping the list.
Try to keep your logic as independent of the form as possible - i.e.: manipulate that list as little as you can from the form, and as much as you can from the non UI classes. You may end up seeing that in the end you don't need the form to hold that reference to the list at all.
Edit again: if I have a system for a pet shop, I might have a Kennel class and a generic list holding items of the Pup class. The kennel instance would hold the list of puppies, not the UI. I hope this small example illustrates my point more clearly.
It's all about choosing the scope of the data and what kinds of operations you are going to be performing on them on the regular basis. For example, you may want other parts of the program to know about that list, but they might not have to know that Form1 even exists. Things can also get messy when you start performing operations on that list in a way that doesn't actually concern the Form1 class.
Whenever you make a new variable, ask yourself some questions. Do other classes need to know about this variable? Do I need to perform operations on this variable that are independent of the form? Does this variable truly belong to the form?
Asking yourself these types of questions can save you time in the future and make your program more readable and easier to maintain.
An internal representation of a list of objects isn't bad (though you should have a good reason to waste the extra memory if you only need it to draw a form), but the list (if it is required to meaningfully render the form) should be an argument in the constructor.

Categories

Resources