What Are The Best Practices When Developing Vb Net Best Practices

.NET Coding Best Practices – Vinayak's thumb rulesDo not hard code strings/ numerics. Instead of that use constants as shown below.Bad practice int Count; Count = 100; if( Count == 0 ) { // DO something… }Good practice int Count; Count = 100; private…

Đang xem: Vb net best practices

.NET Coding Best Practices – Vinayak”s thumb rulesDo not hard code strings/ numerics. Instead of that use constants as shown below.Bad practice
int Count;Count = 100;private static const int ZERO = 0;if( Count == ZERO ) { // DO something… }For string comparison – Use String. Empty instead of “” By default keep the scope of member variables to ‘private’, based on the needs expand the scope either to protected or public or internal.Other advantage of making the scope private by default is that during XMLSerilaization, by default it will serialize all the public members.When we have to manipulate the strings inside a loop, use StringBuilder instead of string as shown below.Bad practice
StringBuilder sb = new StringBuilder();for ( int I = 0 ; I100; i++) { sb.Append(i.ToString()); }Prefer Arrays over Collections for simple operations.Prefer Generic Collections over ArrayListPrefer Generic Dictionaries over HashTable *.Prefer StringCollections and StringDictionaries for String manipulations and storage.Use the appropriate data types. For ex: if you want to check for any status, prefer bool rather than int.Bad practice
bool Check = false;if(!Check) { // DO something }Use ‘as’ operator for type casting and before using that resultant value check for null.
class A { }class B : A { }B objB = new B();A objA1 = (A) objB;A objA 2 = objB as A;if( objA2 != null){ //Do something}For WCF proxy creation, use the using statement
using(Cerate the proxy) { //Do the required operation }Follow ‘Acquire late, release early’ rule for expensive resources such as Connection, File etc. For ex : if you want to make use of SqlConnection Object for any data operations, create the instance at the method level rather than at the class level.
class MyData { public MyData() { } public List GetAllCustomer() { using(SqlConnection objConnection = new SqlConnection(“Connection string”)) { //Do the operation and get the required data.. } }}If you want to create the SqlConnection instance at the class level, ensure that you are implementing the IDisposable for the class and doing the cleanup of SqlConnection instance at the Dispose();
class MyData : IDisposable { SqlConnection objConnection = default(SqlCOnnection); public MyData(){ objConnection = new SqlCOnnection(“Connection string”); } public List GetAllCustomer(){ // By using objConnection get the required data } public void Dispose(){ // Do the cleanup of SqlCOnnection if( objConnection != null ){ if( objConnection.State == ConnectionState.Open){ objConnection.Close(); } } }}If you do not want anybody to extend your class functionalities, make it ‘sealed’ to get the inlining and compile time benefitsAvoid declaring the ‘destructor’ for every class. This will increase the life time of the class which un necessarily makes them long livedPrefer using Thread Pool over manual threading.Do not make any calls to a method from the loop.For ex :Bad practice
for( int i = 0; i100; i++){ //Inline the body of Calculate.}Do not handle exceptions inside a loop, rather handle looping logic inside try/catchFor ex:Bad practice
try{ for(int i = 0 ; i100; i++){ }}catch(Exception ex){ throw ex;}Do not handle application logic by using Exception.For ex :Bad practice
private static const int ZERO = 0;try{ int x,y,z; x = 0; y = 10; if( x != ZERO){ z = y/x; } }catch(Exception ex){ }Prefer for/while loop over foreachFor communication between the layers, prefer Data Transfer objects over DataSet/DataTables.I hope this will help you all to improve the code quality!!Happy programmingRegards,-Vinayak

See also  Best Buy London Ontario, Canada), Best Buy London

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




Motivated achiever who guides organizations in applying technology to business settings, provides added value, and creates project deliverables in a timely manner. An experienced Technical Consultant, have successfully led large project teams of more than 20 people from requirements gathering to implementation and support using C#, .NET ,ADO.NET, ADO.NET Entity Framework,ASP.NET,ASP.NET MVC, WCF and SQL Server.


First Prev Next
Improve the snippet codes Adaying 23-Sep-15 2:08
Ironically for a person that is talking about best practices you clearly do not follow them. I don”t want to sound mean but you wrote some awful code snippets.Note that naming and writing conventions are also part of best practices…For starters look at the first two snippet codes, on one line you are declaring the Count then on another you are initiating it, why?If you look at the fifth and sixth snippet code you”ll see that you don”t follow this convention.Also what is with all these spaces in IF”s condition?In the third and fourth snippet code you have errors, c# is a case sensitive language.In the rest of the snippet codes you are actually using a scripting languages conventions, for example MyData(){, Dispose(){, etc. This is not applied in C#, the “{” goes on separate line.Etc.
Sign In·ViewThread
My vote of 3 Chamila Nishantha 15-Nov-12 17:39
Improvement tips: describe why is good or other wise bad.

Xem thêm: 7 Days To Die Best Gun – 7 Days To Die Weapon Preference: 7Daystodie

Sign In·ViewThread
Some good ideas… Sebastian Br. 25-Jan-10 22:05
…but you should say why it is better to use “foo” instead of “bar”!For eaxample: Why is it better to use for/each instead of for/while loops? Especially on today”s “fast-enough-machines”?Another example: constants are normally introduced for easily changing values in a later iteration of you project. If you change your “ZERO”-constant to – for example – one, than you have a constant named “ZERO” with a value “one”. That”s weired and will confusing Joe-Sixpack-Developer even more.
Sign In·ViewThread
Comment on the article jstemper 21-Jan-10 6:27
The article would have been so much more useful if you had included a sentence or two about why each point is/should be a best practice. Without that this is just another list.John
Sign In·ViewThread
#1, #2, #9, #15, #17, #18, #19 supercat9 20-Jan-10 6:05
#1 — ConstantsMy primary rule for using named constants is to determine what would have to happen for a number to be changed. If there are multiple places in the code which must all have the same value for things to work properly, then named constants should be used. If a particular number is used in only one place, but finding that spot in the event the number must change would be difficult, a named constant (defined in an easier-to-find location) may be appropriate. If a number is only used in one place, but other places in future may use that number (and have to match), a named constant is probably appropriate. On the other hand, something like:

Constant NumberOfTimesToBeep As Integer = 3For I=1 to NumberOfTimesToBeep BeepNextis often not really any better than
For I=1 to 3 BeepNextunless the same constant is, or is likely to be, used multiple times. In the latter case, anyone who sees the number “3” will be able to see what it actually does. In the former case, one would have to look at both the code and the declaration to see what”s going on.#2 — What advantage is there to String.Empty rather than “”? Shouldn”t string literals get interned? The latter formulation is more concise and easier to read.#9 — While Boolean data types are often better than integers, integers can be used with Interlocked operations.#15 — I”ve read various articles indicating one should use the thread pool, but I am leery of using a global resource whose usage by other code will often be unknown and unknowable. If two threads will need to wait for each other, using the system threadpool for them would seem to be a recipe for deadlock. I could certainly understand that using some form of thread pooling is often good, but the system thread pool seems hokey.#17 — The question of whether to handle exceptions inside or outside a loop is one of logic rather than style. If an exception is thrown in the loop, can useful work be done by the remainder of the loop? If so, the exception must be inside. If not, it should probably be outside. The one caveat I would add is that if an exception is thrown within a loop, one may want to check at run-time to ensure that no condition exists which would cause the rest of the loop to fail.#18 — One should early-check conditions which would be likely to cause exceptions, but be very leery of expecting to catch all exceptional conditions. If one didn”t have “Double.TryParse” available, for example, one could try to pre-validate the input before calling Double.Parse, but catching all possible invalid inputs while allowing all valid ones would be difficult. On the other hand, pre-checking the more common invalid-input scenarios may be worthwhile.#19 — What”s wrong with foreach, in situations where one is enumerating an IEnumerable?

Sign In·ViewThread
If these are considered best practices… bhogan 22-Dec-09 7:14
If these are considered best practices, I believe it would be better to provide the reasoning behind your opinions so readers can make informed choices in their coding style.
Sign In·ViewThread
Most are good tips… Ron Beyer 22-Dec-09 3:44
I agree with most of your tips, but there are a few that I have some problems with…1. Using constants…Will ZERO ever be anything different than 0? If not, then why use a constant expression rather than just the number? The problem here is that if you use a more generic constant like LOOPMIN, you can”t change just one of the loops that uses that, they will all change. I think the better practice is instead of declaring things that loop through arrays as:
Copy Code
int<> myArray = new int<100>;for (int i = 0; i You want to do something like this:
Copy Code
int<> myArray = new int<100>;for (int i = myArray.GetLowerBound(); i That way you can change the dimensions of the array without changing the iteration logic. Alternatively you can use something like:
int<> myArray = new int<100>;foreach (int v in myArray) v = 1;14. Avoid declaring a destructorDestructors properly implemented are extremely useful, and you should not rely on the GC to manage your object lifetime 100%. There are a lot of things you can do in a class that will make the GC hold references to your object, even after you are finished using them or they go out of scope. I would venture to say that your class should implement IDisposable and always finalize manually, so you can remove things like event handlers (they are not automatically removed). 15. Do not make calls in a method loopThere is a little bit of truth to this, but for complicated calculation routines you should break apart your loop into functions. Its difficult from a maintainability standpoint to have a single loop that has 1000 (as an example, even 100 lines is excessive) lines of logic inside the loop. Loops should be short, and you should easily be able to see what they do. If you have a function that can be inlined manually in short code, by all means do it. But complicated routines should be broken out. I live by the mantra that if your function spans 2 pages of printed text, it should be refactored.17. Do not handle exceptions in a loopThere are times that this is unavoidable. Your example would stop processing further items in the array if it excepted on a single element. Sometimes you want to ignore error elements and continue processing the rest of the collection. The only way to do this is to put the exception logic inside the loop. What you want to do however, is to avoid throwing exceptions as much as possible, handling them isn”t as expensive as throwing them.

Xem thêm: Best Small Tv 2015 Tv Line, 9 Best Tvs For 2015: Hd, 4K, Curved, Oled

Sign In·ViewThread
Re: Most are good tips…
For #17, you can avoid it by using a simple function for processing logic (which is where you would then place the try/catch). Half the time a function with try/catch-mes will have been called from a loop somewhere up the call stack. Personally I rarely try to create functions with large bodies statements but there are exceptional-cases which cause me to ignore this guidance.I don”t see too many cases where a small operation (where off loading one or two statements to a simple function would kind of be silly) would throw, unless it”s just a function call itself.It should also be mentioned that the CLR can inline functions with small code bodies. All the more reason we don”t want to pre-optimize! We”re not dealing with a native compiler (nor a framework without a type system) here so we shouldn”t be so quick to think of tips which worked in some performance cases with them, in our mananged .NET.Of course if you live and die by the #15 sword, then yes it will be unavoidable

Sign In·ViewThread
Last Visit: 31-Dec-99 18:00 Last Update: 22-Jul-21 1:15
Refresh 1




















Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Go to top
PermalinkAdvertise Privacy Cookies Terms of Use
Layout: fixed | fluid

See more articles in category: Best

Leave a Reply

Back to top button