C# outlining. braces or regions - c#

I am maintaining a large asp.net app.
My objective is to identify the lines added in response to particular tickets. While it is possible using our SVN, I want to put it in the code. because these changes would look just odd to a first time reader of the code.
So which outlining method is more suitable for this purpose
{
//response to ticket #xxxxx
...
...
..
}
OR
#region response to ticket xxxxx
..
...
..
#endregion
Or is there any other method more suited for this

Between the two, definitely use comments - they are very flexible. Regions are no good for this sort of thing - what if multiple tickets require code changes which overlap? That's easily explained in a longer comment.
However, I'd argue against putting this kind of info in the comments anyway. No one is actually going to stumble onto code written a year ago and go look up the ticket. Code should be self-explanatory, and in the very odd case where it is not, comments should describe what the code actually does, not why. To address your specific concern of new readers - your colleagues do not need justification for why code is the way it is. They will assume it is that way for a reason, and when making additional changes will always try to maintain the existing functionality. That's basic professional behavior.
Your changeset should be associated with the ticket # in case anyone needs historical information. There's a list of justifications for why things are they way they are stored on each file. That is stored external to your codebase - either in your source control or some other repository.
In my experience, putting ticket numbers in the code is usually a symptom of bad practices. It denotes a deviation from the design instead of fixing the design. A ticket number says "this is how the code was, and this is how it is now." Codebases should not reflect their own history - all that matters is how they work right now.

Response to Option 1: Adding comments for tickets would decrease the readability of code. I think (and this is encouraged at my company) that when you check in a ticket-fix, you should also document that section of code more appropriately, but again, adding a ticket number might just be confusing.
Response to Option 2: Regions are for grouping functions with similar purpose together, so I would not recommend this option either.
Proposed Option: Use the /// standard of commenting functions and add a This is what was changed. element. This way fixes don't disrupt the normal readability, but it's simple to see functions that were involved with tickets. As an added bonus, this mechanism is self-documenting, so these would automatically get put into your generated documents. Note: You might want to check that custom tags are supported.

Try a few and see what your colleagues think.
For anything but the more trivial changes you're most likely to have alterations scattered through your source -- so using SVN blame / annotate is going to be the best bet.

We use JIRA plug-in for SVN to directly see what code files have been modified for a particular ticket.
Regions might become cumbersome as ther could be a case where one line of code is used to fix two tickets. So, pick the first one //ticket #

The first option. "//response to ticket #xxxxx"
The first time you do this...
int defaultVal = 12;
To this...
int defaultVal = 13;
You will hate your life if you decide on a #region paradigm. One/two line code fixes are the norm, and I know from experience that overuse of regions messes with your visual flow by hiding data unnecessarily.
It would be better to do this to hide the items you KNOW are crap.
#region Old Code
//int defaultVal = 12;
#endregion
int defaultVal = 13; //Changed by Ticket:13414
This leave the new code visible by default, and the old code hidden.

Related

hooks in function argument to accommodate future data?

I have to validate data with some stuff which I don't know yet. I want to provide some placeholders in the function arguments in order to support those objects.
Current
Execute(start_time, end_time, DataSet, some_other_data_hook)
At present, I have implemented this hook as a dictionary so that people can put name of the data and then values in the list
Dictionary<name_of_the_data,List<value>> some_other_data_hook;
This sure looks ugly, and I can't think of any better way to solve this problem.
I think the better approach would be to only engineer what you need right now. Even if you "know" and are promised by domain experts and business owners that more rules will be coming, if they're not here now, don't try to set placeholders.
Part of this is for a maintenance aspect, you shouldn't have any unreferenced/unused code in your assembly. It causes problems with maintainability because you're not sure if someone might be using it.
Another aspect is the amount of energy you're going to consume now to define something undefined. Perhaps one future hook is Duration, so you plan for it, only for product owners to decide duration isn't a good idea. In the end, you'll architect something you might not need.
Make sure you methods are easily modified, that they won't cause breaking changes, and then only set up hooks for what needs to be done today.
Think of it as someone building a computer, you wouldn't want them to throw down a whole bunch of extra solder on the motherboard because there might be a time in the future where new devices would be needed. Same thing with code, if you don't have a defined need, right now, don't code it.
"some stuff" is pretty vague. Is it something that would lend itself to passing in an interface? Something like: Execute(start_time, end_time, DataSet, IValidationRule) where IValidationRule is:
public interface IValidationRule
{
bool IsValid(DataSet data);
}
This would provide you with maximum flexibility to plug in different "validation hooks" of wildly varying structure as requirements change. I would probably create my own return value type, like ValidationResult or something along those lines as well. You can code around structure ambiguity if you can enforce a contract on the required behavior.
If you don't have the slightest clue what the structure OR behavior of the "hooks" are going to look like then I'd agree with taylonr. You can't model something that far out in left field.

Is Resharper correct?

I just installed Reshaper 4.5 and it has come up with the following suggestions:
return this.GetRuleViolations().Count() == 0; -- REMOVE this.
new string[] { this.ID.ToString(), this.Registration } -- REMOVE string, MAKE ANONYMOUS TYPE
int i = Method.GetNumber(); -- REPLACE int WITH var
Should I do these?
I think in some cases it is going to make the code less readable but will it improve performance? what are the benefits of making these changes?
Thanks
1) The explicit this pointer is only necessary when the reference would otherwise be ambiguous. Since GetRuleViolations is defined on the type, you most likely do not need this.
Another point here is that if GetRuleViolations return an IEnumerable of something, you will generally be much better off using Any() instead of Count() == 0 as you risk enumerating the entire sequence.
2) String can be inferred from the initialization.
3) Resharper prefers var over specific types.
Apart from the obvious benefit of your little square going green, if you are writing code that will be maintained by someone else later, it makes good sense not to use your personal preference in coding syntax. Resharper is becoming useful in formatting code in a way that is recognisable to a very wide audience.
I belong to the school of thought that says it doesn't matter who's way is right. If we all stick to a pattern, we'll all find it easier to read each others code.
So, in my humble opinion, don't change the default resharper settings. Just accept that if you use the defaults, you make life simple for everyone.
I think the first one is for the purpose, if you want to make "GetRuleViolations()" a static method. Then you have not to remove the "this" identifier.
For the 3rd one - the one that annoys me the most. It provides the reader with less information and i think it's just a matter of showing off a newish feature.
I'd say - use var when you know the return type and use the correct object type when you do not like this:
var reader = new XmlReader(.... // Implicit
XmlReader reader = SomeClass.GetReader() // Explicit when you can't be sure
First one: Resharper is asking about removing this which is just a style thing to me. Nothing more, keeping it won't harm performance in any way. It is just a matter of readability.
For second and third: Resharper normally prefers using var instead of specific data type, that's why the suggestions. I believe it is a matter of personal choice and provides no extra gain other than readability.
The first seems unclear to me. You usually don't have to prefix this. as long as there are no ambiguities, which I cannot tell from this example. Resharper is probably right. The other two won't improve performance, the compiled result will be the same. It's just a matter of taste and, of course, your coding guidelines.
The first one should be configurable. As far as I remember, you can tell ReSharper whether you want to have "this." in front of only fields, methods, both or none.
Using "var" will not change anything in the generated CIL code, so the performance will stay the same. I haven't used ReSharper for some time and I don't know why it promotes anonymous types so aggressively, but one advantage of "var" is that it's more resistant to change.
Meaning if, instead of calling Method.GetNumber(), you called a wrapper, eg. Filter(Method.GetNumber()) in the same line that returns a Nullable, you won't have to update the variable's type.
None of these will have any effect on performance, only on readability.
I find suggestions 1 and 2 to be more readable, and 3 less readable than your original code.
But you don't need to just follow these suggestions if, e.g., you find them less readable or if they violate your company's code style standard. When you put the cursor on the squiggly line, press Alt-Enter to show the list of Contex Actions. One of them will be to to change the severity of the inspection; you can not show it at all or show it as a hint. You can find a complete list of inspections at ReSharper | Options | Code Inspection | Inspection Severity.

a design problem with relatively complicated validations

i have a design problem.. it may seem that i'm giving you too much details, but those are important.
say i have a very large input form, with a complicated input, that requires quiet complicated validations, includes validations of relations between different inputs. being probably a very burdensome form for the user, i'd like to give him the ultimate experience, and i really don't want to be restricted by programing difficulties here.
i thought that idealic every control should have an empty value at start except those of course, that have default values (the problem is DateTimePicker and such are not supporting empty value).
now the user can fill in any of the controls, in any order he would like. once he has leave the control, the program will validate the control's value, and any of the others validations which are concern with that control, and with other controls that are all non-empty (have been filed in already).
if there are any validation errors, the control is painted in some color, and in some side panel it will specify the errors (in a user friendly language of course, rather than exceptions' descriptions).
if there are errors that concerns to more than one control, only the last one that has been changed is painted.
i'd really like to keep to as many OOP concepts here..
so i have my logic classes, that are dealing with calculating the output and stuff like that. obviously those have nothing to do with the gui. now all of these complicated validations should be also in the logic classes' properties etc. but should be used in the gui as well, so i think there should be something like static validate methods (within the logic classes), that will be used in the gui, and in the logic classes them self.
the problem is, a logic class might contain up to 20 maybe 30 fields to validate... will that static method take 30 parameters? is that okay or is there more acceptable solution?
i'm a bit lost for anything beyond that.. but i'm quite sure there already are some conventions for these situations... i know it has something to do with design patterns, but i have no idea what design patterns there are, which are dealing with such cases, and where should i read about them.
my question basically is how do i integrate the validation of the logic classes and the gui, in the neatest way.
if i already in that, i don't want to open a new question for these:
as i mentioned, i need a method here, that get all the input, all the fields of the class, and somehow perform all the validation checks on the non-null values (if there is a validation check that concern to a few parameters, and even one of them is null, the validation shall not be execute). if you have any interesting ideas, i'd like to hear.
another problem i bump into, is the non-emptyale controls, such as DateTimePicker.... it's really ugly that it will have a certain value, while it should not... don't you think?
p.s.
sorry about my english.. i was too tired to write it perfectly..
EDIT1 working with windows
will that static method take 30
parameters?
Yes but what if you pass your object into your static validation method instead of all its properties individually ex.
public static class YourClassRules
{
public List<SomeSortOfValidationItem> Validate(YourClass obj)
{
var results = new List<SomeSortOfValidationItem>()
if (obj.YourProperty.Length >= 200)
{
results.Add(new SormSortOfValidationItem("YourProperty", "Length must be less than...");
}
//etc.
}
}
my question basically is how do i
integrate the validation of the logic
classes and the gui, in the neatest
way.
There are several different frameworks available. It would be helpful to know if your doing windows or web. Then we could make some recomendations.
another problem i bump into, is the
non-emptyale controls, such as
DateTimePicker.
Are you having issues with the controls or the properties that are bound to the controls. I often use DateTime? or Nullable which will allow for a null value.
Hope this helps.
DataAnnotations can be very easy to implement and very effective. Read this answer for an alternative that can extend further. Also, this question has some great gems regarding validation models too.
Spring has a very good DataBinding and validation API. Since there is a Spring.NET version, I'd recommend looking into it.

Duplicate returned by Guid.NewGuid()?

We have an application that generates simulated data for one of our services for testing purposes. Each data item has a unique Guid. However, when we ran a test after some minor code changes to the simulator all of the objects generated by it had the same Guid.
There was a single data object created, then a for loop where the properties of the object were modified, including a new unique Guid, and it was sent to the service via remoting (serializable, not marshal-by-ref, if that's what you're thinking), loop and do it again, etc.
If we put a small Thread.Sleep( ...) inside of the loop, it generated unique id's. I think that is a red-herring though. I created a test app that just created one guid after another and didn't get a single duplicate.
My theory is that the IL was optimized in a way that caused this behavior. But enough about my theories. What do YOU think? I'm open to suggestions and ways to test it.
UPDATE: There seems to be a lot of confusion about my question, so let me clarify. I DON'T think that NewGuid() is broken. Clearly it works. Its FINE! There is a bug somewhere though, that causes NewGuid() to either:
1) be called only once in my loop
2) be called everytime in my loop but assigned only once
3) something else I haven't thought of
This bug can be in my code (MOST likely) or in optimization somewhere.
So to reiterate my question, how should I debug this scenario?
(and thank you for the great discussion, this is really helping me clarify the problem in my mind)
UPDATE # 2: I'd love to post an example that shows the problem, but that's part of my problem. I can't duplicate it outside of the whole suite of applications (client and servers).
Here's a relevant snippet though:
OrderTicket ticket = new OrderTicket(... );
for( int i = 0; i < _numOrders; i++ )
{
ticket.CacheId = Guid.NewGuid();
Submit( ticket ); // note that this simply makes a remoting call
}
Does Submit do an async call, or does the ticket object go into another thread at any stage.
In the code example you are reusing the same object. What if Submit sends the ticket in a background thread after a short delay (and does not take a copy). When you change the CacheId you are actually updating all the pending submits. This also explains why a Thread.Sleep fixes the problem. Try this:
for( int i = 0; i < _numOrders; i++ )
{
OrderTicket ticket = new OrderTicket(... );
ticket.CacheId = Guid.NewGuid();
Submit( ticket ); // note that this simply makes a remoting call
}
If for some reason this is not possible, try this and see if they are still the same:
ticket.CacheId = new Guid("00000000-0000-0000-0000-" +
string.Format("{0:000000000000}", i));
Thousands of developers use Guids in .NET. If Guid.NewGuid() had any tendency at all to get "stuck" on one value, the problem would have been encountered long ago.
The minor code changes are the sure culprit here. The fact that Thread.Sleep (which is less a red herring than a fish rotting in the sun) "fixes" your problem suggests that your properties are being set in some weird way that can't take effect until the loop stops blocking (either by ending or by Thread.Sleep). I'd even be willing to bet that the "minor change" was to reset all the properties from a separate thread.
If you posted some sample code, that would help.
It's a bug in your code. If you've managed to generate multiple guid's it is the most likely explanation. The clue is here in your question: "when we ran a test after some minor code changes to the simulator all of the objects generated by it had the same Guid"
See this article about how a Guid is created.
This artcile came from This answer.
Bottom line if you are creating the GUIDs too quickly and the clock hasn't moved forward that is why you are getting some as the same. However when you put a sleep in it works because the clock has moved.
The code in Submit and OrderTicket would be helpful as well...
You're reusing OrderTicket. I'd suspect that either you (or remoting itself) is batching calls out - probably in respect to # of connections/host limits - and picking up the last value of CacheId when it finally sends them along.
If you debug or Thread.Sleep the app, you're changing the timing so that the remoting call finishes before you assign a new CacheId.
Are you asyncing the remoting call? I'd think a sync call would block - but I'd check with a packet sniffer like Wireshark to be sure. Regardless, just changing to creating a new OrderTicket in each iteration would probably do the trick.
Edit: The question is not about NewGuid being broken...so my previous answer has been removed.
I dont know the details of how GUIDs are generated.. yet. However currently my org. is breeding GUIDs at a rate that would put rabbits to shame. So I can vouch for the fact that GUIDs aren't broken.. yet.
Post the source code if possible.. or a clone repro app. Many times I find the act of creating that clone app to repro the problem shows me the issue.
The other approach would be to comment out "those minor changes". If that fixes the problem, you can then triangularize to find the offending line of code. Eye-ball the minor changes hard... I mean real Hard.
Do let us know how it goes... this sounds interesting.
My gut is telling me something along these lines is going on...
class OrderTicket
{
Guid CacheId {set {_guid = new Guid("00000000-0000-0000-0000-");}
}
Log the value of CacheId into a log file every time its called with a stack trace ... Maybe someone else is setting it.

Resharper region options on Alt+Insert

How can I set Resharper to wrap, say, the generated equality members with regions when selected from the Alt+Insert menu?
Thanks
there is usually a "wrap in regions" option towards the bottom of the dialog box, but not for this one. I would submit that to JetBrains as a request. For the time being, you'll have to select the generated methods and use the ctrl->E,U,5 (surroundwith shortcut) to get the expected result.
it doesn't really answer your question, but I just can't resist to try to convince you NOT to use regions. Why would you want to do it? The obvious disadvantages of regions are:
they don't compile, so you can never know if the name of the region really describes what is inside
regions are often used to hide rubbish code. The thinking here is: you can't see the rubbish bits, so it is as if they didn't exist. But guess what, they still exist...
regions are just textual, they don't have any semantic meaning. That means that the code inside the region can change the state of another region - which doesn't help to figure out what is happening in the class at all
if you structure your code correctly, it should be obvious what it is doing anyway
I believe using regions makes sense pretty much only for automatically generated parts, e.g. WinForms designer stuff. In most (all?) other cases it is much better to refactor the code, extract some extra classes or methods, etc. to make it clear.
You can highlight the text you are interested in wrapping and use the Visual Studio key shortcut of
CTRL + k, s
selecting #region from the menu.

Categories

Resources