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)
Related
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);
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.
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
There are times I instantiate a new object within a method call for sake of streamlining code instead of assigning the new object to a variable. What drawbacks exist in doing one or the other?
T myobj = new T();
elements.Add(myobj);
--vs--
elements.Add(new T());
Need a reference later
As adaam mentioned in the comments, if you need to keep a reference to an object because you'll be using it, then it's better to do it this way.
T myobj = new T();
elements.Add(myobj);
T.DoStuff(); //this might need to happen further down in the code, so keeping the reference is handy. Otherwise we'd have to dig it out of the elements. And you might be thinking "well, I don't need to reference it later in the code." But what if you're refactoring the code and it requires some modification? Now you'll need to change it, rather than having done it with a separate declaration in the first place.
Debugging
A common situation is when you're stepping through code with the debugger. It's difficult to see properties of an object that was created in this manner.
elements.Add(new T());
When given its own reference, you can easily use your IDE's debugging tools to check the values if the code is written like this:
T myobj = new T();
elements.Add(myobj);
Readability
Another reason to choose one over the other would be readability. That one is opinion based, but you should ask the team you're working with which is more readable in order to determine which practice to follow. Asking everyone on Stack Overflow which reads better is off topic.
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 6 years ago.
Improve this question
I'm developing software in C# and I remember that I read an article with the following statement:
Design the methods of a class like this:
use a void method with argument(s) in order to change state of the class instance. method will do some changes on the data of the class
use return value with a method without any arguments in order to retrieve data from the class
I can't find the article anymore and I'm wondering about the benefits and drawbacks of such a convention in order to improve the quality and maintainability of the code I'm writing.
My question is: do you know any references/articles for this question? Does it make sense to follow these statements?
C# has properties which I think makes these suggestions less practical. The big point to take away is that data inside a class should be encapsulated (the outside world cannot access it directly) and abstracted (the details are hidden). This is one of the primary purposes of a class. For this reason I think this advice would make more sense for a language like C++ that doesn't have properties.
One of the problems though is that people would write a class with private fields then have to write a getter method and a setter method for each private field and this results in redundant boiler plate code. Properties help streamline this strategy while still maintaining encapsulation and abstraction. For example,
UserInfo user = new UserInfo();
user.Username = "foo";
Console.WriteLine(user.Password);
In the above example I have set the username to foo and retreived the password for the user. Exactly HOW I set and retreived the information is hidden. It may be saved in an .xml file right now but later I decide to change to saving it in a database or directly in memory. The outside world that uses this classes is never the wiser. This is one of the many beauties of OOP.
The two bullets in your question can respond to a getter and a setter of a property. If I want to retrieve data from my class without any arguments it makes more sense to have a property. Likewise if I want to change the state of my object I can use a setter property. I can perform validation on the input, make it thread-safe, add logging, everything I could do with a method that takes a single argument.
I suppose the bullet points are referring to Command Query Responsibility Separation. In practice you could still need to pass some argument to a return method in order to filter the results for instance. Using voids to change the state is sensible, and also making your return methods so that they don't change the state is good too, but really the number of arguments you pass in is not decided by whether you have a getter or setter method. It is really a factor of what a method needs to know to get it's job done.
The amount of arguments that you pass in should be kept to a minimum however. If you have more than one argument you should really consider if your method is doing more than one thing. I suppose the message is, "Have your methods do one thing and do it well". You can get loads of information about this from Uncle Bob, Bob Martin's Clean Coders series is a great source of information on this subject.
Having a get method that returns a value and doesn't take any parameters makes it very clear what your method is doing.
GetFirstName() is clearer about what it's doing than GetName(bool first) or GetFirstName(User user).
Clarity is key. The method signature may seem like it's fairly clear, but when you read GetName(false) in the code somewhere then it's going to cause some confusion.
These types of getter methods are also not really my standard in C# where I am more likely to use a property for a getter of that nature.
When it comes to void methods with arguments, then this mainly comes into play for setters where you are setting the state of something in the object. Again, easily handled with properties in C#.
Most of the time these guidelines are there to help keep your code testable.
Methods that have fewer parameters are more easily tested -- assuming you are injecting dependencies into the method signature and not creating new objects in the method itself, which can be difficult to mock and test.
Think of how many test cases you may need to cover if you have a method that accepts 5 parameters.
In the end, these are general guidelines that are good for testability and clarity of your code, but there are certainly times when you will find that it doesn't make sense to follow these guidelines.
As with any coding, just be aware of what you are doing and why you are doing it.
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();
}