Abstracting multiple C# classes - c#

I have to deal with a project where someone else has copied and pasted the same class some 12 times, added some customization, but mainly, the structure of the classes are really similar because they were copied from each other.
I am itching to refactor the code because I can't stand looking at the code base.
Is there a tool that can automate some of this headache, that is, extract identical properties and methods into a parent class and make the other classes inherit from it?

Similar to arivman, give Resharper a shot. 30 day free trial, life-time license available per person (means can take it back home, and to other jobs if they'll allow it).

I don't know any free solution (other than doing it yourself), but you could give NET Refractor from KnowDotNet a shot. They even have a 30 day free trial!

I'd also recommend you to use a tool like Clone Detective before you opt for the Natural selection, there might be more hidden duplication.
Resharper squigglies will definitely give you some hints about code smells and keyboard combos to fix then in a jiffy.
You could also potentially use some bits and pieces from here and i personally find branching and tagging to be quite effective in situations like these. Any analytical due diligence prior to delving in the code i think goes a long way too.

Here we use simian to find the duplicate code. But again you still need manual intervention 2 remove or 2 update it.

Related

Automating complex refactoring tasks

I have the situation that the same repeating refactoring tasks have to be done for a huge number of methods in my code.
For example imagine a interface with 100 methods, each of them has one or more parameters as well as a return value. For each of these methods I need to jump to the implementation change the return type and add a line of code which converts the old return value to its new type for callers of the interface method.
Is there any way to quickly automate such refactorings?
I even thought to write a custom script to do it, but writing a intelligent script would approximately take longer than doing it maually.
A tool supporting such task can save a lot of time.
It's a good question, but in the time it took since you posted it (not to mention the time you spent searching for an answer before posting), you could have completed the changes manually.
I know, I know, it's utterly unsatisfying, but if you think of it as a form of mediation, and only do this once a year, it's not that bad.
If your problem is one interface with 100 methods, then I agree with another poster: just doing it may seem painful but it is limited in effort and you can be done really soon.
If you have this problem repeatedly, or you have very large code base (many, many interfaces for which you want to perform this task), then what you need is a tool for implementing automated change: a program transformation engine. Such a tool provides the ability to parse source code, build a program representation (an abstract syntax tree), and enables one to apply "scripted" operations on the tree either through procedural interfaces and/or through source-to-source transformation patterns.
OUr DMS Software Reengineering Toolkit is such a program transformation system. It has a C# Front End to enable its application to C# code. Configuring such a tool for a complex task is not a matter of hours, so it is not useful for "small scale" changes. For large scale changes, such tools can make it possible to do things simply not practical by hand.
Resharper and CodeRush both have features which can help with this kind of task.
Resharper's change signature functionality is probably the closest match.
Can't you generate a new interface from the class you have and then remove the ones you don't need! if it's that simple!!
change the return type : by changing... the return type, provided it is not a standard type (...), and the converter can be implemented by a TypeConverter.
When i have such boring task to do, i often switch VS2010 and use a tool that allow regex search and replace. In your example, maybe change 'return xxx;' by 'var yyy=convert(xxx); return yyy;'
(for example editor Notepad++ (free) allready offers quite some possiblities to change everything in a project (use with caution))

How do I show that I'm getting the smallest number of conflicts with Git by using K&R instead of B&D as the coding standard?

Git is smart and will "follow" changes in history to make merging easier and auto merge more for me. Conflicts are delineated by the lines that have not changed around the change. With K&R you get no ambiguous lines that have only "{" in them like you would in B&D. How would I test the limit of the context sensitivity that Git has in terms of the lines that surround a change?
I want to avoid resolving conflicts that I may not need to. But I need some way to test how many potential conflicts I will save by switching to K&R and the additional context it brings.
So far, Git is too smart to get fooled by trivial examples.
Any help is appreciated. Thanks in advance.
So this is the closest thing I have found so far as evidence to this.
http://git.661346.n2.nabble.com/Bram-Cohen-speaks-up-about-patience-diff-td2277041.html
The e-mail is discussing the purpose of the "patience" algorithm in Git. In it Bram explains how superfluous matching lines can create nasty conflicts that can be tough to resolve but only in the case of fairly complex merges involving large patches. In other words simple contrived examples will fail to show this behavior.
While he does also mention things like End affecting the results it makes some sense to infer that placing an opening brace on it's own line increases the number of superfluous matching lines possibly resulting in a greater probability of these conflicts.
I'd say this isn't iron-clad, but it does lend some credence to this theory.
So 'unique lines' is a simple cross-language proxy for 'unimportant
lines'.
That quote stands out to me in this discussion, since we are basically matching on what we feel are important lines that are supposed to give us context, however a brace by itself is not important and provides no context.
Pick standard that is easier for you/your team to read over anything else. No matter how your source control system behaves today it will behave better tomorrow, but your code will stay the way you've checked it in for long time.
We have several large projects (over 200+ code files), which contain a massive mixture of both K&R AND B&D. I can safely say that after almost 2 years on Git, a development staff that is refactoring-crazy, and a rebasing behavior of "several time a day", that I have never had a conflict due to coding standards things. So pick whichever, or both, or neither. It won't matter.

Contractor changing code style [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 6 years ago.
Improve this question
I currently support an application at work that was originally written by a team of four but has now reduced to just me. We recently got a contractor in to look at some performance issues while I'm occupied with other things.
While the contractor has appeared to do a good job with the performance, they have also gone through large amounts of the code replacing the pre-existing style with their personal preference.
Unfortunately we don't have a coding standards doc, just a general rule to adhere to c# general rules.
As an example of what they've done, it includes:
removing nearly all the uses of the 'var' keyword
Anywhere with an if statement and a single line, they've added curly braces
Removing most of the lambdas and replacing it with more verbose code
Changing method signatures so every parameter is on a separate line rather than one line
We also operate a TDD policy but the test coverage, especially on the performance specific parts, is very low leaving very little documentation on what they've changed and making it even harder as their checkin comments aren't particularly helpful and the actual functional changes are lost amongst the swathe of 'tweaks'.
How do I talk to the contractor about this? Obviously there's not much impetus on them to change it given they have no responsibility to support the project and they don't seem particularly receptive to change.
Or should I just put up with it for the short duration of the contract then change everything back to the code formatting we used before?
Made community-wiki 'cos there's probably not one right answer here.
Anywhere with an if statement and a single line, they've added curly braces
This one and the only one may be beneficial.
removing nearly all the uses of the 'var' keyword
Removing most of the lambdas and replacing it with more verbose code
Changing method signatures so every parameter is on a separate line rather than one line
These ones make little sense to change.
Tell him he's not authorized to restyle code. You won't be paying for the time wasted for these activities and they'll have to use their own time to put things back. That should provide a refreshment.
These things should be discussed in advance. You should state clearly what activities are allowed and what not. Not a long ago there was another similar question here about a contractor who would put his initials all over the code including database entities. It was some perverse kind of self-promotion for which there is no place in someone else's code.
P.S. There may also be a possibility that by doing all these things your contractor is artificially creating extra workload to bill you more hours.
I'm a contractor (sometimes) and if I did this I would expect to be shown the door with great speed and no payment. Seriously, this person is hired by you and should be doing exactly what he is told to do, no more and no less. And don't worry about being "nice" - contractors don't expect that from permies.
How do I talk to the contractor about this?
Politely: explain why you want to minimize changes to the source code.
ALternatively, have a code inspection of the changes before check-in: and don't allow check-in of changes that you don't understand/don't want/haven't been tested.
Implement FxCop - this should be your first line of defense. Also if you use source control (if you don't then implement one ASAP), make sure to use dev labelling (only build on file that have been labelled for the build), and don't give him rights to move labels on the files. This way you can scrutinize his changes, and refuse to dev label his code until it meets your standards. Whatever he codes won't make it into QA until you move the dev label to the revision in question, so he's pretty much at your mercy there. Note that some shops don't use a single label for their sandbox builds, they like to apply new labels even to the sandbox, so you may be inclined to do that as well.
The problem has happened now, and as the other said it's an unjustifiable waste of your money and it's outright impolite (as correct as the curly braces thing may be).
Certainly to help prevent future problems, and maybe helpful to resolve this, I'd advise you set up a stylecop implementation - at the very least they can't fail to be unaware of when they are breaking your rules.
I think we all know the temptation of seeing coded we think is "not the way I'd do it". But we resist it.
I would have a chat about it with your boss first to get their take on it. But the first thing that springs to mind is that unless you specifically asked the contractor to do the work, he was not doing what he was hired to do, regardless of any benefit he thinks he may have been adding. So there needs to be a discussion about that.
The next thing that sprung to mind is that regardless of how good they may be or well intentioned, people who make bulk changes without discussing it with the owners of the code are bad news. They will piss people off, or worse introduce bugs and unforeseen behavior that you will have to clean up. He needs to be set straight that doing this sort of thing without permission on other peoples code is not acceptable.
When I see things I don't like in others code which are serious enough to warrant attention, I check with the owners of the code first. Even if there are obvious bugs, it
s their code and their decision about cleaning it up, not mine.
As others have said, these changes are simply for coding style. If he is there to improve performance, he is wasting time with these changes. If he can't cite how these changes will improve performance, then his OCD is just running up the bill.
I would say, "I appreciate your changes to the coding style, but lets focus on non-style changes to areas of the code that are causing the slowdown."
If a contractor did wholesale reformatting of code without authorization, I'd give him one and only one change to put things back the way they were -- and on his own time.
In addition to the valid points others make, consider the version-control nightmare this causes. Instead of the clean progression of a few lines added here, a few lines changed here, you now have this "rift" in your source control database, so that any comparisons between versions before and after this contractor's "improvements" will be meaningless.
Have the contractor back out all of his changes. Today. And on his own time.
This is quite common my experience, that people can't resist making 'improvements' and suddenly you find you're billed for stuff you didn't want. Sometimes I'm sure it's done deliberately to get more paying work, but mostly I think it's a developer getting side-tracked and unable to deal with leaving 'wrong' code.
It might require a bit of a battle, but you basically have to keep reiterating "don't change anything you're not asked to work on". Depending on his personality, you might just have to ask once nicely, or get someone higher to force him.
First, as others have said. You are paying the bill. He is not an employee. His job is to do what you ask him to do, and only what you ask him to do, otherwise you can show him the door. Always remember this. You are driving the boat, not him. You can try to not pay him, but that will be hard to do if you have a legal contract and there is nothing in it about leaving code as-is. But, you can simply let him go at any time.
Second, if you can't get him to stop and revert, and you can't get rid of him, you can tell him that if he plans to do style changes, then he should do all style changes in one check-in with absolutely NO code changes. This allows you to move forward from a base set of code that can be diffed to see code changes.
Third, make him explain the justification for the changes he's made. Removing var has no performance benefit.
Fourth, and this may suck a great deal, but youc an always use ReSharper to put the code back to your accepted style after the fact. It's more work, and you still have borked diffs, but oh well. The lambdas are harder, and that's the one you should really get on his case about.
Fifth, to drive home your point, force him to back out every change he's made and re-implement only the code changes, and not the style changes. That should open his eyes as to the mess he's created when he can't figure it out himself.
Finally, you may just have the bite the bullet and PAY him to revet back. Yes, it sucks, but since you made the mistake of not policing him, not specifying up front what you wanted, and what he's not allowed to do... You will pay the ultimate price. You can either pay him to do it, pay someone else to do it, pay you to do it, or live with it (and pay the price of the borked diffs). Any way you cut it, it will cost you money.
Well, smells like a solution wide code reformatting to me, that could be automated/enforced by settings in a tool like Resharper. I would think it very impolite and would ask him to refrain from pressing the "Reformat all code according to my personal taste" button.
To avoid the situation happening in the first place, introduce code review, particularly for any new developers joining who may not know your standards.
I'm a big fan of using git, feature branches and a service that supports pull requests (github or bitbucket). TFS isn't really up to the job, but thankfully Visual Studio supports git now. Doing code review before merging to master ensures it doesn't get forgotton. If you're paranoid you don't even need to give contractors write access to your primary repository.
Alternate point of view:
Your make two statements: "While the contractor has appeared to do a good job with the performance" and "they have also gone through large amounts of the code replacing the pre-existing style with their personal preference."
This raises many questions such as: Whenever you can "drop in" a contractor for a short period of time and gain performance enhancements. This indicates that there must have been very major flaws in the application in the first place. Anytime you need to bring in a contractor to "fix performance" this is a sign of very poorly written code or a very complex problem that requires high end expertise.
Next: When you complain that they have changed the code style even though you did not have any stated code style are you just making a pointless argument about your mojo being better than someone else's mojo. Maybe you should ask the person why they made changes which appear syntactical such that you have a complete picture.
I'm looking at the long list of one sided answers on this post and wondering what happened to the other side. Folks take the emotion out of it and look at it objectively. It's often amazing how many people will look past a beautiful algorithm solution to a complex problem just to notice that the variable naming convention has been altered from camel case to pascal case. I generally put this type of reaction down to justification of self worth by finding immaterial flaws.
Key question I have to ask is: Does the newly formatted code make the application any less readable. If you had budget constraints why did you not make it explicit that you wanted very specific fixes and nothing else. If you wanted to maintain a specific coding style then why not have that explicitly stated?

Coding guides: How do you split up your large source files?

The project I'm working on has just hit 4200 lines in the main C# file, which is causing IntelliSense to take a few seconds (sometimes up to 6 or so) to respond, during which Visual Studio locks up. I'm wondering how everyone else splits their files and whether there's a consensus.
I tried to look for some guides and found Google's C++ guide, but I couldn't see anything about semantics such as function sizes and file sizes; maybe it's there - I haven't looked at it for a while.
So how do you split your files? Do you group your methods by the functions they serve? By types (event handlers, private/public)? And at what size limit do you split functions?
To clarify, the application in question handles data - so its interface is a big-ass grid, and everything revolves around the grid. It has a few dialogs forms for management, but it's all about the data. The reason why it's so big is that there is a lot of error checking, event handling, and also the grid set up as master-detail with three more grids for each row (but these load on master row expanded). I hope this helps to clarify what I'm on about.
I think your problem is summed up with the term you use: "Main C# file".
Unless you mean main (as in the method main()) there is no place for that concept.
If you have a catch-all utility class or other common methods you should break them into similar functional parts.
Typically my files are just one-to-one mappings of classes.
Sometimes classes that are very related are in the same file.
If your file is too large it is an indication your class is too big and too general.
I try to keep my methods to half a screen or less. (When it is code I write from scratch it is usually 12 lines or fewer, but lately I have been working in existing code from other developers and having to refactor 100 line functions...)
Sometimes it is a screen, but that is getting very large.
EDIT:
To address your size limit question about functions - for me it is less about size (though that is a good indicator of a problem) and more about doing only one thing and keeping each one SIMPLE.
In the classic book "Structured Programming" Dijkstra once wrote a section entitled: "On our inability to do much." His point was simple. Humans aren't very smart. We can't juggle more than a few concepts in our minds at one time.
It is very important to keep your classes and methods small. When a method gets above a dozen lines or so, it should be broken apart. When a class gets above a couple of hundred lines, it should be broken apart. This is the only way to keep code well organized and manageable. I've been programming for nearly 40 years, and with every year that has gone by, I realize just how important the word "small" is when writing software.
As to how you do this, this is a very large topic that has been written about many different times. It's all about dependency management, information hiding, and object-oriented design in general. Here is a reading list.
Clean Code
SOLID
Agile Principles, Patterns, and Pratices in C#
Split your types where it's natural to split them - but watch out for types that are doing too much. At about 500 lines (of Java or C#) I get concerned. At about 1000 lines I start looking hard at whether the type should be split up... but sometimes it just can't/shouldn't be.
As for methods: I don't like it when I can't see the whole method on the screen at a time. Obviously that depends on size of monitor etc, but it's a reasonable rule of thumb. I prefer them to be shorter though. Again, there are exceptions - some logic is really hard to disentangle, particularly if there are lots of local variables which don't naturally want to be encapsulated together.
Sometimes it makes sense for a single type to have a lot of methods - such as System.Linq.Enumerable but partial classes can help in such cases, if you can break the type up into logical groups (in the case of Enumerable, grouping by aggregation / set operations / filtering etc would seem natural). Such cases are rare in my experience though.
Martin Fowler's book Refactoring I think gives you a good starting point for this. It instructs on how to identify "code smells" and how to refactor your code to fix these "smells." The natural result (although it's not the primary goal) is that you end up with smaller more maintainable classes.
EDIT
In light of your edit, I have always insisted that good coding practice for back-end code is the same in the presentation tier. Some very useful patterns to consider for UI refactorings are Command, Strategy, Specification, and State.
In brief, your view should only have code in it to handle events and assign values. All logic should be separated into another class. Once you do this, you'll find that it becomes more obvious where you can refactor. Grids make this a little more difficult because they make it too easy to split your presentation state between the presentation logic and the view, but with some work, you can put in indirection to minimize the pain caused by this.
Don't code procedurally, and you won't end up with 4,200 lines in one file.
In C# it's a good idea to adhere to some SOLID object-oriented design principles. Every class should have one and only one reason to change. The main method should simply launch the starting point for the application (and configure your dependency injection container, if you're using something like StructureMap).
I generally don't have files with more than 200 lines of code, and I prefer them if they're under 100.
There are no hard and fast rules, but there's a general agreement that more, shorter functions are better than a single big function, and more smaller classes are better than 1 big class.
Functions bigger than 40 lines or so should make you consider how you can break it up. Especially look at nested loops, which are confusing and often easy to translate to function calls with nice descriptive names.
I break up classes when I feel like they do more than 1 thing, like mix presentation and logic. A big class is less of a problem than a big method, as long as the class does 1 thing.
The consensus in style guides I've seen is to group methods by access, with constructors and public methods on the top. Anything consistent is great.
You should read up on C# style and refactoring to really understand the issues you're addressing.
Refactoring is an excellent book that has tips for rewriting code so that behavior is preserved but the code is more clear and easier to work with.
Elements of C# Style is a good dead tree C# style guide, and this blog post has a number of links to good online style guides.
Finally, consider using FxCop and StyleCop. These won't help with the questions you asked, but can detect other stylistic issues with your code. Since you've dipped your toe in the water you might as well jump in.
That's a lot, but developing taste, style and clarity is a major difference between good developers and bad ones.
Each class should do one small thing and do it well. Is your class a Form? Then it should not have ANY business logic in it.
Does it represent a single concept, like a user or a state? Then it shouldn't have any drawing, load/save, etc...
Every programmer goes through stages and levels. You're recognizing a problem with your current level and you are ready to approach the next.
From what you said, it sounds like your current level is "Solving a problem", most likely using procedural code, and you need to start to look more at new ways to approach it.
I recommend looking into how to really do OO design. There are many theories that you've probably heard that don't make sense. The reason they don't is that they don't apply to the way you are currently programming.
Lemme find a good post... Look through these to start:
how-do-i-break-my-procedural-coding-habits
are-there-any-rules-for-oop
object-oriented-best-practices-inheritance-v-composition-v-interfaces
There are also posts that will refer you to good OO design books. A "Refactoring" book is probably one of the very best places you could start.
You're at a good point right now, but you wouldn't believe how far you have to go. I hope you're excited about it because some of this stuff in your near future is some of the best programming "Learning Experiences" you'll ever have.
Good luck.
You can look for small things to change and change each slowly over time.
Are all the methods used in that class only? Look for support methods, such as validation, string manipulation, that can be moved out into helper/util classes.
Are you using any #region sections? Logical groupings of related methods in a #region often lend themselves to being split into separate classes.
Is the class a form? Consider using User Controls for form controls or groups of form controls.
Sometimes large classes evolve over time due to lots of developers doing quick fixes / new features without considering the overall design. Revisit some of the design theory links others have provided here and consider on-going support to enforce these such as code reviews and team workshops to review design.
Well, I'm afraid to say that you may have a bigger issue at hand than a slow load time. You're going to hit issues of tightly coupled code and maintainability/readability problems.
There are very good reasons to split class files into smaller files (and equally good reasons to move files to different projects/assemblies).
Think about what the purpose that your class is supposed to achieve. Each file should really only have a single purpose. If it's too generalized in its goal, for example, "Contain Shopping Basket Logic", then you're headed down the wrong path.
Also, as mentioned, the term you use: "Main C# file" just reeks that you have a very procedural mindset. My advise would be to stop, step back, and have a quick read up on some of the following topics:
General OOP principles
Domain-driven design
Unit testing
IoC Containers
Good luck with your searches.
Use Partial classes. You can basically break a single class into multiple files.
Perhaps the OP can respond: is your project using Object-Oriented Programming? The fact that you use the word "file" suggests that it is not.
Until you understand object orientation, there is no hope for improving your code in any important way. You'd do better to not split up the file at all, wait until it grows to be unbearably slow and buggy, then instead of bearing it any more, go learn OO.
The Intellisense parser in Visual Studio 2008 seems to be considerably faster than the one 2005 (I know they specifically did a lot of work in this area), so although you should definitely look into splitting the file up at some point as others have mentioned, Visual Studio 2008 may resolve your immediate performance problem. I've used it to open a 100K+ line Linq to SQL file without much issue.
Split the code so that each class/file/function/etc. does only One Thing™. The Single Responsibility Principle is a good guideline for splitting functionality into classes.
Nowadays, the largest classes that I write are about 200 lines long, and the methods are mostly 1-10 lines long.
If you have regions of code within a class, a simple method is to use the partial keyword and breakout that definition of the class into that file. I typically do this for large classes.
The convention I use is to have the ClassName_RegionName.cs. For example, if I want to break out a class that manages the schema for a database connection, and I called the class DatabaseConnection I would create a file called DatabaseConnection.cs for the main class and then DatabaseConnection_Schema.cs for the schema functionality.
Some classes just have to be large. That's not bad design; they are just implementation-heavy.

In C# (or any language) what is/are your favourite way of removing repetition?

I've just coded a 700 line class. Awful. I hang my head in shame. It's as opposite to DRY as a British summer.
It's full of cut and paste with minor tweaks here and there. This makes it's a prime candidate for refactoring. Before I embark on this, I'd thought I'd ask when you have lots of repetition, what are the first refactoring opportunities you look for?
For the record, mine are probably using:
Generic classes and methods
Method overloading/chaining.
What are yours?
I like to start refactoring when I need to, rather than the first opportunity that I get. You might say this is somewhat of an agile approach to refactoring. When do I feel I need to? Usually when I feel that the ugly parts of my codes are starting to spread. I think ugliness is okay as long as they are contained, but the moment when they start having the urge to spread, that's when you need to take care of business.
The techniques you use for refactoring should start with the simplest. I would strongly recommand Martin Fowler's book. Combining common code into functions, removing unneeded variables, and other simple techniques gets you a lot of mileage. For list operations, I prefer using functional programming idioms. That is to say, I use internal iterators, map, filter and reduce(in python speak, there are corresponding things in ruby, lisp and haskell) whenever I can, this makes code a lot shorter and more self-contained.
#region
I made a 1,000 line class only one line with it!
In all seriousness, the best way to avoid repetition is the things covered in your list, as well as fully utilizing polymorphism, examine your class and discover what would best be done in a base class, and how different components of it can be broken away a subclasses.
Sometimes by the time you "complete functionality" using copy and paste code, you've come to a point that it is maimed and mangled enough that any attempt at refactoring will actually take much, much longer than refactoring it at the point where it was obvious.
In my personal experience my favorite "way of removing repetition" has been the "Extract Method" functionality of Resharper (although this is also available in vanilla Visual Studio).
Many times I would see repeated code (some legacy app I'm maintaining) not as whole methods but in chunks within completely separate methods. That gives a perfect opportunity to turn those chunks into methods.
Monster classes also tend to reveal that they contain more than one functionality. That in turn becomes an opportunity to separate each distinct functionality into its own (hopefully smaller) class.
I have to reiterate that doing all of these is not a pleasurable experience at all (for me), so I really would rather do it right while it's a small ball of mud, rather than let the big ball of mud roll and then try to fix that.
First of all, I would recommend refactoring much sooner than when you are done with the first version of the class. Anytime you see duplication, eliminate it ASAP. This may take a little longer initially, but I think the results end up being a lot cleaner, and it helps you rethink your code as you go to ensure you are doing things right.
As for my favorite way of removing duplication.... Closures, especially in my favorite language (Ruby). They tend to be a really concise way of taking 2 pieces of code and merging the similarities. Of course (like any "best practice" or tip), this can not be blindly done... I just find them really fun to use when I can use them.
One of the things I do, is try to make small and simple methods that I can see on a single page in my editor (visual studio).
I've learnt from experience that making code simple makes it easier for the compiler to optimise it. The larger the method, the harder the compiler has to work!
I've also recently seen a problem where large methods have caused a memory leak. Basically I had a loop very much like the following:
while (true)
{
var smallObject = WaitForSomethingToTurnUp();
var largeObject = DoSomethingWithSmallObject();
}
I was finding that my application was keeping a large amount of data in memory because even though 'largeObject' wasn't in scope until smallObject returned something, the garbage collector could still see it.
I easily solved this by moving the 'DoSomethingWithSmallObject()' and other associated code to another method.
Also, if you make small methods, your reuse within a class will become significantly higher. I generally try to make sure that none of my methods look like any others!
Hope this helps.
Nick
"cut and paste with minor tweaks here and there" is the kind of code repetition I usually solve with an entirely non-exotic approach- Take the similar chunk of code, extract it out to a seperate method. The little bit that is different in every instance of that block of code, change that to a parameter.
There's also some easy techniques for removing repetitive-looking if/else if and switch blocks, courtesy of Scott Hanselman:
http://www.hanselman.com/blog/CategoryView.aspx?category=Source+Code&page=2
I might go something like this:
Create custom (private) types for data structures and put all the related logic in there. Dictionary<string, List<int>> etc.
Make inner functions or properties that guarantee behaviour. If you’re continually checking conditions from a publically accessible property then create an private getter method with all of the checking baked in.
Split methods apart that have too much going on. If you can’t put something succinct into the or give it a good name, then start breaking the function apart until the code is (even if these “child” functions aren’t used anywhere else).
If all else fails, slap a [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] on it and comment why.

Categories