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.
Related
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)
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 3 years ago.
Improve this question
Does anyone know how to convert the C# getter and setter to a java-like getter and setter pattern using the Rider IDE?
Convert this:
public Transform List
{
get { return list; }
set { list = value; }
}
to this
public Transform GetList() { return this.list; }
public SomeClass SetList(Transform list) { this.list = list; return SomeClass; }
This would be usedful for chaining setters in a fluent builder pattern.
A distinct non answer: stop wasting "double" your time!
C# isn't Java. Fighting a tool to fight the native idiomatic constructs of your target language, that is likely double pointless.
Source code is written to be read by humans. And good source code never surprises its readers. An experienced c# programmer will look at your Java like getters and setters and can only wonder: "why is he polluting these classes with those strange methods, instead of using c# property support".
Beyond that, you might want to read https://en.m.wikipedia.org/wiki/Uniform_access_principle to understand why the c# properties are actually a better approach than Java fields with getter/setter pairs!
Or as they said 2 thousand years ago: when you come to Rome, do like the Romans do! If you don't want to do like the Romans do, stay away from Rome, or c# in your specific case.
OP is probably coming from the java world. In the Menu(Intellij) Java IDE ->Code->Generate
In the generate menu, "Getter and Setter" is the 4th Option.
In the C# world(Rider), properties are used to expose selected fields.
Jetbrains Recommends generating Properties rather than the Java getter-setter way.
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.
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();
}