首页 > 开发 > 综合 > 正文

C# Programming Guidelines

2024-07-21 02:18:09
字体:
来源:转载
供稿:网友
source:

this article is from a book named<thinking in c#>,if you are interested in the book,you'd better to have a real book made by paper :)

thinking in c#

larry o’brien and bruce eckel












prentice hall
upper saddle river, new jersey 07458
www.phptr.com

begin:

c[
this appendix contains suggestions to help guide you in performing low-level program design, and in writing code.

naturally, these are guidelines and not rules. the idea is to use them as inspirations, and to remember that there are occasional situations where you need to bend or break a rule.

design
1. elegance always pays off. in the short term it might seem like it takes much longer to come up with a truly graceful solution to a problem, but when it works the first time and easily adapts to new situations instead of requiring hours, days, or months of struggle, you’ll see the rewards (even if no one can measure them). not only does it give you a program that’s easier to build and debug, but it’s also easier to understand and maintain, and that’s where the financial value lies. this point can take some experience to understand, because it can appear that you’re not being productive while you’re making a piece of code elegant. resist the urge to hurry; it will only slow you down.





1. first make it work, then make it fast. this is true even if you are certain that a piece of code is really important and that it will be a principal bottleneck in your system. don’t do it. get the system going first with as simple a design as possible. then if it isn’t going fast enough, profile it. you’ll almost always discover that “your” bottleneck isn’t the problem. save your time for the really important stuff.

2. remember the “divide and conquer” principle. if the problem you’re looking at is too confusing, try to imagine what the basic operation of the program would be, given the existence of a magic “piece” that handles the hard parts. that “piece” is an object—write the code that uses the object, then look at the object and encapsulate its hard parts into other objects, etc.

3. separate the class creator from the class user (client programmer). the class user is the “customer” and doesn’t need or want to know what’s going on behind the scenes of the class. the class creator must be the expert in class design and write the class so that it can be used by the most novice programmer possible, yet still work robustly in the application. library use will be easy only if it’s transparent.

4. when you create a class, attempt to make your names so clear that comments are unnecessary. your goal should be to make the client programmer’s interface conceptually simple. to this end, use method overloading when appropriate to create an intuitive, easy-to-use interface.

5. your analysis and design must produce, at minimum, the classes in your system, their public interfaces, and their relationships to other classes, especially base classes. if your design methodology produces more than that, ask yourself if all the pieces produced by that methodology have value over the lifetime of the program. if they do not, maintaining them will cost you. members of development teams tend not to maintain anything that does not contribute to their productivity; this is a fact of life that many design methods don’t account for.

6. automate everything. write the test code first (before you write the class), and keep it with the class. automate the running of your tests through a makefile or similar tool. this way, any changes can be automatically verified by running the test code, and you’ll immediately discover errors. because you know that you have the safety net of your test framework, you will be bolder about making sweeping changes when you discover the need. remember that the greatest improvements in languages come from the built-in testing provided by type checking, exception handling, etc., but those features take you only so far. you must go the rest of the way in creating a robust system by filling in the tests that verify features that are specific to your class or program.

7. write the test code first (before you write the class) in order to verify that your class design is complete. if you can’t write test code, you don’t know what your class looks like. in addition, the act of writing the test code will often flush out additional features or constraints that you need in the class—these features or constraints don’t always appear during analysis and design. tests also provide example code showing how your class can be used.

8. all software design problems can be simplified by introducing an extra level of conceptual indirection. this fundamental rule of software engineering[1] is the basis of abstraction, the primary feature of object-oriented programming.

9. an indirection should have a meaning (in concert with guideline 9). this meaning can be something as simple as “putting commonly used code in a single method.” if you add levels of indirection (abstraction, encapsulation, etc.) that don’t have meaning, it can be as bad as not having adequate indirection.

10. make classes as atomic as possible. give each class a single, clear purpose. if your classes or your system design grows too complicated, break complex classes into simpler ones. the most obvious indicator of this is sheer size: if a class is big, chances are it’s doing too much and should be broken up.
clues to suggest redesign of a class are:
1) a complicated switch statement: consider using polymorphism.
2) a large number of methods that cover broadly different types of operations: consider using several classes.
3) a large number of member variables that concern broadly different characteristics: consider using several classes.

11. watch for long argument lists. method calls then become difficult to write, read, and maintain. instead, try to move the method to a class where it is (more) appropriate, and/or pass objects in as arguments.

12. don’t repeat yourself. if a piece of code is recurring in many methods in derived classes, put that code into a single method in the base class and call it from the derived-class methods. not only do you save code space, you provide for easy propagation of changes. sometimes the discovery of this common code will add valuable functionality to your interface.

13. watch for switch statements or chained if-else clauses. this is typically an indicator of type-check coding, which means you are choosing what code to execute based on some kind of type information (the exact type may not be obvious at first). you can usually replace this kind of code with inheritance and polymorphism; a polymorphic method call will perform the type checking for you, and allow for more reliable and easier extensibility.

14. from a design standpoint, look for and separate things that change from things that stay the same. that is, search for the elements in a system that you might want to change without forcing a redesign, then encapsulate those elements in classes. you can learn significantly more about this concept in thinking in patterns with java, downloadable at www.bruceeckel.com.

15. don’t extend fundamental functionality by subclassing. if an interface element is essential to a class it should be in the base class, not added during derivation. if you’re adding methods by inheriting, perhaps you should rethink the design.

16. less is more. start with a minimal interface to a class, as small and simple as you need to solve the problem at hand, but don’t try to anticipate all the ways that your class might be used. as the class is used, you’ll discover ways you must expand the interface. however, once a class is in use you cannot shrink the interface without disturbing client code. if you need to add more methods, that’s fine; it won’t disturb code, other than forcing recompiles. but even if new methods replace the functionality of old ones, leave the existing interface alone (you can combine the functionality in the underlying implementation if you want). if you need to expand the interface of an existing method by adding more arguments, create an overloaded method with the new arguments; this way you won’t disturb any existing calls to the existing method.

17. read your classes aloud to make sure they’re logical. refer to the relationship between a base class and derived class as “is-a” and member objects as “has-a.”

18. when deciding between inheritance and composition, ask if you need to upcast to the base type. if not, prefer composition (member objects) to inheritance. this can eliminate the perceived need for multiple base types. if you inherit, users will think they are supposed to upcast.

19. use data members for variation in value and method overriding for variation in behavior. that is, if you find a class that uses state variables along with methods that switch behavior based on those variables, you should probably redesign it to express the differences in behavior within subclasses and overridden methods.

20. watch for overloading. a method should not conditionally execute code based on the value of an argument. in this case, you should create two or more overloaded methods instead.

21. use exception hierarchies—preferably derived from specific appropriate classes in the standard java exception hierarchy. the person catching the exceptions can then catch the specific types of exceptions, followed by the base type. if you add new derived exceptions, existing client code will still catch the exception through the base type.

22. sometimes simple aggregation does the job. a “passenger comfort system” on an airline consists of disconnected elements: seat, air conditioning, video, etc., and yet you need to create many of these in a plane. do you make private members and build a whole new interface? no—in this case, the components are also part of the public interface, so you should create public member objects. those objects have their own private implementations, which are still safe. be aware that simple aggregation is not a solution to be used often, but it does happen.

23. consider the perspective of the client programmer and the person maintaining the code. design your class to be as obvious as possible to use. anticipate the kind of changes that will be made, and design your class so that those changes will be easy.

24. watch out for “giant object syndrome.” this is often an affliction of procedural programmers who are new to oop and who end up writing a procedural program and sticking it inside one or two giant objects. with the exception of application frameworks, objects represent concepts in your application, not the application.





25. if you must do something ugly, at least localize the ugliness inside a class.





26. if you must do something nonportable, make an abstraction for that service and localize it within a class. this extra level of indirection prevents the nonportability from being distributed throughout your program. (this idiom is embodied in the bridge pattern).

27. objects should not simply hold some data. they should also have well-defined behaviors. (occasionally, “data objects” are appropriate, but only when used expressly to package and transport a group of items when a generalized container is innappropriate.)





28. choose composition first when creating new classes from existing classes. you should only used inheritance if it is required by your design. if you use inheritance where composition will work, your designs will become needlessly complicated.





29. use inheritance and method overriding to express differences in behavior, and fields to express variations in state. an extreme example of what not to do is inheriting different classes to represent colors instead of using a “color” field.





30. watch out for variance. two semantically different objects may have identical actions, or responsibilities, and there is a natural temptation to try to make one a subclass of the other just to benefit from inheritance. this is called variance, but there’s no real justification to force a superclass/subclass relationship where it doesn’t exist. a better solution is to create a general base class that produces an interface for both as derived classes—it requires a bit more space, but you still benefit from inheritance, and will probably make an important discovery about the design.





31. watch out for limitation during inheritance. the clearest designs add new capabilities to inherited ones. a suspicious design removes old capabilities during inheritance without adding new ones. but rules are made to be broken, and if you are working from an old class library, it may be more efficient to restrict an existing class in its subclass than it would be to restructure the hierarchy so your new class fits in where it should, above the old class.

32. use design patterns to eliminate “naked functionality.” that is, if only one object of your class should be created, don’t bolt ahead to the application and write a comment “make only one of these.” wrap it in a singleton. if you have a lot of messy code in your main program that creates your objects, look for a creational pattern like a factory method in which you can encapsulate that creation. eliminating “naked functionality” will not only make your code much easier to understand and maintain, it will also make it more bulletproof against the well-intentioned maintainers that come after you.





33. watch out for “analysis paralysis.” remember that you must usually move forward in a project before you know everything, and that often the best and fastest way to learn about some of your unknown factors is to go to the next step rather than trying to figure it out in your head. you can’t know the solution until you have the solution. java has built-in firewalls; let them work for you. your mistakes in a class or set of classes won’t destroy the integrity of the whole system.

34. when you think you’ve got a good analysis, design, or implementation, do a walkthrough. bring someone in from outside your group—this doesn’t have to be a consultant, but can be someone from another group within your company. reviewing your work with a fresh pair of eyes can reveal problems at a stage when it’s much easier to fix them, and more than pays for the time and money “lost” to the walkthrough process.

implementation
35. in general, follow the microsoft coding conventions. these are available at
#ref# (the code in this book follows these conventions as much as i was able). these are used for what constitutes arguably the largest body of code that the largest number of c# programmers will be exposed to. if you doggedly stick to the coding style you’ve always used, you will make it harder for your reader. whatever coding conventions you decide on, ensure they are consistent throughout the project.





36. whatever coding style you use, it really does make a difference if your team (and even better, your company) standardizes on it. this means to the point that everyone considers it fair game to fix someone else’s coding style if it doesn’t conform. the value of standardization is that it takes less brain cycles to parse the code, so that you can focus more on what the code means.





37. follow standard capitalization rules. capitalize the first letter of class names and non-private methods and properties. the first letter of private fields, methods, and objects (references) should be lowercase. all identifiers should run their words together, and capitalize the first letter of all intermediate words. for example:
thisisaclassname
thisisaprivatemethodorfieldname
capitalize all the letters of static final primitive identifiers that have constant initializers in their definitions. this indicates they are compile-time constants.

38. don’t create your own “decorated” private data member names. this is usually seen in the form of prepended underscores and characters. hungarian notation is the worst example of this, where you attach extra characters that indicate data type, use, location, etc., as if you were writing assembly language and the compiler provided no extra assistance at all. these notations are confusing, difficult to read, and unpleasant to enforce and maintain. let classes and packages do the name scoping for you.

39. follow a “canonical form” when creating a class for general-purpose use. include definitions for equals( ), hashcode( ), tostring( ), clone( ) (implement cloneable), and implement comparable and serializable.





40. use the javabeans “get,” “set,” and “is” naming conventions for methods that read and change private fields, even if you don’t think you’re making a javabean at the time. not only does it make it easy to use your class as a bean, but it’s a standard way to name these kinds of methods and so will be more easily understood by the reader.





41. for each class you create, consider including a static public test( ) that contains code to test that class. you don’t need to remove the test code to use the class in a project, and if you make any changes you can easily rerun the tests. this code also provides examples of how to use your class.





42. sometimes you need to inherit in order to access protected members of the base class. this can lead to a perceived need for multiple base types. if you don’t need to upcast, first derive a new class to perform the protected access. then make that new class a member object inside any class that needs to use it, rather than inheriting.

43. if two classes are associated with each other in some functional way (such as containers and iterators), try to make one an inner class of the other. this not only emphasizes the association between the classes, but it allows the class name to be reused within a single package by nesting it within another class.





44. anytime you notice classes that appear to have high coupling with each other, consider the coding and maintenance improvements you might get by using inner classes. the use of inner classes will not uncouple the classes, but rather make the coupling explicit and more convenient.





45. don’t fall prey to premature optimization. this way lies madness. in particular, don’t worry about writing (or avoiding) native methods, making some methods final, or tweaking code to be efficient when you are first constructing the system. your primary goal should be to prove the design, unless the design requires a certain efficiency.

46. keep scopes as small as possible so the visibility and lifetime of your objects are as small as possible. this reduces the chance of using an object in the wrong context and hiding a difficult-to-find bug. for example, suppose you have a container and a piece of code that iterates through it. if you copy that code to use with a new container, you may accidentally end up using the size of the old container as the upper bound of the new one. if, however, the old container is out of scope, the error will be caught at compile-time.

47. use the containers in the .net framework sdk. become proficient with their use and you’ll greatly increase your productivity.

48. for a program to be robust, each component must be robust. use all the tools provided by c#: access control, exceptions, type checking, and so on, in each class you create. that way you can safely move to the next level of abstraction when building your system.

49. prefer compile-time errors to run-time errors. try to handle an error as close to the point of its occurrence as possible. prefer dealing with the error at that point to throwing an exception. catch any exceptions in the nearest handler that has enough information to deal with them. do what you can with the exception at the current level; if that doesn’t solve the problem, rethrow the exception.

50. watch for long method definitions. methods should be brief, functional units that describe and implement a discrete part of a class interface. a method that is long and complicated is difficult and expensive to maintain, and is probably trying to do too much all by itself. if you see such a method, it indicates that, at the least, it should be broken up into multiple methods. it may also suggest the creation of a new class. small methods will also foster reuse within your class. (sometimes methods must be large, but they should still do just one thing.)





51. keep things as “private as possible.” once you publicize an aspect of your library (a method, a class, a field), you can never take it out. if you do, you’ll wreck somebody’s existing code, forcing them to rewrite and redesign. if you publicize only what you must, you can change everything else with impunity, and since designs tend to evolve this is an important freedom. in this way, implementation changes will have minimal impact on derived classes. privacy is especially important when dealing with multithreading—only private fields can be protected against un-synchronized use.





52. use comments liberally, and use the comment-documentation syntax to produce your program documentation. however, the comments should add geniune meaning to the code; comments that only reiterate what the code is clearly expressing are annoying. note that the typical verbose detail of java class and method names reduce the need for as many comments.





53. avoid using “magic numbers”—which are numbers hard-wired into code. these are a nightmare if you need to change them, since you never know if “100” means “the array size” or “something else entirely.” instead, create a constant with a descriptive name and use the constant identifier throughout your program. this makes the program easier to understand and much easier to maintain.





54. when creating constructors, consider exceptions. in the best case, the constructor won’t do anything that throws an exception. in the next-best scenario, the class will be composed and inherited from robust classes only, so they will need no cleanup if an exception is thrown. otherwise, you must clean up composed classes inside a finally clause. if a constructor must fail, the appropriate action is to throw an exception, so the caller doesn’t continue blindly, thinking that the object was created correctly.





55. if your class requires any cleanup when the client programmer is finished with the object, make your class implement idisposable tk.





56. when you are creating a fixed-size container of objects, transfer them to an array—especially if you’re returning this container from a method. this way you get the benefit of the array’s compile-time type checking, and the recipient of the array might not need to cast the objects in the array in order to use them.





57. choose interfaces over abstract classes. if you know something is going to be a base class, your first choice should be to make it an interface, and only if you’re forced to have method definitions or member variables should you change it to an abstract class. an interface talks about what the client wants to do, while a class tends to focus on (or allow) implementation details.





58. inside constructors, do only what is necessary to set the object into the proper state. actively avoid calling other methods (except for final methods) since those methods can be overridden by someone else to produce unexpected results during construction. (see chapter 7 for details.) smaller, simpler constructors are less likely to throw exceptions or cause problems.





59. watch out for accidental overloading. if you attempt to override a base-class method and you don’t quite get the spelling right, you’ll end up adding a new method rather than overriding an existing method. however, this is perfectly legal, so you won’t get any error message from the compiler or run-time system—your code simply won’t work correctly.





60. watch out for premature optimization. first make it work, then make it fast—but only if you must, and only if it’s proven that there is a performance bottleneck in a particular section of your code. unless you have used a profiler to discover a bottleneck, you will probably be wasting your time. the hidden cost of performance tweaks is that your code becomes less understandable and maintainable.





remember that code is read much more than it is written. clean designs make for easy-to-understand programs, but comments, detailed explanations, and examples are invaluable. they will help both you and everyone who comes after you. if nothing else, the frustration of trying to ferret out useful information from the online java documentation should convince you
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表