It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is there a good practice to split part of complex method's functionality to several smaller methods only in terms of good code readability (but maybe paying some performance for methods calling)? Or this is some kind of "bad style"?
The very basic rule is that your method should do only one thing. If you detect that is doing many different things, then you have a clear refactoring oportunity.
If you reach the point where your method has a single responsability but the size is too long anyway, try to extract "helper" functionality to separated methods. You might even detect code that can be promoted to separated classes.
TDD development is a great methodology to avoid this kind of issues since it really helps to clearly separate concerns and to avoid a bunch of code on single methods just for the sake of testability. If you don't write concise methods, it becames too hard to test them properly.
If you think about reusing code (The DRY principle), you should consider refactoring. Split the method content into different small module based on the functionality so that it can be reusable. Ex : If you have a method which saves a customer registration details and create a new order for him. you could probably check that many methods like CheckUserExist, SaveUser and SaveOrder. You should be able to reuse this functionalities in other areas of your code as necessary. Splitting it into modular pieces makes your code more readable too.
Unclebob (Robert C. Martin) considers that methods should be no larger than 4-5 lines of code. His motto, concerning this, is "Extract till you drop". Personally, i believe this is a very good practice.
Visual Studio allows you to extract a method by pressing CTRL+R, M.
in addition to Claudio's answer, there are some SMELLS that if detected, it means that you have to refactor and split your code.
1- non-DRY code: if you find yourself copying/pasting some lines into more than one place, this is a bad smell that needs to be placed in a center placed, and to be called from as many as it should be.
2- Methods with hundreds of lines: any good method should not exceed 50 lines of code, maybe more or less than this number, but rest assured that this method of 346 lines is not a good thing to do.
3- Too many parameters: a long list of parameters in your methods make readability and code quality worse.
4- code invasion: Methods that are using many blocked from another class, should exist inside this class.
Hope that helps.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have recently started using the MVVM pattern. I'm beginning to see that my View-Model's might quickly get very large and unmanageable. Is there some way to counter this?
There are a few approaches to this. I've yet to find a single universal "fix", but I'll share a few things I've picked up along the way. You've tagged this as c#, but not specified what platform you're using (is this a desktop app, ASP.NET website, or what?) so I'll try to keep it generic. Most of my experience of MVVM is in web development though, so bits of that may creep in.
First, recognise that massive viewmodels can be a symptom of a design that needs rethinking. It might be that one page is trying to do too much. Breaking this page up into several pages will not only reduce the size of your viewmodel, it will also let you move logic into other methods and make your backend or server-side code easier to navigate, and may well make the page less cluttered and easier for the end user to actually use.
Second, look closely to see if your viewmodels are overstepping their bounds a little. They might be doing logic that should be handled elsewhere. For example, if you're using repositories (or something like them) to access a data source, let those classes handle logic relating to constructing queries or preparing data for saving, rather than making your viewmodels do it. If you don't use repositories, consider adding some in and shifting your datasource-access code to them.
Similarly, see if your viewmodels share logic. If so, shift it to a base class and inherit from that one whenever you need that shared logic. You can inherit from multiple base viewmodels to combine functionality and reduce code repetition.
This last point is a little more web-specific, but: make use of partial views. If the viewmodel for your page is getting large because that page has a lot of stuff on it, consider splitting the page into areas or panes (at least conceptually, if not visually) and making each area a partial view. This means that your view code is easier to read, because what was an enormous page is now more or less just a template with partial view calls. It makes your server-side code easier to read, because what was one big method to construct and populate this huge page is now several smaller ones. Best of all, it may even allow you to do clever things with those panes, like using AJAX to reload them (periodically or based on interactions or events) without having to reload the whole page.
Partial classes, ViewModels inheritance (i.e. base ViewModel that contains common logic you shouldn't duplicate), separation of concerns (i.e. use a service layer and do not call DB request from ViewModels)...etc.
It depends on your actual code, and on what you mean by "very large". Your question is actually vague.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have been advised to refrain usage of Reflection. I really wanted to know, is it because Reflection is expensive? If not what is the reason to avoid using it?
My current and future projects might as well need to access any given class - members information. As I some times need to list fields & Properties - values or declaration name.
So What I would like to know, is:
How does Reflection work? How does it get to the information? (a short explanation will do)
And why it's not so recommended to use the reflection in application? If you do need to get required information being a field or properties values OR names, could you do it not by using System.Reflection?
Some background.
The usage in my current project(for example), is to list out a specific sql server table-columns names, or SQL - tables names .
I could think of other ways to have it returned as a List<strings>.
If I really knew why or how "bad" it is, to use reflection,
..I could then make a decision, if I really want to avoid it, as I might find an alternative approach (in this specific scenario).
Either by accessing database (not preferable) any time I need (say) list of tables names or I could do it once (access the data ), then store it in a text file or xml, if I really must avoid reflection.
I know of some even more elegant one, too. That's not the issue though. (again this is only an example as there could be many other use cases, you probably know that. )
update
this Question was closed please help reopen it , and vote 'reopen' below
thanks .
A CLR assembly (executable or dynamic link library) typically contains metadata about its structure, which means information about the types, the structures, the methods, the fields, their names and a bunch of other information that, in "traditional" languages, were usually lost and replaced by offsets and size information only.
Reflection is a powerful tool and some (usually advanced) things can only be achieved using reflection. However, it also raises concerns about security and encapsulation, because you start relying on the implementations of the parts of your program (or other programs), while you should generally avoid those and just trust the interface those parts give. Another concern is performance, because to access all this kind of (ultimately textual) information, the program is slowed down, in contrast to using the non-reflective approaches (which usually still use offset and size information). For instance, you could re-implement polymorphism using reflection and bypass the virtual method table. But the latter is many times faster than the former.
Use reflection if you have to, but don't use it if you don't have to. It's one of those tools that are very powerful and people advise against using them, but you may use them if you really know what you're doing. That being said, please keep in mind that using reflection techniques in a wrong manner does not only raise the above issues, but tends to make your code significantly harder to maintain as well.
If it were as simple as "never use reflection", we wouldn't have reflection at all.
Reflection is slow, and as such, you have to be judicious in its use. Often times there are better solutions (both in terms of design and performance) that use interfaces, delegates, etc to accomplish your goals (dependency injection and dynamic types come to mind).
Try to figure out how to solve your problem using object oriented design without reflection. If you truly need to use reflection, consider how its performance will impact your application, and design accordingly.
Reflection works by parsing class type information. Use it sparingly as its computationally expensive.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have an utility library with the class ConsoleApp, which has only static method like GetIntValue(string name) to ask user to enter the integer value of the parameter with specified name, or functions to parse command line parameters.
As for me ConsoleApp is an utility class, and inheriting it just to get avoid "ConsoleApp." in the code looks like BaseBeen anti-pattern.
But on the other side, ConsoleApp will be inherited only by the classes that is really Console applications, in this way, it's not a BaseBeen.
So, is it really BaseBeen?
SOLID design principles (particularly SRP, O/CP, and DIP) suggest that you're better providing that functionality via delegation (e.g. strategy pattern). Has-A is better than Is-A, etc.
However, you're pretty squarely in first-world-problems territory here because Program.cs is very much on the transient end of your codebase. Clearly you might need to parse some command line parameters before your bootstrapper runs (e.g. to configure your bootstrapper!), so you might find it challenging to inject some kind of value provider.
So, I'd say yes it's an antipattern, however there are probably more important things to worry about.
See e.g. http://s3.amazonaws.com/hanselminutes/hanselminutes_0145.pdf page 8 where Uncle Bob talks about DIP:-
"Main is the most concrete of our
functions and it will create all of our instances and all of the
factories ... and it will then
hand off to the abstract part ... and the
abstract core will manipulate it as though it were in this fantasy
world where everything was abstract."
If Main has to call some static methods, that's ok. If you want to inherit from a utility class to make it easier for you, that maybe smells a bit but I don't really care. Just make sure you know where the boundary is. If you're using your static utility class outside of Main then you're likely to have a problem.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have a first job interview for a software engineer position but in the email they state that I will have to write out a program at the interview stage. Does everyone do this?
What kind of program might it be for a graduate?
The job is for a .NET developer, but I can use any language, so I will stick with C#. I'm actually S**Ting it; I have no clue what they are going to ask me to do.
Many companies will spend much of the interview time asking candidates to write actual code (usually on a whiteboard or piece of paper though sometimes on a real computer) as this is a great way to see if they will be successful in the job. Some things to keep in mind:
Talk out loud. Often interviewers care about your thought process and approach to the problem as much or more than they care about the actual code you write.
Ask questions. Interviewers will often intentionally make a problem ambiguous just to see if you'll notice and seek clarification. Ask things like: "Who is the audience?" "Should I include exception handling?" "Shall I optimize for performance or just make sure it works?"
Don't get flustered if you're struggling. Tell the interview what you're thinking and they'll often point you in the right direction. Partial credit counts.
Get a good night's sleep before your interview. Lots of whiteboard coding and related discussion can be surprisingly grueling.
Good interviewers will be able to extract what you've learned over the course of your lifetime, so don't worry too much about last minute study sessions. It's too late. That said, it's not a bad idea to brush up on basic language syntax and core data structures and algorithms.
Here are some sample problems you may want to practice writing out on paper:
Write a function to calculate the nth number in the Fibonacci sequence.
Write a function to sort 2 arrays of numbers (without using existing libraries).
Design a Deck class and a Card class and write a function to shuffle a deck of cards.
Design a Circle class and write a function to determine if 2 circles intersect.
Design a LinkedList class and write a function to reverse the elements in the list.
At least be able to do this FizzBuzz
By the time the interview is scheduled, there's probably not too much you can do in the order of preparation.
Just remember, they want to know about your problem solving process. Just try to think out loud as much as possible and if you truly don't know something just say so.
No matter what type of question they ask, just go with the flow and do your best on it. The last thing any interviewer wants to see is someone who gets flustered or upset due to a particular question. I'll be the first to admit that some of the questions asked in an interview may be lame and unnecessary, but you are trying to get a job from these people and you will just have to humor them.
When you have more time to study, you should probably start looking at Questions every good .NET developer should be able to answer.
We issue programming tests all the time. There are many reasons for doing this, over and above the obvious one of testing coding ability. We look for
a) Coding style
b) Ability to develop and implement algorithms
c) Ability to follow instructions
d) Ability to communicate what has been done
But by far and away the most valuable thing about a programming test is discussing with the candidate why they did what they did. In this discussion it becomes obvious rather quickly how much the candidate really understood the test and their own design and implementation. It also roots out plagiarism very quickly.
Usually software development jobs give simple tests. I've never once interviewed for a job that required any more than a simple implementation of a function.
Her'es a few simple tests I know of:
FizzBuzz: http://www.geekschool.org/programming/fizzbuzz/
For a job at MS, I was asked to write a function to reverse the words in a string.
At a different job, I was asked to write an implementation of the Join function in c++.
A friend of mine got this one for game development: Write a function to test simple rectangle collision
More than likely it's something simple like FizzBuzz, just meant to weed out the totally unqualified people.
If the company don't ask for you to write code in the interview, that's really, really bad. Go for another company.
The type of test depends. I've done test that i had to write small C code, with pointers or recursive functions.
But generally, they ask for a basic asp.net application (I'm also C# developer), like just one form, inserting and reading from the DB.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 13 years ago.
Please can anyone one point me to a good tutorial that helps me to make my code fast and light.
I'm interested to know which Method is faster and when to use a method instead of other...
And how to evaluate if a code is good or bad?
My programming language is C#.
Hi all,
Thanks for your replies, they are very helpful.
I'm editing my question to be more specific specially that optimization is unlimited.
I want to know what is the best method in each condition.
For example using StringBuilder is better than string if i am appending lines to a string...
I only need this simple things.
Be aware of sub optimization.
Even though one specific function is faster than another replacing this isn't necessarily gonna make any difference in the runtime of your application. You need to understand which parts of your code that actually is a potential problem, and focus on optimizing these parts. Be aware of the O notation of your functions, and how often they are called. To identify parts that needs optimization a profiler can be of good help.
This question has some interesting points on why you shouldn't optimize until there is actually a need to do so.
Sure. Here's what we do:
Begin the journey by deciding when the journey is over. Set meaningful, customer-focussed, realistic performance goals. (For both speed and resource consumption.)
Carefully test your code frequently to see if you are meeting your performance targets.
If you are meeting your performance targets, don't worry about performance. Things are fine. Worry about bugs, or robustness, or features.
If you are not meeting your performance targets, run a profiler. Use it to identify what is the worst offending code. It only makes sense to fix the worst code; making something that is already incredibly fast and light slightly faster and lighter does not solve your performance problem.
Rewrite the slow code so that it's more performant. (This is the hard bit.) Make sure you test it to make sure it really is better.
If despite your best efforts you cannot make it good enough, either re-evaluate what your goals are, or cancel the project and spend your time on something that you can be successful at.
Keep iterating on that until you ship something.
Basically implement first, then test where to optimize.
If you are using Visual Studio Profissional you can use Analyze -> Launch Performance Wizard to analyze method performance. I am not sure about whether the other versions support this feature, however, there are also some commercial/free applications around ... look for profiler (see here for a list).
Type REALLY fast.
You should look at hidden features of c#, this post covers the most best practises in c# development
You can get a ton on advice of on this. But be aware of :
Premature optimization is root of all evil.
Aim first for correctness, next for clarity and only then performance.
As the old saying goes,
"No one cares how quickly you can calculate the wrong answer"
(on a practical level though, use a profiler)
If one method was always faster than another, they wouldn't bother including the slower one.
The only invariant when it comes to performance is that you need to profile. Everything follows from that.
If you get yourself a profiler, it will help you along, some will even give you great tips.
Example: ANTS Profiler
Usually you will find that reducing the number of times you create Strings to be the main performance boost you can get.
That and not messing with the Garbage Collector manually (unless you really really know what you're doing)
This link for Java design patterns is way too involved, don't get too put off by the word Java there, you can use what they teach for development in any language.
The thing is, if you want to know when to do what and what methods to use and so on, design patterns is what you are talking about.
I wish someone had pointed this to me earlier in my career.
In terms of general advice:
Try to use the fewest loops necessary
Move code out of loops where possible
Avoid copying things (like strings) in loops
Avoid creating objects in loops
Cache where warranted (generally small objects that take a lot of time to make), but make sure your cache has a good disposal policy or it turns into a memory leak
You can compile your program in native mode to improve the runtime performance.
One of the ways of figuring this out yourself is having a console app where you try running discrete pieces of code against each other and timing them. Like here.