答:
Read SICP and learn Scheme, and the practical idea of abstract data types. Then coding in C is easy (since with SICP, a bit of C, and a bit of PHP, Ruby, etc... your thinking would be widen enough, and you would understand that object oriented programming might not be the best style in all cases, but only for some kind of programs). Be careful about C dynamic memory allocation, which is probably the hardest part. The C99 or C11 programming language standard and its C standard library is actually quite poor (it does not know about TCP or directories!), and you'll often need some external libraries or interfaces (e.g. POSIX, libcurl for HTTP client library, libonion for HTTP server library, GMPlib for bignums, some library like libunistring for UTF-8, etc...).

Your "objects" are often in C some related struct-s, and you define the set of functions operating on them. For short or very simple functions, consider defining them, with the relevant struct,  as static inline in some header file foo.h to be #include-d elsewhere.

Notice that object oriented programming is not the only programming paradigm. In some occasions, other paradigms are worthwhile (functional programming à la Ocaml or Haskell or even Scheme or Commmon Lisp, logic programming à la Prolog, etc etc... Read also J.Pitrat's blog about declarative artificial intelligence). See Scott's book: Programming Language Pragmatics

Actually, a programmer in C, or in Ocaml, usually does not want to code in an object oriented programming style. There is no reason to force yourself to think of objects when that is not useful.

You'll define some struct and the functions operating on them (often thru pointers). You could need some tagged unions (often, a struct with a tag member, often some enum,  and some union inside), and you might find useful to have a flexible array member at the end of some of your struct-s.

Look inside the source code of some existing free software in C (see github & sourceforge
to find some). Probably, installing and using a Linux distribution would be useful: it is made almost only of free software, it has great free software C compilers (GCC, Clang/LLVM) and development tools. See also Advanced Linux Programming if you want to develop for Linux.

Don't forget to compile with all warnings and debug info, e.g. gcc -Wall -Wextra -g -notably during the development & debugging phases- and learn to use some tools, e.g. valgrind to hunt memory leaks, the gdb debugger, etc. Take care to understand well what is undefined behavior and strongly avoid it (remember that a program could have some UB and sometimes seem to "work").

When you genuinely need object oriented constructs (in particular inheritance) you can use pointers to related structures and to functions. You could have your own vtable machinery, have each "object" starting with a pointer to a struct containing function pointers. You take advantage of the ability to cast a pointer type to another pointer type (and of the fact that you can cast from a struct super_st containing the same field types as those starting a struct sub_st to emulate inheritance). Notice that C is enough to implement quite sophisticated object systems -in particular by following some conventions-, as GObject (from GTK/Gnome) demonstrates.

When you genuinely need closures, you'll often emulate them with callbacks, with the convention that every function using a callback is passed both a function pointer and some client data (consumed by the function pointer when it calls that). You could also have (conventionally) your own closure-like struct-s (containing some function pointer and the closed values).

Since C is a very low level language, it is important to define and document your own conventions (inspired by the practice in other C programs), in particular about memory management, and probably some naming conventions also. It is useful to have some idea about instruction set architecture. Don't forget that a C compiler may do lots of optimizations on your code (if you ask it to), so don't care too much about doing micro-optimizations by hand, leave that to your compiler (gcc -Wall -O2 for optimized compilation of released software). If you care about benchmarking and raw performance, you should enable optimizations (once your program has been debugged).

Don't forget that sometimes metaprogramming is useful. Quite often, large software written in C contain some scripts or ad-hoc programs to generate some C code used elsewhere (and you might also play some dirty C preprocessor tricks, e.g. X-macros). There exists some useful C program generators (e.g. yacc or gnu bison to generate parsers, gperf to generate perfect hash functions, etc...). On some systems (notably Linux & POSIX) you could even generate some C code at runtime in generated-001.c file, compile it to a shared object by running some command (like gcc -O -Wall -shared -fPIC generated-001.c -o generated-001.so) at runtime, dynamically load that shared object using dlopen & get a function pointer from a name using dlsym. I'm doing such tricks in MELT (a Lisp-like domain specific language which might be useful to you, since it enables customization of the GCC compiler).

Be aware of garbage collection concepts and techniques (reference counting is often a technique to manage memory in C, and it is IMHO a poor form of garbage collection which does not deal well with circular references; you could have weak pointers to help about that, but it might be tricky). On some occasions, you might consider using Boehm's conservative garbage collector.


问:
What is the minimum practical definition for the Scheme language?
What is the smallest practical set of primitives that can be used to define the Scheme language?

For example, map can be defined as

```<code>(define (map proc lis)
   (cond ((null? lis)
          '())
         ((pair? lis)
          (cons (proc (car lis))
                (map proc (cdr lis))))))
</code>```

Can the functions in this definition be similarly reduced to smaller primitives?

答:
I strongly suggest reading Queinnec's book Lisp In Small Pieces, it has several chapters to answer your question, taking into account your practicality request (without which some bare lambda-calculus would be enough); it also goes from simplistic mini-scheme interpreter (as an implementation of eval) to a complete Lisp-like compiler (to bytecode and to C).

Your question needs an entire book to be answered, and Queinnec's book is that book.

ContentLicense: CC BY-SA 3.0


问:
Algorithm to detect if a word is spelled correctly
I am trying to develop a javascript spellchecker that doesn't use a dictionary, and can correctly, given a single word, detect if a word is spelled correctly or not. Right now, I just have a list of sub strings that never occur within words, and if the word contains one of those sub strings, I count it as misspelled. For example, I would have a substring "lll", and if a word contains "lll" it would be counted as misspelled (such as "I'lll").

However, I'm finding this doesn't work as well as expected. Most misspelled words seem to involve letters in the wrong order, or words that don't follow common rules. The above approach doesn't work for either of these issues. For example, there is no good substring for the spelling "accidant".

I'm looking for a more effective method of determining if a word is probably misspelled or not, ideally something that solves the issues of letters in incorrect order and keys near the correct letter on a keyboard accidentally being pressed (but solutions to other common causes of misspellings are fine).

This is english-only, so it doesn't need to work with other languages.
Also, false positives are a much larger problem for me than false negatives, so I would prefer to err on the side of saying words are spelled correctly when in fact they are not.

答:
Simple heuristics like "no triples" and similar should be safe, and there may be others like that which you should add, but they'll catch only a few of the possible errors. For the rest, you won't get far without having a store of as many words as possible.

The best way I know of compressing dictionaries losslessly while still having fast lookup, is a DAWG/MA-FSA, see http://stevehanov.ca/blog/index.php?id=115 (and the intros to tries on that same site) for a friendly introduction. The main attraction with the DAWG is that you can very quickly check if something is misspelt, while typically using less memory than a hash table would.

You can also store these on-disk (or send them over the network) using 4 bytes per labelled edge. Taking only the 63001 words matching ^[a-z]+$ from the English aspell dictionary /usr/share/dict/words, I get 49829 edges, which should be possible to store in ~194K – not much larger than angular.js ;-) But on the other hand, if you have mod_deflate on your server, gzip handles the a-z's in 163K (you might also find http://pieroxy.net/blog/pages/lz-string/index.html interesting).

Read also http://norvig.com/spell-correct.html if you haven't already.

But then you say you want to err on the side of false negatives; that's going to be harder if you don't want to include a big dictionary. You can of course skip checking any word matching [^a-z] if you know that your dictionary only has the a-z's. And you can stick with single-edit-distance errors (since higher-edit-distance is more likely to be false positives).

Another alternative, if you want to go all the way on "false-negatives-only", is to find a big list of common spelling errors, and simply use that instead of a list of correct words. That'll be very "undynamic", but if you work from frequency (priorities the most frequent errors), it might end up being a bit useful. You can also pre-spell your expected input, if you already know a lot about what kind of text will be written; e.g. if you want to make a speller for a forum where people talk about a specific subject, you can first scrape all the text in that forum, then run it through aspell and catch all the errors (and suggestions), and only store the top N of those.


问:
How to think as a C programmer after biased with OOP language?
Previously, I've only used Object Oriented Programming languages (C++, Ruby, Python, PHP), and am now learning C. I'm finding it difficult to figure out the proper way to do things in a language with no concept of an 'Object'. I realize that it's possible to use OOP paradigms in C, but I'd like to learn the C-idiomatic way.

When solving a programming problem, the first thing I do is to imagine an object that will solve the problem. What steps do I replace this with, when using a non-OOP Imperative Programming paradigm?

答: One of the big reasons people are encouraged to learn C is that's it's one of the lowest of the high-level programming languages. OOP languages make it easier to think about data models and templating code and message passing, but at the end of the day, a microprocessor executes code step-by-step, jumping in and out of blocks of code (functions in C) and moving references to variables (pointers in C) around so that different parts of a program can share data. Think of C as assembly language in English -- providing step by step instructions to your computer's microprocessor -- and you won't go far wrong. As a bonus, most operating system interfaces work like C function calls rather than OOP paradigms, so learning C will also tell you a lot about how code execution moves from one program (the OS) to another (your program) and back again.</p>


问:
Function wrappers with no args: bad practice?
My colleague likes to write classes containing methods looking like this:

```<code>public function doTaskA()
{
    return $this->doTask('A');
}
public function doTaskB()
{
    return $this->doTask('B');
}
private function doTask($task)
{
    ...
</code>```

I say this is bad practice, and would prefer to just make the doTask method public. I think if you really feel it is necessary to hardcode the possible values of $task in the class, then just make them class constants and call doTask(self::TASK_A) rather than writing a new function purely as a wrapper.

The worst case I saw of this, was a class with more than a dozen of these wrappers, and the doTask method was barely twenty lines long.

So, is this actually bad practice? Or is it just a matter of style? Or am I wrong, and it is actually considered good practice, as he insists?

答:
It depends on scenarios.

Multiple Identical Calls

Consider having do to a particular task a number of times throughout your code. Doing foo.doTask(args) might get tedious. Having to provide the arguments each time, can also be error prone. Having a wrapper which wraps it up for you can be convenient and also less error prone. Also, imagine if you need to change the value of one of the arguments in that function, you will have to go through all the calls and make multiple changes. Using the wrapper approach will mean that the change will be localised.

Mutliple Slightly Different calls

On the other end of the spectrum, having a lot of slightly different wrappers, one for each possible type, can yield too many wrappers which eventually just confuse the user of your API. Changing the code might be confusing since you might not be quite so sure about what you want to change.

In either case though, wrappers should be useful if you need to provide controlled access to your methods, so that is another thing you would need to keep in mind.


问:
Are hex dump and binary-to-text encoding related or different things?
Binary-to-text encoding is to represent binary data as characters.

Hex dump of binary files seem also do the same for reading binary files.

Are they related or different things?

答:
A hex dump will have characters 0..9 and A..F, one byte becomes a pair of characters.

binary to text has characters 0..9, A..Z and a..z and punctuation etc.
Text will often include simple compression eg 3 bytes can be split into 4 characters. But more complex compression eg LZMA can be used as well.


问:
Name of data structure that's tree-like with multiple root nodes
I'm attempting to implement a data structure, and using a more traditional tree data structure, but I'm not using the root node as it holds no real value in the context I'm using it in.

Ideally, I want to use a structure that is a tree, but that has multiple root nodes (and that is not just a list of trees). Is there a name for a data structure like this?

答: Try for Forest Data structure using Java Programming. I have done this already and it's easy. As Java API contains no general API for trees/graphs, since there is no unique set of features needed in every use case. There are quite some tree/graph-like APIs for special cases, though.And it is easy to make your own graph - one could even say that every object is in fact a node in a graph, with the values of its reference type fields being the (outgoing) neighbors. I had even implemented search using hashing techniques to find the immediate parent and immediate child node, if exists.</p>


答:
I wouldn't say this is bad practice as a general rule, but it does lean away from flexible programming practices such as use of dependency injection.

If the 'dependencies' of a class or function can be passed in as arguments, it makes the class / function more re-useable, easier to refactor, and less of a black box to the programmer who has to use the class. I've found that adhering to this style throughout a project leads to flexible and maintainable code.

Never say never or always in programming, but I think you can make a reasonable argument for steering colleagues away from this style of coding.

npinti's argument also holds. If you find yourself calling the same function with the same parameters over and over, and an IoC container (see dependency injection above) can't do this work for you, then you may want to wrap it with a dedicated function, though the name should clearly indicate that it is a variation on the more general function which accepts parameters.

Title: Function wrappers with no args: bad practice?

Body:
My colleague likes to write classes containing methods looking like this:

```<code>public function doTaskA()
{
    return $this->doTask('A');
}
public function doTaskB()
{
    return $this->doTask('B');
}
private function doTask($task)
{
    ...
</code>```

I say this is bad practice, and would prefer to just make the doTask method public. I think if you really feel it is necessary to hardcode the possible values of $task in the class, then just make them class constants and call doTask(self::TASK_A) rather than writing a new function purely as a wrapper.

The worst case I saw of this, was a class with more than a dozen of these wrappers, and the doTask method was barely twenty lines long.

So, is this actually bad practice? Or is it just a matter of style? Or am I wrong, and it is actually considered good practice, as he insists?


问:
hashing algorithm to check inclusion in a set
The problem I am trying to solve is to validate if a username is already used before allowing an admin user to create a new user with that username.

Currently I am doing an ajax request to check if the username is taken. This can cause a lag that detracts from the user experience - especially as they are encouraged to create more than 30 usernames at once during the onboarding process.

I wonder if there is a hashing algorithm that allows the backend to construct a string that the frontend can use to check if a new username is in the set.

e.g.,:

on the backend

```<code>usernames_set = jim, carl, fred
my_hash = generate_hash(usernames_set) // returns e.g., 23223edw3234fcvdvc
# now pass this hash to the frontend.
</code>```

on the frontend

```<code>checkValueInHash('jim') // returns true
checkValueInHash('nigel') // returns false
</code>```

I appreciate I can simply pass the set of usernames to the frontend, but this would become infeasible as the number of items in the set becomes thousands. Also, there is security implications of proving a list of valid usernames.

Note I indent to solve the consistency problem (what happens when new users are created after the hash is sent to the frontend?) by using websockets to push a new string when new users are created.

Also note I appreciate I reduce this problem by sending username checks in bulk,  but I would like to understand what other options are available too.

答: My current thinking is using a bloom filter: add all usernames to bloom filter on backend, compress the bits from the bloom filter and pass to frontend, inflate and populate a frontend bloom filter.</p>


问:
how can the presenter or view interact with the model in the MVP pattern?
I'm learning the MV* patterns. MVP in this case. I'm trying to refactor an old android application into the MVP pattern to make things less tightly coupled, but I'm struggling one one concept. I know that the presenter get's data from the domain layer which connects through the data layer, but how can the view communicate with the data, directly or indirectly? here's an example of what I'm trying to figure out:

I've got a long running download service (I assume this should be in the data layer) that needs to be started or stopped depending on user interaction in the UI. How would I communicate those signals to the service in the data layer? should I do that through the domain layer?

from what I've seen it looks like the UI can not talk back to the data or domain layers.

If someone would be willing to explain this to me I'd be very grateful.

here are some of the articles I'm working off of:
first resource |
second resource |
third resource

答:
In both MVP flavours, Passive View and Supervising Controller, the presenter handles the input logic and other complex view logic. So the download control logic should definitely go into the presenter.

In a typical Java setting (I assume Android is similar), you can register event handlers with the widgets. So you can pass the interaction from the view to the presenter in two ways:

The presenter registers itself as event handler to the widget. This requires either direct access from the presenter to the widget (not so good for loose coupling) or a public method on the view. I see this as a bit cumbersome.

Register an anonymous event handler within the view class and call a presenter method to further handle the event. This is my preferred way. Some pseudo-code:

```<code>downloadStopButton.addSelectionHandler(new Selectionhandler() {
    handleEvent(Event e) {
        presenter.downloadStopCalled();
    }
});
</code>```

In both cases, the presenter then instructs the model or service layer to stop the download. If you have some state related to the download in a model, and the model knows about the service, then you can go through the model. Otherwise I think just calling a service from the presenter is also ok.

Body:
In both MVP flavours, Passive View and Supervising Controller, the presenter handles the input logic and other complex view logic. So the download control logic should definitely go into the presenter.

In a typical Java setting (I assume Android is similar), you can register event handlers with the widgets. So you can pass the interaction from the view to the presenter in two ways:

The presenter registers itself as event handler to the widget. This requires either direct access from the presenter to the widget (not so good for loose coupling) or a public method on the view. I see this as a bit cumbersome.

Register an anonymous event handler within the view class and call a presenter method to further handle the event. This is my preferred way. Some pseudo-code:

downloadStopButton.addSelectionHandler(new Selectionhandler() {
    handleEvent(Event e) {
        presenter.downloadStopCalled();
    }
});

In both cases, the presenter then instructs the model or service layer to stop the download. If you have some state related to the download in a model, and the model knows about the service, then you can go through the model. Otherwise I think just calling a service from the presenter is also ok.


问:
Best way to organise the software for microcontroller external peripheral drivers
Recently, I have begun designing and writing code for microcontrollers in order to get a deeper understanding of how they work. The first major project I have undertaken involves writing a driver for the trusty Hitachi HD44780 LCD controller. In no time at all, I was able to implement a communication interface with the LCD and all the defined LCD commands. I am happy with the basic driver, I'm sure it follows convention. It uses a layered top-down approach such that there is a well defined public interface and the bottom layer contains the only functions to talk to the GPIO hardware.

However, I have started to implement advanced features such a vertical shifting/scrolling, animations etc. Implementation so far has been done within a single module which is good because it keeps all the functions together and the user of the driver can just call the functions provided to him/her. The downside of this is the driver is becoming more complex to maintain which tells me that I may need to break it up rather than pursue monolithic design.

I'm thinking of creating another module just for say vertical scrolling. The public interface will contain the data structure and functions required to perform scrolling which is all handled by main. Is this a valid approach or am I missing something completely?

When I say module, I am talking about a group of inter-related functions. My understanding is that a driver is a module for controlling a bit of hardware but module doesn't necessarily mean driver e.g. C string library.

答:
Drivers are frequently split into several layers.  Something as "simple" as a mouse driver has separate modules for:

Different USB specifications:  1.0, 2.0, etc.

Specific USB controller chips.

HID devices.

USB mice.

All mice at kernel level.

Equivalent implementations of the above for PS/2 and serial mice.

Windowing system mouse driver (Xorg, etc.)

Graphical toolkit mouse API (GTK, QT, etc.)

It's certainly reasonable to split your driver based on level of abstraction, or what is likely to change together.  Things like buffering, scrolling, formatting, wrapping, and animation can and should be split off and worked separately, using only the public API of the layers below.


答:
C APIs often -- perhaps even, usually -- do have an essentially object oriented interface if you look at them the right way.

In C++:

```<code>class foo {
    public:
        foo (int x);
        void bar (int param);
    private:
        int x;
};

// Example use:
foo f(42);
f.bar(23);
</code>```

In C:

```<code>typedef struct {
    int x;
} foo;

void bar (foo*, int param);

// Example use:
foo f = { .x = 42 };
bar(&f, 23);
</code>```

As you may be aware, in C++ and various other formal OO languages, under the hood an object method takes a first argument that is a pointer to the object, much like the C version of bar() above.  For an example of where this comes to the surface in C++, consider how std::bind can be used to fit object methods to function signatures:

```<code>new function<void(int)> (
    bind(&foo::bar, this, placeholders::_1)
//                  ^^^^ object pointer as first arg
);
</code>```

As others have pointed out, the real difference is that formal OO languages may implement polymorphism, access control, and various other nifty features.  But the essence of object oriented programming, the creation and manipulation of discrete, complex data structures, is already a fundamental practice in C.

Title: How to think as a C programmer after biased with OOP language?

Body:
Previously, I've only used Object Oriented Programming languages (C++, Ruby, Python, PHP), and am now learning C. I'm finding it difficult to figure out the proper way to do things in a language with no concept of an 'Object'. I realize that it's possible to use OOP paradigms in C, but I'd like to learn the C-idiomatic way.

When solving a programming problem, the first thing I do is to imagine an object that will solve the problem. What steps do I replace this with, when using a non-OOP Imperative Programming paradigm?

Body:
C APIs often -- perhaps even, usually -- do have an essentially object oriented interface if you look at them the right way.

In C++:

class foo {
    public:
        foo (int x);
        void bar (int param);
    private:
        int x;
};

// Example use:
foo f(42);
f.bar(23);

In C:

typedef struct {
    int x;
} foo;

void bar (foo*, int param);

// Example use:
foo f = { .x = 42 };
bar(&f, 23);

As you may be aware, in C++ and various other formal OO languages, under the hood an object method takes a first argument that is a pointer to the object, much like the C version of bar() above.  For an example of where this comes to the surface in C++, consider how std::bind can be used to fit object methods to function signatures:

new function<void(int)> (
    bind(&foo::bar, this, placeholders::_1)
//                  ^^^^ object pointer as first arg
);

As others have pointed out, the real difference is that formal OO languages may implement polymorphism, access control, and various other nifty features.  But the essence of object oriented programming, the creation and manipulation of discrete, complex data structures, is already a fundamental practice in C.


问:
How large is ok for a Class?
I’m a long time developer (I’m 49) but rather new to object oriented development. I’ve been reading about OO since Bertrand Meyer’s Eiffel, but have done really little OO programming.

The point is every book on OO design starts with an example of a boat, car or whatever common object we use very often, and they start adding attributes and methods, and explaining how they model the state of the object and what can be done with it.

So they usually go something like "the better the model the better it represents the object in the application and the better it all comes out".

So far so good, but, on the other hand, I’ve found several authors that give recipes such as “a class should fit in just a single page” (I would add “on what monitor size?" now that we try not to print code!).

Take for example a PurchaseOrder class, that has a finite state machine controlling its behavior and a collection of PurchaseOrderItem, one of the arguments here at work is that we should use a PurchaseOrder simple class, with some methods (little more than a data class), and have a PurchaseOrderFSM “expert class” that handles the finite state machine for the PurchaseOrder.

I would say that falls in the “Feature Envy” or “Inappropriate Intimacy” classification of Jeff Atwood's Code Smells post on Coding Horror. I’d just call it common sense. If I can issue, approve or cancel my real purchase order, then the PurchaseOrder class should have issuePO, approvePO and cancelPO methods.

Doesn’t that goes with the “maximize cohesion” and “minimize coupling” age old principles that I understand as cornerstones of OO?

Besides, doesn’t that helps toward the maintainability of the class?

答:
Large enough to contain all the necessary logic to perform it's job.

Small enough to be maintainable and follow the Single Responsibility Principle.

Title: How large is ok for a Class?


问:
How many applications should you provide to cover all sort of mobile phones
At the moment we have:

Iphone

Android

J2me touch

J2me non-touch

J2me touch for Blackberry

J2me non-touch for Blackberry

We were thinking of making another

J2me non-touch for crappy devices (because the regular non-touch is just to heavy)

The question is, can you think of any other versions of our application that we should provide to target 'ALL' mobile phones

答:
Windows Mobile 6.5

Windows Phone 7

Native Symbian? But maybe the J2ME version
is enough for that platform.

ContentLicense: CC BY-SA 2.5


问:
Class becoming God Object what pattern to use
I am developing Android app and my MainActivity is becoming God Object.

By the way native Activity class implementation is some sort of God Object already.

The problem is that my activity class is growing and growing.

Let me explain class responsibilites, for those who are not familiar with android.

Activity is like a screen with it's UI, lifecycle, functionality to communicate with OS.

Drawer is part of UI that brings to the activity side menu for navigation in the app.
What is the problem.

```<code>public abstract class MainActivity extends SingleFragmentToolBarActivity<T> implements Drawer.OnDrawerItemClickListener {
    private static final int PROFILE_HEADER_IDENTIFIER = 200;
    private float mDisplayDpWidth;
    private float mDisplayDpHeight;
    private Drawer.Result mNavigationDrawer;
    private AccountHeader.Result mAccountHeader;
    private double mDrawerWidthFactor = 0.9;
    private double mDrawerHeaderHeightFactor = 0.3;
    private IProfile<ProfileDrawerItem> mGuestProfile;
    private IProfile<ProfileDrawerItem> mLoggedInProfile;
    private boolean userIsLogged = false;
    public Drawer.Result getNavigationDrawer() {
        return this.mNavigationDrawer;
    }
    private AccountHeader.Result geAccountHeader() {
        return this.mAccountHeader;
    }
    private static final int PROFILE_SETTING = 1;
    private final AccountHeader.OnAccountHeaderSelectionViewClickListener mHeaderSelectionViewClickListener = new AccountHeader.OnAccountHeaderSelectionViewClickListener(.....);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setUpNavigationDrawer(savedInstanceState);
    }

    private void setUpNavigationDrawer(Bundle savedInstanceState) {
        DrawerImageLoader.init(new DrawerImageLoader.IDrawerImageLoader() {
            @Override
            public void set(ImageView imageView, Uri uri, Drawable placeholder) {
                Picasso.with(imageView.getContext()).load(uri).placeholder(placeholder).into(imageView);
            }

            @Override
            public void cancel(ImageView imageView) {
                Picasso.with(imageView.getContext()).cancelRequest(imageView);
            }

            @Override
            public Drawable placeholder(Context ctx) {
                return null;
            }
        });
        getDisplayMetrics();
        mGuestProfile = buildGuestProfile();
        mAccountHeader = buildNavigationHeader(savedInstanceState);
        mNavigationDrawer = buildDrawer(savedInstanceState);
    }
    protected Drawer.Result buildDrawer(Bundle savedInstanceState) {
     Drawer drawer =  new Drawer(this)
            .withActivity(this);
    ........
    }
    protected List<IProfile> getProfileItemList() {
    ......
    }
    protected AccountHeader.Result buildNavigationHeader(Bundle savedInstanceState) {
    ......
    }
    private ProfileDrawerItem buildGuestProfile() {
        .......
    }
    private ProfileDrawerItem buildLoggedInProfile(UserBean userBean) {
        .......
    }
    private void getDisplayMetrics() {
       .....
    }
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l, IDrawerItem iDrawerItem) {
     ......
    }

    protected Drawer addItemsIntoDrawer(Drawer buildDrawer) {
        ......
    }
    public void setDrawerWidthFactor(double factor) {
      ......
    }
    public void setDrawerHeaderHeightFactor(double factor) {
      ......
    }
</code>```

This is only declaration of some methods and class members.

This code above is ONLY for setting navigation drawer in my MainActivity, there will be quite more code in the future here for communicating with services and so on, if to left this as it is, soon I will get class with millions line of code, tons of class members and ton of methods.

Ho to solve this problem, what pattern can be acceptable in this way.

Setting drawer requires reference to the Activity.

I have some ideas how to solve this problem.

Use strategy pattern create interface with all these methods responsible for setting navigation drawer, but how can I pass reference to the activity into the interface implementation in this case I have to create not interface but abstract class and pass reference to the Activity into it's constructor.

 This will work, but I still think that it is not perfect, clean solution.

Please suggest what can I do to stop class growing.

EDIT

There is only small responsibility of my activity, there will be more important responsibilities in the future, so I have to get rid of writing a lot initialization code. I haven't post body of methods (300 lines of code). I have found one possible way here is to create some abstract class with basic methods and than create implementation and just use it in my activity when I need this.And in this case it will be possible to change it in runtime (before view has been inflated).

答:
You could create list of classes responsible for each operation, where and when it makes sense for example,

```<code>public abstract class MainActivity extends SingleFragmentToolBarActivity<T> implements Drawer.OnDrawerItemClickListener {
    ....

    private void setUpNavigationDrawer(Bundle savedInstanceState) {
        NavigationDrawer drawer = new NavigationDrawer(this,savedInstanceState);
        drawer.setup();
    }
}
</code>```

Here you could move logic for each operation (in this example it's NavigationDrawer) to own class where it takes care of the operation.

Body:
You could create list of classes responsible for each operation, where and when it makes sense for example,

public abstract class MainActivity extends SingleFragmentToolBarActivity<T> implements Drawer.OnDrawerItemClickListener {
    ....

    private void setUpNavigationDrawer(Bundle savedInstanceState) {
        NavigationDrawer drawer = new NavigationDrawer(this,savedInstanceState);
        drawer.setup();
    }
}

Here you could move logic for each operation (in this example it's NavigationDrawer) to own class where it takes care of the operation.


问:
Symfony 2 Multi tenancy architecture, data loaded form front controller/kernel based on subdomain
Hello fellow programmers,

(a bit of background)I'm building a Symfony 2 application for university Student accommodation, when our clients from the university side register with their details a subdomain is created, students belonging to a particular university can access the online accommodation service through this subdomain, there will be several universities that will be registered and each university will have their own subdomain and separate set of related-data/student-data that cannot be accessed from other universities.

(what i have already done) i managed to create a nice login and register pages and also managed to create subdomains by editing the hosts file (with file_put_contents() any better way to do this using symfony?) then i created a service that fetches the UniversityID from the parameters.yml, this way i can get university specific data since all tables have a universityID column.

should i create a script that runs before every thing is loaded that would dynamically update the UniversityID inside the parameters.yml based on the subdomain? what is the best practice for this

In conclusion, what i want from the community is,

1). i'm looking to use the Front controller to load the University Specific data, how do i load/set dynamic data using front controller and/or Kernel

2). how to create subdomains from dynamically without being platform (OS) specific

-thanks

答:
It seems like you're viewing the problem as one of re-configuring your application based on the subdomain it is accessed from.

Given that your university specific data is basically user data - i.e. it will change as users sign up for and use your application, I think a better approach is to store all of that stuff in your database and then create a service for accessing it when you need to, rather than as part of the application startup.

I would write a simple and minimal service that inspects the subdomain and returns the university ID. (You'd need to inject the @request_stack into it (see https://stackoverflow.com/a/20502945/86780), access the hostname of the current request and perform some sort of lookup.)

As for creating subdomains dynamically - I'd suggest that you configure your webserver to work with any subdomain (i.e. *.yourdomain.tld) and have your application figure out whether it's valid or not.

Basically, avoid writing server config dynamically. This approach is likely give you problems when it comes to scaling and tuning your application.


问:
How to handle an aggregated list of the fields of multiple objects?
I have some objects each hold a list of variables, and a list which holds all variables of these objects, for example

```<code>class A
{
   List<Var> varList;
}

class B
{
   List<A>   aList;
   List<Var>   allVarOfAs;
  // it is a common list which holds the members of varList of all members of the aList
}
</code>```

Now if an object from varList in an an object of aList (an A object in B) is removed, how can I update the common list allVarOfAs?

What is the pattern for such situation?

答:
The simplest solution is to NOT have the aggregated list 'allVarOfAs'. Instead make it a method or property which returns the aggregated list on the fly, but doing a SelectMany over aList. E.g.

```<code>IEnumerable<Var> allVarOfAs
{
     get
     {
          return aList.SelectMany(a=>a.varList);
     }
}
</code>```

or

```<code>List<Var> allVarOfAs
{
     get
     {
          return aList.SelectMany(a=>a.varList).ToList();
     }
}
</code>```

Body:
The simplest solution is to NOT have the aggregated list 'allVarOfAs'. Instead make it a method or property which returns the aggregated list on the fly, but doing a SelectMany over aList. E.g.

IEnumerable<Var> allVarOfAs
{
     get
     {
          return aList.SelectMany(a=>a.varList);
     }
}

or

List<Var> allVarOfAs
{
     get
     {
          return aList.SelectMany(a=>a.varList).ToList();
     }
}


答:
First, add some encapsulation and suppose you declare your fields private and define public add and remove methods in class B (which add and remove A instances). Then, add and remove will be respondible for updating allVarOfAs.

The problem with this approach is that as long as any other object has a reference to the same aList (directly, or by having a reference to an A), it can modify it without going throught your B instance. You would have to ensure that no instance of class A is ever shared with other objects, and that A.varList is only modified by a B object (otherwise, the actual union of lists and the one computed in B could differ).

It is simpler and always correct to recompute allVarOfAs when needed (see JacquesB's answer).

Maintaining allVarOfAs could be done incrementally: but do you really need to?

Title: How to handle an aggregated list of the fields of multiple objects?

Body:
I have some objects each hold a list of variables, and a list which holds all variables of these objects, for example

```<code>class A
{
   List<Var> varList;
}

class B
{
   List<A>   aList;
   List<Var>   allVarOfAs;
  // it is a common list which holds the members of varList of all members of the aList
}
</code>```

Now if an object from varList in an an object of aList (an A object in B) is removed, how can I update the common list allVarOfAs?

What is the pattern for such situation?


问:
Non-printable characters and editors
Today I was presented with a very nasty problem and I do not quite know where to ask this but hope here is ok.

So I have the following string: "\0" (at least that's how it looks in visual studio). If you open the same file in notepad++ it looks like this: "\0SOH". so yes, I have reached a point where I need to check a string which has non printable characters. The problem is the string I am comparing against are hardcoded and would come to look like this:

```<code>switch (s)
{
    case "\0\0":
        Console.WriteLine("Crypto method 00");
        break;
    case "\0":
        Console.WriteLine("Crypto method 01");
        break;
    case "\0":
        Console.WriteLine("Crypto method 02");
        break;
    case "\0":
        Console.WriteLine("Crypto method 03");
        break;
    default:
        Console.WriteLine(s);
        break;
}
</code>```

complete example code can be found on pastbin for the next month

But the code is not important, this, the display of this code, it is horrible and that's the problem. I cannot possibly commit something like this because no one will know what is happening.

Of course I could add comments so my co-workers will know what's going on but to me that does not seem like the proper solution. so my question what is the proper solution to create understandable code in this situation? Do I ask my co-workers to rewrite their code to make it work with byte arrays? Do I simply keep it this way?

A way to resolve this in code would be: ASCIIEncoding.Default.GetString(new byte[]{0, 1}); but this 'hack' does not really make it more understandable.

To clarify, I am not looking for a code fix, I can think of several (such as mentioned above) I am looking for advice on how to handle this or perhaps a way to make sure the (for example Visual studio) editor will distinguish between them.

Some extra context

A piece of old code handling the TCP connection receives the data (like it should) and then returns a string, it uses ASCII encode to create a string from the received byte[].

We have now gotten to a point where higher on we need to set/read a few status bytes which, because of the way we get messages from the TCP layer result in unreadable strings.

It is possible to rewrite the TCP to only send byte[] arrays but this is going to take up more time than anyone is willing to put in.

答:
You could do the comparison of the bytes by storing the strings as constants, with decent names. So case "\0\0": would become case STATUS_CRYPTO_1: which helps remove the 'magic number' aspect of your switch statement.

But the correct solution here is to add some comments. That's what comments were designed for, that's their intended purpose. Some documentation at the top of your function is probably the best place to say what the byte array is that you're comparing against, and why.

Title: Non-printable characters and editors


问:
Maintaining State without assignment
I am learning functional programming and I have trouble understanding how some particular scenarios are implemented without the use of assignment. The following simple problem pretty much sums up my confusion.

Write a program that receives events about changes in a given data structure and      emits events when this data structure reaches a certain state.

So I have a copy of the datastructure that I maintain

```<code>datastructure_copy::DataStructure
</code>```

I have the stream of events which are fired when it changes:

```<code>datastructure_changes::Stream Change
</code>```

I have a function that applies a change to a data structure and returns a new copy it:

```<code>apply_change::Change -> DataStructure -> DataStructure
</code>```

And I have a predicate which checks if the data state has reached the desired state.

```<code>is_ready::DataStructure ->Boolean
</code>```

In other words I need something like 'reduce' that works on streams.

I know that one way to implement this is to recompute the state each time a change arrives, however this seems impractical. I played a bit with the State monad, but it looks to me like it is meant to solve a different problem.

So is there another way to do that?

Note that my question is purely conceptual and I am not deeply familiar with Haskell.

答:
I know that one way to implement this is to recompute the state each time a change arrives, however this seems impractical.

If the changes applied when an event occurs are not distributive, in one way or another, you will have to recompute the state each time an event occurs, since the final state is nothing but the initial state, plus successive changes. And even if the changes are distributive, you typically want to successively transform a state to the next one, since you want to stop your process as fast as a given state is reached, and since you have to compute the next state to determine if the new one is the wanted state.

In functional programming, state changes are typically represented by function calls and/or function parameters.

As you can not predict when the final state will be computed, you should not use non-tail recursive function. A stream of states, in which each state is based on the previous one, could be a good alternative.

So in your case, I would answer the question by the following code, in Scala :

```<code>import scala.util.Random

val initState = 0.0
def nextState(state: Double, event: Boolean): Double = if(event) state + 0.3 else state - 0.1 // give a new state
def predicate(state: Double) = state >= 1

// random booleans as events
// nb: must be a function in order to force Random.nextBoolean to be called for each  element of the stream
def events(): Stream[Boolean] = Random.nextBoolean #:: events()

val states: Stream[Double] = initState #:: states.zip(events).map({ case (s,e) => nextState(s,e)}) // a stream of all the successive states

// stop when the state is >= 1 ;
// display all the states computed before it stopped
states takeWhile(! predicate(_)) foreach println
</code>```

Which can give, for instance (I simplified the output) :

```<code>0.0
0.3
0.2
0.5
0.8
</code>```

val states: Stream[Double] = ... is the line where successive states are computed.

The first element of this stream is the initial state of the system. zip merges the stream of states with the stream of events into a single stream of pairs of elements, each pair being a (state, event). map transforms each pair into a single value being the new state, computed as a function of the old state and the associated event. A new state is therefore a previously computed state, plus the associated event that "modifies" the state.

So basically, you define a potentially infinite stream of states, each new state being a function of the last computed state, and a new event. Since streams are lazy in Scala (among others), there are only computed on demand, so you don't have to compute useless states, and you can compute as many states as you want.

If you are only interested in the first state that respects the predicate, replace the last line of code by:

```<code>states find predicate get
</code>```

Which retrieves:

```<code>res7: Double = 1.1
</code>```

Title: Maintaining State without assignment

Body:
I know that one way to implement this is to recompute the state each time a change arrives, however this seems impractical.

If the changes applied when an event occurs are not distributive, in one way or another, you will have to recompute the state each time an event occurs, since the final state is nothing but the initial state, plus successive changes. And even if the changes are distributive, you typically want to successively transform a state to the next one, since you want to stop your process as fast as a given state is reached, and since you have to compute the next state to determine if the new one is the wanted state.

In functional programming, state changes are typically represented by function calls and/or function parameters.

As you can not predict when the final state will be computed, you should not use non-tail recursive function. A stream of states, in which each state is based on the previous one, could be a good alternative.

So in your case, I would answer the question by the following code, in Scala :

import scala.util.Random

val initState = 0.0
def nextState(state: Double, event: Boolean): Double = if(event) state + 0.3 else state - 0.1 // give a new state
def predicate(state: Double) = state >= 1

// random booleans as events
// nb: must be a function in order to force Random.nextBoolean to be called for each  element of the stream
def events(): Stream[Boolean] = Random.nextBoolean #:: events()

val states: Stream[Double] = initState #:: states.zip(events).map({ case (s,e) => nextState(s,e)}) // a stream of all the successive states

// stop when the state is >= 1 ;
// display all the states computed before it stopped
states takeWhile(! predicate(_)) foreach println

Which can give, for instance (I simplified the output) :

0.0
0.3
0.2
0.5
0.8

val states: Stream[Double] = ... is the line where successive states are computed.

The first element of this stream is the initial state of the system. zip merges the stream of states with the stream of events into a single stream of pairs of elements, each pair being a (state, event). map transforms each pair into a single value being the new state, computed as a function of the old state and the associated event. A new state is therefore a previously computed state, plus the associated event that "modifies" the state.

So basically, you define a potentially infinite stream of states, each new state being a function of the last computed state, and a new event. Since streams are lazy in Scala (among others), there are only computed on demand, so you don't have to compute useless states, and you can compute as many states as you want.

If you are only interested in the first state that respects the predicate, replace the last line of code by:

states find predicate get

Which retrieves:

res7: Double = 1.1


答:
As can already be seen in the question, using such non-printable characters directly in a string-literal makes the code essentially unreadable. At first glance, you would say that the presented code should fail to compile because there are multiple identical case labels.

Most languages (and that includes C#) support escape sequences to deal with troublesome characters like line-breaks, quotes and non-printable characters. Just like that you would use \n to represent a line-break in a string, you can use \x01 to represent the character U+0001 (ASCII SOH)in a string.

This is very commonly used when the string type is (mis-)used to represent byte data. As an example, your code would become:

```<code>switch (s)
{
    case "\x00\x00":
        Console.WriteLine("Crypto method 00");
        break;
    case "\x00\x01":
        Console.WriteLine("Crypto method 01");
        break;
    case "\x00\x02":
        Console.WriteLine("Crypto method 02");
        break;
    case "\x00\x03":
        Console.WriteLine("Crypto method 03");
        break;
    default:
        Console.WriteLine(s);
        break;
}
</code>```

Title: Non-printable characters and editors

Body:
Today I was presented with a very nasty problem and I do not quite know where to ask this but hope here is ok.

So I have the following string: "\0" (at least that's how it looks in visual studio). If you open the same file in notepad++ it looks like this: "\0SOH". so yes, I have reached a point where I need to check a string which has non printable characters. The problem is the string I am comparing against are hardcoded and would come to look like this:

```<code>switch (s)
{
    case "\0\0":
        Console.WriteLine("Crypto method 00");
        break;
    case "\0":
        Console.WriteLine("Crypto method 01");
        break;
    case "\0":
        Console.WriteLine("Crypto method 02");
        break;
    case "\0":
        Console.WriteLine("Crypto method 03");
        break;
    default:
        Console.WriteLine(s);
        break;
}
</code>```

complete example code can be found on pastbin for the next month

But the code is not important, this, the display of this code, it is horrible and that's the problem. I cannot possibly commit something like this because no one will know what is happening.

Of course I could add comments so my co-workers will know what's going on but to me that does not seem like the proper solution. so my question what is the proper solution to create understandable code in this situation? Do I ask my co-workers to rewrite their code to make it work with byte arrays? Do I simply keep it this way?

A way to resolve this in code would be: ASCIIEncoding.Default.GetString(new byte[]{0, 1}); but this 'hack' does not really make it more understandable.

To clarify, I am not looking for a code fix, I can think of several (such as mentioned above) I am looking for advice on how to handle this or perhaps a way to make sure the (for example Visual studio) editor will distinguish between them.

Some extra context

A piece of old code handling the TCP connection receives the data (like it should) and then returns a string, it uses ASCII encode to create a string from the received byte[].

We have now gotten to a point where higher on we need to set/read a few status bytes which, because of the way we get messages from the TCP layer result in unreadable strings.

It is possible to rewrite the TCP to only send byte[] arrays but this is going to take up more time than anyone is willing to put in.

Body:
As can already be seen in the question, using such non-printable characters directly in a string-literal makes the code essentially unreadable. At first glance, you would say that the presented code should fail to compile because there are multiple identical case labels.

Most languages (and that includes C#) support escape sequences to deal with troublesome characters like line-breaks, quotes and non-printable characters. Just like that you would use \n to represent a line-break in a string, you can use \x01 to represent the character U+0001 (ASCII SOH)in a string.

This is very commonly used when the string type is (mis-)used to represent byte data. As an example, your code would become:

switch (s)
{
    case "\x00\x00":
        Console.WriteLine("Crypto method 00");
        break;
    case "\x00\x01":
        Console.WriteLine("Crypto method 01");
        break;
    case "\x00\x02":
        Console.WriteLine("Crypto method 02");
        break;
    case "\x00\x03":
        Console.WriteLine("Crypto method 03");
        break;
    default:
        Console.WriteLine(s);
        break;
}


问:
Is it a good practice to wrap all primitives and Strings?
According to Jeff Bay's Essay on Object Callisthenics,

One of the practices is set to be "Wrap all primitives and Strings"

Can anyone elaborate on this ?

In languages where we already have wrappers for primitives like C# and Java.
and In languages where Collections can have generics where you are sure of what type goes into the collection, do we need to wrap string's inside their own classes ?

Does it have any other advantage ?

答:
Scroog1's answer covers adding context to a value. Another example: say you have

```<code>public void SubmitOrder(int productId, int customerId) { ... }
</code>```

then there is always the possibility that you call it as so:

```<code>processor.SubmitOrder(customerId, productId);
</code>```

Ouch. Let's hope you wrote a unit test that checked which value was passed in which place. But if you define:

```<code>public void SubmitOrder(ProductID pid, CustomerID cid) { ... }
</code>```

then the compiler will stop you getting it wrong. For a small project this may well be overkill; for a large one where bugs have life-or-death consequences it may well stop you having sleepless nights.

Body:
Scroog1's answer covers adding context to a value. Another example: say you have

public void SubmitOrder(int productId, int customerId) { ... }

then there is always the possibility that you call it as so:

processor.SubmitOrder(customerId, productId);

Ouch. Let's hope you wrote a unit test that checked which value was passed in which place. But if you define:

public void SubmitOrder(ProductID pid, CustomerID cid) { ... }

then the compiler will stop you getting it wrong. For a small project this may well be overkill; for a large one where bugs have life-or-death consequences it may well stop you having sleepless nights.


问:
How to decide what forms the System Under Test
Ok, so we started with the initial version of "The Art Of Unit Testing" and we do unit tests for classes where every test covers one aspect of one method.

This has the drawback of high maintenance costs and brittle tests and seems that the second version of "The Art Of Unit Testing" points to take bigger units when testing.

Which is the right size (the one that you use) when doing unit tests? I've heard of testing only the public interface provided by a module but in the project we are working we have a relative small public surface with a very big back office so I'm not sure if that would work as the Arrange of the tests would be really big and probably difficult to follow.

So, again, how to you set the boundaries of your SUT or how do you decide what forms your SUT?

答:
Ideally things would vary according to the rule of common sense. Martin Fowler talks about a unit as a class (plus related classes in some cases) and IMHO a unit should be a useful lump of code, this may be a single method where a method is quite complex, or a whole class as classes are the means of dividing a system into manageable components.

A single method is generally not a unit, as they tend to be too granular to be of any practical use.

Perhaps a rule of thumb is to think of the test as documentation - you can use your tests as example code, a how-to-use a piece of functionality. If you think that a test is meaningless to anyone else, as the tests are too small or trivial, then its a smell that the unit being tested is too small too, and should be enclosed in a wider unit. So a complex method may require a lot of possible inputs, and your test would demonstrate them, but a network class (say) would have a test that describes the entire class by constructing it, setting hostname and port, and then calling send or receive methods on it - those methods by themselves being useless by themselves.

Only testing public interface makes sense - if the code cannot be accessed by the public interface, then there's no real reason to have it! However, you say you have a large back-office functionality, the API to access the component parts of the back-office is still a public interface (ie its public to a computer client or class) and should be considered for a unit test in that regard.


答:
There is no "one size fits all" answer to where you should put the boundaries of your SUT.

The optimal size of a SUT for unit-testing depends on a lot of factors, including

The language and toolchain you are working with (how many errors can be detected by static analysis/compiling the code)

The complexity of the product you are making

How familiar the team is with creating such a product

A team writing their tenth low-complexity website might use much larger SUTs in their unit-tests than a team that is new to the job and/or is tasked with a very complex site.

Choosing the size of your SUT is a balancing act. If it is too small, then the tests start to depend on implementation choices, which causes rework of the tests if the implementation changes.

If it is too large, then there is no easy correlation between "Test A fails" and "There is a problem in function/area B".

Some general guidelines are:

The tests are a client of a class, just like the other modules that will eventually interface with it. Testcases should not have access to internals of a class unless that is absolutely necessary to verify that a particular requirement has been met. And even then you should first look if that requirement can be verified using only the public members of the class.

Each test should verify only one requirement. Often this is misrepresented as having only a single assert in a test. Quite often requirements can't be verified with only a single assert statement, leading to people writing multiple testcases where each test covers only part of the verification. If you need several closely related assert statements to verify a requirement, then it is perfectly fine to have it all in one test.

You should mock away all dependencies of your SUT, unless they are known to be fast and well-tested (like standard or third-party classes). When writing expectations for these mocks, try not to rely on the order in which calls are made, unless the order of the calls is an explicit requirement.

Focus your testing effort on the areas with high complexity and/or uncertainty. There is very little value in writing a test for a one-line getter. For those functions, it is very easy to see that they are correct and there is little risk that a future change will break them.

Title: How to decide what forms the System Under Test

Body:
Ok, so we started with the initial version of "The Art Of Unit Testing" and we do unit tests for classes where every test covers one aspect of one method.

This has the drawback of high maintenance costs and brittle tests and seems that the second version of "The Art Of Unit Testing" points to take bigger units when testing.

Which is the right size (the one that you use) when doing unit tests? I've heard of testing only the public interface provided by a module but in the project we are working we have a relative small public surface with a very big back office so I'm not sure if that would work as the Arrange of the tests would be really big and probably difficult to follow.

So, again, how to you set the boundaries of your SUT or how do you decide what forms your SUT?


答:
This is not a bad practice. Overloading a single method to do different things depending on parameters is actually an antipattern. If different strings leads to different behavior it is good design to created distinct methods.

Eg.

```<code>x.deleteFile()
x.sendMail()
</code>```

is a much better interface than

```<code>x.doTask("DeleteFile")
x.doTask("SendMail")
</code>```

even if they internally call the same private method. This fact is an implementation detail which should be encapsulated.

Consider the downsides of the second solution:

you cannot add parameters to one of the tasks in the future.

you cannot safely change the name of a task

you cannot inspect the code to see where the "SendMail" functionality is used

spelling errors will not be detected by the compiler but will cause the program to fail at runtime.

you are are creating a 'god-method' which is an antipattern because it breaks the single-responsibility principle and high-cohesion/low-coupling principle.

you cannot easily see what tasks the "god-method" supports.

you cannot segregate the interface as per the SOLID principles, which means you cannot override or supply an alternative implementation of "DeleteFile" without also supplying an alternative implementation of "SendMail".

So you should definitely listen to your colleague and consider his viewpoints carefully!

Body:
This is not a bad practice. Overloading a single method to do different things depending on parameters is actually an antipattern. If different strings leads to different behavior it is good design to created distinct methods.

Eg.

x.deleteFile()
x.sendMail()

is a much better interface than

x.doTask("DeleteFile")
x.doTask("SendMail")

even if they internally call the same private method. This fact is an implementation detail which should be encapsulated.

Consider the downsides of the second solution:

you cannot add parameters to one of the tasks in the future.

you cannot safely change the name of a task

you cannot inspect the code to see where the "SendMail" functionality is used

spelling errors will not be detected by the compiler but will cause the program to fail at runtime.

you are are creating a 'god-method' which is an antipattern because it breaks the single-responsibility principle and high-cohesion/low-coupling principle.

you cannot easily see what tasks the "god-method" supports.

you cannot segregate the interface as per the SOLID principles, which means you cannot override or supply an alternative implementation of "DeleteFile" without also supplying an alternative implementation of "SendMail".

So you should definitely listen to your colleague and consider his viewpoints carefully!


问:
What are my options for exposing customization settings to the admin user?
I'm writing a blog system as a learning exercise and I would like to allow the admin (or blog owner) to select/change some custom options based on features that I choose to expose to them such as:

change blog name (string)

select layout (int)

number of blog entries per page (int)

more stuff like this...

The only way that I can really think of to do this is by creating a class, with a property for each option and letting the owner get and set the properties.

What are my options for exposing customization settings to the admin / owner?

This is how I've implemented it for the time-being, although I am aware that this may not be the best way to do this:

I've created a class called Setting.cs

```<code>    public class Setting : IEntity
    {
        [Key]
        public int Id { get; set; }
        public string BlogName { get; set; }
        public string SubTitle { get; set; }
        public int PostsPerPage { get; set; }

    }
</code>```

Then I added a settings method to my Admin Dashboard controller like this:

```<code>    public ActionResult Settings(int? id = 1)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Setting set = db.Settings.Find(id);

        if (set == null)
        {
            return HttpNotFound();
        }
        return View(set);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult Settings([Bind(Include = "Id,BlogName,SubTitle,PostsPerPage")] Setting sets)
    {
        if (ModelState.IsValid)
        {
            db.Entry(sets).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index", "Dashboard");
        }
        return View(sets);
    }
</code>```

I then seed the record and just retrieve the same record and update it with the new settings each time.

I suppose I should state my concerns:

It seems strange to store a single row of data in it's own table of my database.

It also seems strange that if one wanted to, one could instantiate the Settings.cs class and possibly make multiple records of it.

I've hard-coded my controller with the record ID, as well as any calls to the controller, which to me feels like I'm abusing the intended purpose of using a controller by hard coding it.

I'm new to programming but this doesn't seem right to me. In Swift iOS programming I could create a pList (flat-file) or store settings in the NSUserDefaults. I'm just wondering what my options are in ASP.NET MVC.

I originally wanted to ask "What's the best way to implement admin/owner settings?" but I didn't want my question closed as being subjective. I am, however, hoping to deduce what the preferred method is ultimately to adhere to best practices.

答:
Depending on your framework, there is usually some type of simple persistence method for these types of non-relational values.

Java has properties

C#(.net framework) has Settings


问:
What pattern to use when you have to hide/show different sections on a form depending on a dropdown value?
For example, let's say you have 8 sections to hide/show and depending on the value of a dropdown, you have to show or hide dynamically from 1 to 8 sections.

1) Is there any better way of doing this than with the approach of the code below?

2) Is this approach acceptable?

```<code>$("#dropdown").change(function(){

  var value = this.value;
  var $section1 = $("#section1");
  var $section2 = $("#section2");
  var $section3 = $("#section3");

  $(".section").hide(); //hides all sections

  if(value == "someValue"){
     $section1.show();
     $section2.show();
  } else if (value == "someOtherValue") {
     $section3.show();
  } else {
     $section2.show();
     $section3.show();
  }

  //etc
})
</code>```

Any other advice that you consider helpful will be appreciated.

答:
While not really a pattern per se, the main thing I'd do here is separate the code from the data.

By "data", I mean which sections should be shown or hidden for each dropdown item.

```<code>var sectionsToShow = {
   item1: [1, 2, 3],
   item2: [2],
   item3: [6, 4, 5],
   ...
};
</code>```

Then your dropdown handler can (ideally) do something like

```<code>sectionsToShow[this.value].forEach(function(sectionToShow) {
   actualSections[sectionToShow].show();
});
</code>```

to show whichever sections are appropriate for that item.

This way it's much, much easier to reconfigure what sections are shown for each item when you inevitably have to change that mapping somehow.

Body:
While not really a pattern per se, the main thing I'd do here is separate the code from the data.

By "data", I mean which sections should be shown or hidden for each dropdown item.

var sectionsToShow = {
   item1: [1, 2, 3],
   item2: [2],
   item3: [6, 4, 5],
   ...
};

Then your dropdown handler can (ideally) do something like

sectionsToShow[this.value].forEach(function(sectionToShow) {
   actualSections[sectionToShow].show();
});

to show whichever sections are appropriate for that item.

This way it's much, much easier to reconfigure what sections are shown for each item when you inevitably have to change that mapping somehow.


问:
How to think as a C programmer after biased with OOP language?
Previously, I've only used Object Oriented Programming languages (C++, Ruby, Python, PHP), and am now learning C. I'm finding it difficult to figure out the proper way to do things in a language with no concept of an 'Object'. I realize that it's possible to use OOP paradigms in C, but I'd like to learn the C-idiomatic way.

When solving a programming problem, the first thing I do is to imagine an object that will solve the problem. What steps do I replace this with, when using a non-OOP Imperative Programming paradigm?

答:
I am also I OO native ( C++ generally ) who sometimes has to survive in a world of C. To me the fundamentally biggest hurdle is dealing with error handling and resource management.

In C++ we have throw to pass an error from where it happens all the way back to the top level where we can deal with it and we have destructors to automatically free our memory and other resources.

You might notice that many C APIs include an init function which provides you with a typedef'd void * which is really a pointer to a struct. Then you pass this in as the first argument for every API call. Essentially that becomes your "this" pointer from C++. It gets used for all the internal data structures which are hidden away (a very OO concept). You can also use it to manage memory, e.g. have a function called myapiMalloc which mallocs your memory and records the malloc in your C version of a this pointer so you can make sure it is freed when your API returns. Also as I recently discovered you can use it to store error codes and use setjmp and longjmp to give you behaviour very similar to throw catch. Combining both concepts gives you a lot of the functionality of a C++ program.

Now you did say that you didn't want to learn to force C into C++. That isn't really what I'm describing (at least not deliberately). This is simply a (hopefully) well designed method to exploit C functionality. It does turn out to have some OO flavours - perhaps that's why OO languages developed, they were a way to formalise/enforce/facilitate concepts that some people found to be best practice.

If you think this is to OO feeling for you then the alternative is to have pretty much every function return an error code which you must religiously ensure you check after every function call and propagate up the call stack. You must ensure that all resources are freed not only at the end of each function, but at every return point (which potentially could be after any function call which can return an error that indicates you cannot continue). It can get very tedious and tends to lead to you thinking I probably don't need to deal with that potential memory allocation failure (or file read or port connect...), I'll just assume that it will work or I'll write the "interesting" code now and come back and deal with the error handling - which never happens.


问:
OAuth/OAuth2 RFC question
This question is about a line from the OAuth2 rfc - https://www.rfc-editor.org/rfc/rfc6749

In Section 2.3, there is this line

```<code>The client MUST NOT use more than one authentication method in each request.
</code>```

What exactly does this mean?

答: It's an error for the user to attempt to authenticate twice, e.g. via HTTP Basic Auth and then via Post.  I believe that this is to avoid specifying what should be done if the user sends two different client_ids via two different authentication methods - rather than specifying which authentication takes precedence, it's simpler to forbid this scenario altogether</p>

Title: OAuth/OAuth2 RFC question


问:
Hardcoding strings that will never change
So, in my efforts to write a program to conjugate verbs (algorithmically, not through a dataset) for French, I've come across a slight problem.

The algorithm to conjugate the verbs is actually fairly simple for the 17-or-so cases of verbs, and runs on a particular pattern for each case; thus, the conjugation suffixes for these 17 classes are static and will (very likely) not change any time soon. For example:

```<code>// Verbs #1 : (model: "chanter")
    terminations = {
        ind_imp: ["ais", "ais", "ait", "ions", "iez", "aient"],
        ind_pre: ["e", "es", "e", "ons", "ez", "ent"],
        ind_fut: ["erai", "eras", "era", "erons", "erez", "eront"],
        participle: ["é", "ant"]
    };
</code>```

These are inflectional suffixes for the most common class of verb in French.

There are other classes of verbs (irregulars), whose conjugations will also very likely remain static for the next century or two. Since they're irregular, their complete conjugations must be statically included, because they can't reliably be conjugated from a pattern (there are also only [by my count] 32 irregulars). For example:

```<code>// "être":
    forms = {
        ind_imp: ["étais", "étais", "était", "étions", "étiez", "étaient"],
        ind_pre: ["suis", "es", "est", "sommes", "êtes", "sont"],
        ind_fut: ["serai", "seras", "sera", "serons", "serez", "seront"],
        participle: ["été", "étant"]
    };
</code>```

I could put all this into XML or even JSON and deserialize it when it needs to be used, but is there a point? These strings are part of natural language, which does change, but at a slow rate.

My concern is that by doing things the "right" way and deserializing some data source, I've not only complicated the problem which doesn't need to be complicated, but I've also completely back-tracked on the whole goal of the algorithmic approach: to not use a data source! In C#, I could just create a class under namespace Verb.Conjugation (e.g. class Irregular) to house these strings in an enumerated type or something, instead of stuffing them into XML and creating a class IrregularVerbDeserializer.

So the question: is it appropriate to hard-code strings that are very unlikely to change during the lifetime of an application? Of course I can't guarantee 100% that they won't change, but the risk vs cost is almost trivial to weigh in my eyes - hardcoding is the better idea here.

Edit: The proposed duplicate asks how to store a large number of static strings, while my question is when should I hard-code these static strings.

答:
is it appropriate to hard-code strings that are very unlikely to change during the lifetime of an application? Of course I can't guarantee 100% that they won't change, but the risk vs cost is almost trivial to weigh in my eyes - hardcoding is the better idea here

It looks to me that you answered your own question.

One of the biggest challenges we face is to separate out the stuff that's likely to change from the stuff that won't change.  Some people go nuts and dump absolutely everything they can into a config file.  Others go to the other extreme and require a recompile for even the most obvious changes.

I'd go with the easiest approach to implement until I found a compelling reason to make it more complicated.


答:
You are reasoning at the wrong scope.

You haven't hardcoded only individual verbs. You have hardcoded the language and its rules. This, in turn, means that your application cannot be used for any other language, and cannot be extended with other rules.

If this is your intent (i.e. using it for French only), this is the right approach, because of YAGNI. But you admit yourself that you want to use it later for other languages as well, which will mean that very soon, you'll have to move all the hardcoded part to the configuration files anyway. The remaining question is:

Will you, with a certainty close to 100%, in the near future, extend the app to other languages? If so, you should have been exporting things to JSON or XML files (for words, parts of the words, etc.) and dynamic languages (for rules) right now instead of forcing yourself to rewrite the major part of your app.

Or there is only a minor probability that the app will be extended somewhere in the future, in which case YAGNI dictates that the simplest approach (the one you're using right now) is the better?

As an illustration, take Microsoft Word's spelling checker. How many things do you think are hardcoded?

If you are developing a text processor, you could start by a simple spelling engine with hardcoded rules and even hardcoded words: if word == "musik": suggestSpelling("music");. Rapidly, you'll start moving words, then rules themselves outside your code. Otherwise:

Every time you have to add a word, you have to recompile.

If you learned a new rule, you have to change the source code once again.

And more importantly, there is no way you can adapt the engine to German or Japanese without writing tremendous amounts of code.

As you highlighted yourself:

Very few rules from French could be applied to Japanese.

As soon as you hardcode the rules for a language, every other one will require more and more code, especially given the complexity of natural languages.

Another subject is how you express those different rules, if not through code. Ultimately, you may find that a programming language is the best tool for that. In that case, if you need to extend the engine without recompiling it, dynamic languages may be a good alternative.

Title: Hardcoding strings that will never change

Body:
So, in my efforts to write a program to conjugate verbs (algorithmically, not through a dataset) for French, I've come across a slight problem.

The algorithm to conjugate the verbs is actually fairly simple for the 17-or-so cases of verbs, and runs on a particular pattern for each case; thus, the conjugation suffixes for these 17 classes are static and will (very likely) not change any time soon. For example:

```<code>// Verbs #1 : (model: "chanter")
    terminations = {
        ind_imp: ["ais", "ais", "ait", "ions", "iez", "aient"],
        ind_pre: ["e", "es", "e", "ons", "ez", "ent"],
        ind_fut: ["erai", "eras", "era", "erons", "erez", "eront"],
        participle: ["é", "ant"]
    };
</code>```

These are inflectional suffixes for the most common class of verb in French.

There are other classes of verbs (irregulars), whose conjugations will also very likely remain static for the next century or two. Since they're irregular, their complete conjugations must be statically included, because they can't reliably be conjugated from a pattern (there are also only [by my count] 32 irregulars). For example:

```<code>// "être":
    forms = {
        ind_imp: ["étais", "étais", "était", "étions", "étiez", "étaient"],
        ind_pre: ["suis", "es", "est", "sommes", "êtes", "sont"],
        ind_fut: ["serai", "seras", "sera", "serons", "serez", "seront"],
        participle: ["été", "étant"]
    };
</code>```

I could put all this into XML or even JSON and deserialize it when it needs to be used, but is there a point? These strings are part of natural language, which does change, but at a slow rate.

My concern is that by doing things the "right" way and deserializing some data source, I've not only complicated the problem which doesn't need to be complicated, but I've also completely back-tracked on the whole goal of the algorithmic approach: to not use a data source! In C#, I could just create a class under namespace Verb.Conjugation (e.g. class Irregular) to house these strings in an enumerated type or something, instead of stuffing them into XML and creating a class IrregularVerbDeserializer.

So the question: is it appropriate to hard-code strings that are very unlikely to change during the lifetime of an application? Of course I can't guarantee 100% that they won't change, but the risk vs cost is almost trivial to weigh in my eyes - hardcoding is the better idea here.

Edit: The proposed duplicate asks how to store a large number of static strings, while my question is when should I hard-code these static strings.


答:
The important part is separation of concern. How you achieve that is less relevant. i.e. Java is fine.

Independently of how the rules are expressed, should you need to add a language of change a rule: how many code and files do you have to edit?

Ideally, adding a new language should be possible by either adding a 'english.xml' file or a new 'EnglishRules implements ILanguageRules' object. A text file (JSON/XML) gives you an advantage if you want to change it outside of your build lifecycle, but require a complex grammar, parsing, and will be harder to debug. A code file (Java) let you express complex rules in a simpler way, but require a rebuild.

I would start with a simple Java API behind a clean language agnostic interface - as you need that in both cases. You can always add an implementation of that interface backed by an XML file later if you wish, but I don't see the need to tackle that problem immediately (or ever).


答:
Even while hardcoding seems fine here, and better than dynamically loading config files, I still would recommend that you do strictly separate your data (the dictionary of verbs) from the algorithm. You can compile them right into your application in the build process.

This will save you a lot of hazzle with maintenance of the list. In your VCS you can easily identify whether a commit did change the algorithm, or just fix a conjugation bug. Also, the list might need to be appended in the future for cases you didn't consider. Especially, the number of the 32 irregular verbs you counted doesn't seem be exact. While those seem to cover the commonly used ones, I found references to 133 or even 350 of them.


答:
I agree 100% with Dan Pichelman's answer, but I would like one thing to add. The question you should ask yourself here is "who is going to maintain/extend/correct the word list?". If it is always the person who also maintains the rules of a specific language (the particular developer, I guess you), then there is no point in using an external configuration file if this makes things more complex - you will not get any benefits from this. From this point of view, it will make make sense to hardcode such word lists even if you have to change them from time to time, as long as it is sufficient to deliver a new list as part of a new version.

(On the other hand, if there is a slight chance someone else must be able to maintain the list in the future, or if you need to change the word lists without deploying a new version of your application, then use a separate file.)


问:
Database view performance - good practice?
Often times at work we opt to create views in the database to expose the data that we want to work with instead of building some monster query in our code. Being somewhat new to this field my assumptions are that the view is just another query that is added onto whatever query I pass at run-time.

Sometimes we are returning hundreds of thousands of results, even millions sometimes and this can take some times. So, my question is does a view affect the query time and/or performance of the query?

答:
According to this discussion from 2007 in an Oracle forum, views were not cached at that time. From this description, it is clear that Oracle provides query result caching, but that will work independently from queries through a view, or selects without a view. If you use the same view in different queries, I would expect that the result caching might help a little bit, since the cache results from one query might be reused by a different query based on the same view, but this will probably depend on the query and the Oracle version.

However, Oracle supports the concept of materialized views, which can speed up queries, and also queries base on those kind of views. So the correct answer is:

it depends on the Oracle version, the database configuration and the particular query.

The best thing you can do is actually measure it for your specific situation.


答:
In general, a view's performance is equal to that of the defining query's performance. Usually the query planner can do all its tricks across views' boundaries if views are joined with other datasets.

It's always a good idea to run EXPLAIN PLAN against your most used statements, and see what might be a bottleneck.

Views that perform costly processing can be made materialized so that the computed values are stored and auto-updated. This makes sense when the underlying tables change not as often as the view is queried.

Title: Database view performance - good practice?

Body:
Often times at work we opt to create views in the database to expose the data that we want to work with instead of building some monster query in our code. Being somewhat new to this field my assumptions are that the view is just another query that is added onto whatever query I pass at run-time.

Sometimes we are returning hundreds of thousands of results, even millions sometimes and this can take some times. So, my question is does a view affect the query time and/or performance of the query?


答:
At a conceptual level, yes, a view is just a stored query that the optimizer will combine with whatever additional joins and predicates you add in your code to produce an optimal query plan.  In theory, using a view should be no different than replicating the "monster query" over and over in your code.  And to the extent that your DBA team may be able to do something to improve the performance of the query, having it in a view may make it easier for them to transparently improve the performance of all your queries.

Now, when you get down into the weeds, it is entirely possible that using a view would improve the performance of some queries and degrade the performance of other queries when compared to replicating the monster query because it causes the optimizer to pick a different query plan.  Since the optimizer is considering 10's of thousands of query plans and making lots of decisions about which branches to follow and which to abandon, it's hard to know in advance which queries would benefit from a view and which might be harmed.  Heck, it's often hard to know why a particular query was improved or harmed by putting some logic in a view unless you enjoy going deeply into 10053 trace files.  For most developers writing most queries, it's reasonably safe to assume that the presence of a view isn't going to have a meaningful impact on performance.


问:
How do you go about understanding others' code?
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?

答: Usually, I analyse a simple part first, e.g. the module used to maintain a small table. This teaches me the style the other programmer is using. If I have problems understanding even that, it's either very badly written or my knowledge of the language, framework etc. is insufficient. Once I grasp the simple part, it's time to move to the more complex parts of the program.</p>


问:
Function wrappers with no args: bad practice?
My colleague likes to write classes containing methods looking like this:

```<code>public function doTaskA()
{
    return $this->doTask('A');
}
public function doTaskB()
{
    return $this->doTask('B');
}
private function doTask($task)
{
    ...
</code>```

I say this is bad practice, and would prefer to just make the doTask method public. I think if you really feel it is necessary to hardcode the possible values of $task in the class, then just make them class constants and call doTask(self::TASK_A) rather than writing a new function purely as a wrapper.

The worst case I saw of this, was a class with more than a dozen of these wrappers, and the doTask method was barely twenty lines long.

So, is this actually bad practice? Or is it just a matter of style? Or am I wrong, and it is actually considered good practice, as he insists?

答:
The worst case I saw of this, was a class with more than a dozen of these wrappers, and the doTask method was barely twenty lines long.

I think this needs better addressing than the issue of using function wrappers, which as pointed out by the others answers tend to have more advantages than disadvantages.

Assuming you need minimally one line per method argument in doTask($task), something like below:

```<code>// PHP I think?
private function doTask($task)
{
    // ...
    if ($task === 'A') actuallyDoTaskA();
    if ($task === 'B') actuallyDoTaskB();
    // ...
}
</code>```

doTask() now becomes more of a hindrance since it is simply delegating calls to other methods, which should have been called by doTaskA()/doTaskB() in the first place.

In conclusion, such function wrappers can prove beneficial if you want to make the arguments used across your codebase consistent, or if it is used in a manner that reduces code duplication (e.g. different value substitutions for string formatting by callers). However, if the underlying method being called becomes another 'function wrapper' in itself, then you should really consider removing one level... preferably the underlying method.

Body:
The worst case I saw of this, was a class with more than a dozen of these wrappers, and the doTask method was barely twenty lines long.

I think this needs better addressing than the issue of using function wrappers, which as pointed out by the others answers tend to have more advantages than disadvantages.

Assuming you need minimally one line per method argument in doTask($task), something like below:

// PHP I think?
private function doTask($task)
{
    // ...
    if ($task === 'A') actuallyDoTaskA();
    if ($task === 'B') actuallyDoTaskB();
    // ...
}

doTask() now becomes more of a hindrance since it is simply delegating calls to other methods, which should have been called by doTaskA()/doTaskB() in the first place.

In conclusion, such function wrappers can prove beneficial if you want to make the arguments used across your codebase consistent, or if it is used in a manner that reduces code duplication (e.g. different value substitutions for string formatting by callers). However, if the underlying method being called becomes another 'function wrapper' in itself, then you should really consider removing one level... preferably the underlying method.


问:
Guideline/best practices on what traits/categories to give to tests
Is there any standard on what traits/categories to give to tests?

Here is an example:

using Xuint;

public class XUnitTest1
{
    [Fact]
    [Trait("Category", "CI")]
    public void TestMethodX1() { ... }

    [Fact]
    [Trait("Category", "CI")]
    public void TestMethodX2() { ... }

    [Fact]
    [Trait("Category", "CI")]
    [Trait("Runningtime", "Short")]
    [Trait("Priority", "2")]
    [Trait("Owner", "Terje")]
    public void TestMethodX3()
    {
        var sut = new SomeClasses.VerySimpleMath();
        int result = sut.Add(2, 3);
        Assert.Equal(result, 5)
    }
}
```

I guess that this is mostly used to reduce the time of executing when some are long but is there any standard? Should one bother starting giving traits/categories right from the start or only when tests are taking longer to run or when the need arises? What kind or traits/categories do people usually end up with?

答:
Do not ask for "best practices". (Particularly not here, since people will become snarky about it.)

Software development is a mind game. The things we do, we do because it makes reasoning about our code easier for ourselves. If you mindlessly ape the behaviour of a successful practitioner without understanding his problems and why this behaviour is a solution for them, you will not gain his expertise.

This is very different from other careers. To become a successful pole vaulter, you must possess a lot of understanding and motivation, but you must also practice the movements again and again, tirelessly. In such a field, copying the behaviour of a champion is useful; it really does take a long time of practice to internalize the movements you need to make a successful vault, and the more often you repeat them, the better.

Creating software isn't like that. There is no sequence of movements that brings you success; there is no daily exercise that will hone your skill if you repeat it tirelessy without change. (I suspect that part of the success of the "design pattern" meme, and the more recent "Code Kata" meme, is due to the misguided hope among beginners that there is such a thing.)

Why, then do we have design patterns, code guidelines, or best practices? They are regularities that professionals who have solved certain problems have notices and considered them useful have described and named in the hope that others could profit from them as well. Sometimes this works. But it works well only if you actually do have the same problem that the author had. If you apply a solution that served someone else well to a different situation, it won't work well at all. In order to understand which useful solution to copy, you must understand the problem that the author had, what problem you have, and whether their nature is similar enough that re-applying the solution makes sense.

Back from the rant, on to your question: what problem do you hope to solve with traits on tests? (I freely confess that I've never used any, and had never even heard of thembeing used before you asked.)

Are your test suites too slow and you want to cherry-pick subsets of your tests to save time? I strongly advise against that; a test suite is supposed to be run completely, since you never know where or when unforeseed effects of a change will break some of your existing code. Do you want to impose an ordering on them? That's not a good idea; tests should be independent enough that they behave exactly the same no matter what order they're run in.

Did you just learn of the feature and now think "Hmm, I wonder what useful things I can do with that?" In that case you should store the knowledge away and calmly wait for a situation where traits can do something useful for you. If you do have a problem, i.e. your tests aren't doing what you need them to do, tell us a bit more about the problem, so that we understand it, and perhaps we can advise you.


问:
Best algorithm to determine whether two arrays can be the same in a circular queue
I'm trying to figure out an efficient way to determine whether two distinct arrays of the same size can be shifted to form the same circular queue. For example:

```<code>Array1 = ['A','B','C','D']
Array2 = ['D','A','B','C']
</code>```

Can form the same circle if both ends are joined together:

I thought that one way would be to loop through one of the arrays while one remains constant, for example:

```<code>while Array1 is not = Array2 and iterations < Length of Array1
      temporary = Array1[last]
      for index is 0, add 1, before index = last
           temporary[index] becomes temporary[index+1]
      Array1[0] = temporary
      if Array1 == Array2 return TRUE
return FALSE
</code>```

Is there a more efficient way? I would need to do this check for several arrays among each other and remove duplicates. Plain speech, pseudocode or Python/C# data structures/code would be appreciated.

答:
Obviously you can check every possible offset between the two arrays and check every element for equality. But that always takes quadratic time. It's better to take the first element of Array1 and skip through Array2 until you find that same value. You save yourself lots of comparisons that can't possibly succeed because you already know the arrays won't be identical. (You might even find the rarest element in Array1 somehow and start with that, since it's even more likely to save you work.)

How much work this saves depends on how long the arrays are and how many identical values are in them, but in practice it could be a great part of the total effort.