问:
How does a software developer know if the target hardware is fast enough to run the software?
How do software developers manage to know if their software will run on the target hardware they are developing to? Many developers today work on machines much faster than the intended platform. What kind of tools do they use to understand when they are going overboard?

I'm asking from the perspective where you for example develop algorithms on a modern x86 in a GNU/Linux environment but the intended platform is an much slower Arm, still in GNU/Linux.

答:
If you mean how minimum/recommended system requirements are found, the application is simply tried on different machines.

In most cases, there is no hard limit: if the application works with 512 MB of memory, it will probably work with 511 MB of RAM as well (unless it explicitly checks for the memory). This means that you may have a limited number of machines to use for benchmarking, and deduce the limits from there. For instance, if the machine with 1 GB of RAM can barely run the app, while a machine with 4 GB of RAM runs it well enough and keeps in average 1 to 2 GB free, the minimum system requirements may include 2 GB of memory.

Precision

Note that benchmarking and profiling is precise. A non-functional requirement of performance, for instance, will specify in detail the test hardware and the load, the number of milliseconds representing the threshold and the threshold percentage. You can then make an automated test which either passes or fails, on every commit, indicating when the app became slower than expected. Talking about feelings (“this part of the app feels slow for me”) is unacceptable, because the lawyer of your customer may assert that the app still doesn't feel fast enough, while you've spent the last two months optimizing it and find it extremely fast.

When it comes to minimum/recommended system requirements, such precision is rarely required. The person writing down the system requirements may indeed simply test the app on multiple machines and use his feeling of fast/slow as the only criteria. If on the other hand the contract stipulates that the app should run on a machine with 2 GB of memory, than it should be in the Software requirements specification, written in non-ambiguous terms (see above).

Test environment

Also note that:

You should test the software on different hardware anyway (unless, of course, the software is distributed in a controlled environment, like a single data center), so there are chances that you already have the infrastructure you need.

Virtual machines make such testing less expensive than the purchase of dozens of actual, real machines.

However, testing on virtual machines may not be as straightforward as throwing a VM in the pool: while many hypervisors (or operating systems themselves) do a great job of allowing you to throttle some aspects (such as network bandwidth), it still requires additional configuration.

Complexity

I used RAM as an illustration, but the same logic applies to any other aspect: CPU speed, free space on hard disk, the speed of those hard disks, network bandwidth, etc. Not counting that the same hardware may not operate exactly the same every time.

For instance, one of my software products had a bug I spent a lot of time to debug. It appeared that when Windows put hard disks on stand-by when they are not used for a few minutes and they slept for a long time, waking them up takes a while, which sometimes triggered a timeout in my app.

This makes such testing a difficult task, even with virtual machines. This is one of two major complexities of desktop software, the other one being the fact that the software product has to survive in the wild, i.e. get along with thousands of other software products (including malware) which may be installed, deal with different configurations, accessibility options, broken things, etc.


问:
Is it bad practice for services to share a database in SOA?
I have recently been reading Hohpe and Woolf's Enterprise Integration Patterns, some of Thomas Erl's books on SOA and watching various videos and podcasts by Udi Dahan et al. on CQRS and Event Driven systems.

Systems in my place of work suffer from high coupling. Although each system theoretically has its own database, there is a lot of joining between them. In practice this means there is one huge database that all systems use. For example, there is one table of customer data.

Much of what I've read seems to suggest denormalising data so that each system uses only its database, and any updates to one system are propagated to all the others using messaging.

I thought this was one of the ways of enforcing the boundaries in SOA - each service should have its own database, but then I read this:

https://stackoverflow.com/questions/4019902/soa-joining-data-across-multiple-services

and it suggests this is the wrong thing to do.

Segregating the databases does seem like a good way of decoupling systems, but now I'm a bit confused. Is this a good route to take? Is it ever recommended that you should segregate a database on, say an SOA service, an DDD Bounded context, an application, etc?

答:
If done correctly, separating business concerns into different databases (or at least different schemas) is a virtue.

Please see Martin Fowler's description of the CQRS Pattern:

As our needs become more sophisticated we steadily move away from [treating an information system like a CRUD datastore]... The change that CQRS introduces is to split that conceptual model into separate models for update and display... There's room for considerable variation here. The in-memory models may share the same database, in which case the database acts as the communication between the two models. However they may also use separate databases, effectively making the query-side's database by a real-time ReportingDatabase. In this case there needs to be some communication mechanism between the two models or their databases.

And NServiceBus Architectural Principles:

Command Query Separation

A solution that avoids this problem separates commands and queries at the system-level, even above that of client and server. In this solution there are two "services" that span both client and server - one in charge of commands (create, update, delete), the other in charge of queries (read). These services communicate only via messages - one cannot access the database of the other...

And Command and Query Responsibility Segregation (CQRS)

Command and Query Responsibility Segregation

Most applications reads data more frequently than they write data. Based on that statement, it would be a good idea to make a solution where easily you can add more databases to read from, right? So what if we set up a database dedicated just for reading? Even better; what if we design the database in a way so it’s faster to read from it? If you design your applications based on the patterns described in CQRS architecture, you will have a solution that is scalable and fast at reading data.

ContentLicense: CC BY-SA 3.0


问:
Throw exception or let code fail
I am wondering if there are any pros and cons against this style:

```<code>private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}
</code>```

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

答:
I like the two main answers, but want to suggest that your function names could be improved.  I'm used to Java, so YMMV, but an "add" method should, IMO, not throw an Exception if the item is already there.  It should add the item again, or, if the destination is a Set, do nothing.  Since that is not the behavior of Materials.Add, that should be renamed TryPut or AddOnce or AddOrThrow or similar.

Likewise, your LoadMaterial should be renamed LoadIfAbsent or Put or TryLoad or LoadOrThrow (depending on whether you use answer #1 or #2) or some such.

Follow the C# Unity naming conventions whatever they are.

This will be especially useful if you have other AddFoo and LoadBar functions where it is allowable to load the same thing twice.  Without clear names the developers will get frustrated.

Title: Throw exception or let code fail


问:
HTTP events? Is there a standard / precedent for this?
Our architecture is HTTP servers (custom written) whereby custom clients send a HTTP request for some information and information is returned just as HTTP works. Now we need a special custom 'extension' which is a request which is a subscription for receiving asynchronous 'events' on a resource.

For example, the client sends an http request subscribing for events on some entity. As the 'entity' generates events they are passed to the http server and the http server must then lookup subscriptions for that entity and send the event message to all subscribed clients. Hope that makes sense.

So my questions are:

Has this been done before / or is there a standard I should be looking at?

If no standard, any suggestions on how to implement?

How does a http server send an unsolicited 'message' to a client?

答:
Here's how I would implement it:

Client opens a TCP/IP connection with Server and (assuming that succeeds) sends an HTTP packet to Server that says Client would like to be notified when Entity has an update.

Server adds Client to a list of observers, noting Client's IP address.

Server waits for notifications from Entity.

Upon receiving an update from Entity, Server establishes a TCP/IP connection with each observer, iteratively or otherwise, including Client.

If connection with Client is successful, Server sends an HTTP packet with a notification that Entity has updated. Return to step 3.

If connection with Client is unsuccessful, Client is put in a priority queue to receive that notification at a later time.

When that predetermined time comes, Server again attempts step 4. If the connection is again unsuccessful, Client's priority is reduced. Server may choose to drop Client from the observer list if this priority drops too low.

Hope that helps!


问:
How to make an interpreter for a stack of Free Monad Transformers
I like the idea of using Free monads to "purify" code and I've used it in some simple scenarios.  However, I can't seem to figure out how to write an interpreter for a Free monad transformer.  In particular a stack of free monads.

Here's a simple example of what I have in mind.  Say I'm purifying access to two databases.  I can write

```<code>{-# LANGUAGE DeriveFunctor #-}
module Question where

import Control.Monad.Trans.Free
import Control.Applicative ( (<$>) )
import Control.Monad.Trans.Class ( lift )

data DB1reqF x = FetchName String ( String -> x ) deriving (Functor)

data DB2reqF x = FetchInt String ( Int -> x ) deriving (Functor)

type DB1req = Free DB1reqF
type DB2req = Free DB2reqF
type DB2reqT = FreeT DB2reqF

fetchName :: String -> DB1req String
fetchName s = liftF $ FetchName s id

fetchInt :: String -> DB2req Int
fetchInt s = liftF $ FetchInt s id

runDB1reqF :: DB1reqF ( IO a ) -> IO a
runDB1reqF ( FetchName s n ) = putStrLn ( "Get from DB1: " ++ s  ) >> getLine >>= n

runDB2reqF :: DB2reqF ( IO a ) -> IO a
runDB2reqF ( FetchInt s n ) = putStrLn ( "Get from DB2: " ++ s  ) >> read <$> getLine >>= n

runDB1 :: DB1req a -> IO a
runDB1 = iterM runDB1reqF

runDB2 :: DB2req a -> IO a
runDB2 = iterM runDB2reqF
</code>```

which works fine for using DB1 and DB2 separately.  But if I want to use them together, I would think to stack a transformer with the other like

```<code>type CompoundProg = DB2reqT DB1req

fetchIntT :: (Monad m) => String -> DB2reqT m Int
fetchIntT s  = liftF $ FetchInt s id

complexProg :: CompoundProg Int
complexProg = do
    n <- lift $ fetchName "Fred"
    fetchIntT n
</code>```

But I can figure out how to write either of these functions:

```<code>runCompound :: CompoundProg a -> IO a
runCompound = undefined

runDB2T :: ( Monad m ) => DB2reqT m a -> m ( IO a )
runDB2T = undefined
</code>```

I also can't seem to find any examples.  Is a free monad stack a bad way to go about doing this sort of thing?

答:
Based on the example Daniel gave in the comments, here's an answer in case anyone stumbles here:

```<code>runDB2T :: ( Monad m ) => ( forall b. m b -> IO b ) -> DB2reqT m a ->  IO a
runDB2T f = iterT runDB2reqF . hoistFreeT f

runCompound :: CompoundProg a -> IO a
runCompound = runDB2T runDB1
</code>```

with {-# LANGUAGE RankNTypes #-}.

Body:
Based on the example Daniel gave in the comments, here's an answer in case anyone stumbles here:

runDB2T :: ( Monad m ) => ( forall b. m b -> IO b ) -> DB2reqT m a ->  IO a
runDB2T f = iterT runDB2reqF . hoistFreeT f

runCompound :: CompoundProg a -> IO a
runCompound = runDB2T runDB1

with {-# LANGUAGE RankNTypes #-}.


答:
Seeing as how you can configure the hardware and memory that the VM is allowed you can test a wide range of setups on your own PC. This also allows you to test across multiple operating systems.

Well for instance the CPU of a PC could be 6 Ghz. When you install virtual PC you can actually set the computer to use a certain amount of that. So for example you could set the virtual PC to run at 2.5 Ghz, and test the game to see if it runs. When you find the point where the game doesnt run properly say 2ghz. You would take a step up to maybe 2.2 Ghz and if it runs well then that would be your minimum specification for that piece of hardware.

I have sourced the information below from Justin Cave on stackexchange.
The web url to a similar question is How are minimum system requirements determined?
All the information below has came directly from Justin Cave 2011 and has not been edited.

Frequently, the minimum requirements are set by looking at the types of systems that target market customers would actually use for the product in question and picking some reasonable cutoff that doesn't alienate the target customer and is something the QA department can test with a minimal additional hassle.

If you expect that most of your customers are going to install your product on relatively recent desktop computers, for example, you would probably look around and see that just about any low end desktop computer for the home is going to ship with 2 GB of RAM. So a recent computer is very likely to have at least 1 GB of RAM even if it's a couple years old. If very few of your customers are going to want to use a machine that only has 512 MB of RAM, the revenue of these sales is likely to be more than offset by the support requests (older machines are likely to have lots of other problems and incompatibilities that will cause problems and generate more help desk calls than other customers). So it may well be more profitable to avoid making sales to those customers.

Title: How does a software developer know if the target hardware is fast enough to run the software?

Body:
How do software developers manage to know if their software will run on the target hardware they are developing to? Many developers today work on machines much faster than the intended platform. What kind of tools do they use to understand when they are going overboard?

I'm asking from the perspective where you for example develop algorithms on a modern x86 in a GNU/Linux environment but the intended platform is an much slower Arm, still in GNU/Linux.


问:
How to model parallel processes (in a Bounded Context) with the same data store?
The situation. Let's say a background process puts stuff into data containers. It runs all the time, observes system events, and populates the data accordingly.

The user may launch a control panel application. With this application, the user can define new containers, rename or delete old ones. The panel is separated from the actual workhorse process to not accidentally take it down when it crashes.

For the sake of the example, let's assume the background process increases a counter for each container by 1 every minute. It's a lifetime counter. It needs to know about the containers. It's the only process which modifies the counters, though.

The control panel should display a list of containers and the current count. It should update a displayed count when needed (i.e. when the counter changed in the meantime). It needs to read the data but not write it -- except maybe for mutating the set of containers.

The question. Both processes operate on a similar domain. Both need to know about containers and counts. They only do different things with them. Now how would you model this in terms of DDD?

I pondered if they were different Bounded Contexts, but since the domain seems to be exactly the same, there's no indicator that this is necessary. The separation between both is merely technical. Maybe do some kind of RPC?

How should the processes share data? Should the control panel become a read-only process, access the same data store the background process writes to, and delegate container creation to the background process so writing is unified? (Is this CQRS already?)

答:
Use a pub/sub framework like nServiceBus. The control panel can subscribe to update events on the domain model. The background process will emit the update events. When the control panel first starts up, it will send a command to the background process to tell it to send all the info it needs.

Messages will contain serialized domain objects. The framework deals with making sure they get there. For example with nServicebus you can use MSMQ and be on separate machines (of course or the same one but here I'm assuming the control panel is running on a webserver and the update process is running on an app server).

Now for updates, the control panel can send commands via the bus to the update process, reflecting what update is wants. Same idea, serialize some info and put it on the bus. The UI can then block (OK give the poor user a throbber) until the next update message is received. Or, it can have an 'update pending' message in the header area that turns into 'refresh' or actually has the UI refresh (watch out if the user is onto something else...)

You might not want to throw all these new infrastructure pieces into your shop. But standing up pub/sub (inversion of communications SOA pattern) gives you so many options, you'll jump for joy.


问:
How useful are IT headhunters/recruiters when looking for a new job?
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?

答:
They sound like real-estate agents most of the time : "An exciting position...", "A great role for a motivated xyz", "A chance to enter industry K", etc.

All while they seem not able to note my details properly, which results in being sent job offers totally NOT matching anything in my CV.

Sincerely, they've been quite useless to me as I picked up zero jobs advertised to me by headhunters, but I suppose other people had a different experience there.

ContentLicense: CC BY-SA 2.5


问:
Why is using break considered bad practice?
I am currently in a beginning programming course at my University (I've got plenty of experience in the subject already, but I still have to pay for that piece of paper with time and money.) and the professor has been stressing since the beginning of the course that the break primitive that many languages provide is bad programming practice, and that many companies have policies stating that their programmers are not to use them.

Why is it considered bad practice to exit functions and loops with break primitives?

答:
In switch statements, they're pretty much essential -- well, you can use extract method/class to break it down into one-line cases, but ... -- I don't think that's what your professor means.

To break from a loop is considered by some to be a goto with another name. So is returning from the middle of a method. I have even seen a similar case used against exceptions. If you think about it, it makes logical sense; all of the reasons for avoiding the use of goto would apply equally to multiple exit points from a loop or method.

All of those constructs create paths through the code that aren't linear.

But, all that said, I would argue that they each represent a place where goto could be used to improve readability (usually by decreasing indentation), so having language constructs that represent them in different ways can only be a good thing. That way, we know, when we see one of these constructs, what the code is intending to do, and we can continue to enforce a policy of not using goto.

That is, however, my opinion. I don't think everyone agrees with me. And I will agree with anyone who contends that when you come to write a break, or a mid-method return, or an exception that covers anything but an unexpected situation, you should probably have a think about better ways to code it. Just remember, such a thing doesn't always exist.


答:
Ideally in my world there would be a tool to benchmark the platforms and then a tool for running the program to get some figures so you could compare and understand which platform you'll be using later on.

There is no such tool.

There is not even a methodology to follow.

The best you can do is extrapolate from the measured performance of the application running on a different platform.  Even that is liable to be unreliable.

Basically, the performance of an application is going to depend on a large number of complicated platform parameters, and (in some cases) on complicated interactions between the platform and the applications fine-grained behaviour.  It is too complicated to model.

(Depending on the nature of your application, the parameters could include CPU clock speed, CPU chipset, number of cores, memory size, memory architecture, memory speed, I/O system bandwidth, network interface, graphics card, hard drive controller and device, etcetera, etcetera.  Hundreds of different hardware and software characteristics could be relevant ...)

The best practical advice would be to just try it.  If you can't afford to buy an example of each candidate platform, then see if the salesman will let you try out the application on their kit before you sign the contract to buy.  If you can't do that, then toss a coin ...


问:
SOA principles, encapsulation and autonomy
We are developing multiple web services in C# using WCF, but we´re new doing it.

So, for what we have read and learnt, this is our approach:

We have a class library that we called CommonLibrary that has a few classes that are going to be used on all our services (language stuff, type of user connected and a common object that all the services are meant to return).

We have another class library called SecurityLibrary which validates the user that is consuming the method.

At the moment we have 2 services that are almost at 90% finished, both of them use CommonLibrary and SecurityLibrary.

Now the questions:

Is this a bad approach?

Are we violating the SOA principles of encapsulation and autonomy by using common/shared library with each of our services?

A third person told us to copy all the code of those libraries on each of our services so we have a 100% autonomous service, is this the right way? I think is hard for maintenance and shows a lot of duplicity. Any update made on one has to be replicated or merged on those other services...

Thanks for your time helping us to clarify this.

答:
My company use this approach (we are a Java/Maven/Jenkins shop). We use a webclient-common library in 4 or so web clients, and a webserver-common library in 3 web server projects. Just what advantage a "cut and paste" approach would add to this is a mystery to me.

As with using any common code, good release management and version tagging practices are essential. When we upgrade the common libraries, the multiple projects using them don't see the upgraded version until they are recompiled with their dependencies updated to pick up the latest version. Maven handles this brilliantly, and I expect C# has a similar tool.

So in my humble opinion, you are doing it dead right.


问:
To cache or not to cache a ReadOnlyWrapper object?
I have a system with a structure like this:

The ConcreteWriteable is caching the ReadOnlyWrapper.

This is a similar system to what .Net's System.Array uses for its Array.AsReadOnly<T>(T[] array) method (ignoring for the moment that System.Array's AsReadOnly is static). However looking at the code for System.Array at reference source, System.Array.AsReadOnly is returning a new wrapper each time, whereas I'm creating the wrapper at the same time as the ConcreteWriteable and caching it, then returning the same one each time.

This got me thinking, is there some reason why I shouldn't be doing this? Is there some reason why creating a new wrapper each time is more desirable than returning the same wrapper (bearing in mind that the wrapper cannot possibly change the ConcreteWriteable and is indeed a wrapper, not a copy)?

答:
Do not cache.

Technically: As Frank already said, the difference is the garbage collector. If you cache it, your objects will be moved to the java oldspace, where trashing objects is slow and painful. Whereas trashing objects in the new object space, comes at no costs, because this element isn't simply touched any more. But if you keep objects for no reason, this object is copied from one half of the new object space to the other, because there is a path to this object - The VM assumes: It must be important enough to keep. The object is aging in the new space and copied each time, where it produces (copying) costs. Thus caching objects produces costs by living on and they are much more expensive to clean up, after they reach oldspace.

Design: Always let the consumer of your API decide, how long an object must live. You as a designer, you don't have this information when designing the API/class.

Premature Optimization: You should also avoid premature optimization. Not every caching is a big gain. Do optimizations, when there is a good reason to, but avoid it if it makes code less readable with no much gain - avoid microoptimizations. If you need a caching instance, don't do it by default, but provide a "factory" providing caching objects, which contains the caching code. Your VM will come with new optimization strategies each time you get a newer one. If you need speed - it is mostly better to choose better algorithms instead of using microoptimizations.

Creating Objects: Last but not least, the "new" operation is not very expensive. There is no need to avoid that.


问:
In boundary-value analysis, why test min+1 along with min?
In boundary analysis testing, some authors suggest testing MIN-1, MIN, MIN+1 (and the same for MAX).

Also for 1-100 range (if A>=1 && A<=100), test cases would be: 0,1,2 and 99,100,101.

I do not see the point - if 100 works, then 99 must work too (in my opinion but this is why I ask).

答:
Lets assume you are testing a class "interval", representing intervals of natural numbers:

```<code> var interval= new Interval(1,100);
</code>```

Now your first two tests are "green":

```<code>AssertIsTrue(interval.Contains(100))
AssertIsFalse(interval.Contains(101))
</code>```

and you are confident the author made no "off-by-one-error".

Unfortunately, the implementation looks like this

```<code>Contains(x)
{
    return (x>= beginRange && x == endRange);
   // above line has a typo, "==" should have been be "<="
}
</code>```

So you were better off to add another test at first hand,

```<code> AssertIsTrue(interval.Contains(99));
</code>```

which fails, revealing the bug missed by the first two tests.

Or to be more general: off-by-one errors do not always manifest themselves by mixing up "<" and "<=", there are lots of other possibilities to get such things wrong, and as a tester, you are better off not to make any assumptions about how the internal implementation of a function looks like.

Body:
Lets assume you are testing a class "interval", representing intervals of natural numbers:

 var interval= new Interval(1,100);

Now your first two tests are "green":

AssertIsTrue(interval.Contains(100))
AssertIsFalse(interval.Contains(101))

and you are confident the author made no "off-by-one-error".

Unfortunately, the implementation looks like this

Contains(x)
{
    return (x>= beginRange && x == endRange);
   // above line has a typo, "==" should have been be "<="
}

So you were better off to add another test at first hand,

 AssertIsTrue(interval.Contains(99));

which fails, revealing the bug missed by the first two tests.

Or to be more general: off-by-one errors do not always manifest themselves by mixing up "<" and "<=", there are lots of other possibilities to get such things wrong, and as a tester, you are better off not to make any assumptions about how the internal implementation of a function looks like.


问:
How should I change in get method without calling getList() of Deque?
```<code>import java.util.List;
import java.util.ArrayList;

public class Test {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        Deque queue = new Deque();

        int random = (int)(Math.random() * 100);

        queue.addLast(10);
        queue.addLast(20);
        queue.addLast(random);
        queue.addLast(40);
        queue.addLast(50);

        for(int i = 0; i < 2; i++) {

            assertTrue(get(queue, 0) == 10);
            assertTrue(get(queue, 1) == 20);
            assertTrue(get(queue, 2) == random);
            assertTrue(get(queue, 4) == 50);
            assertTrue(get(queue, 3) == 40);

            try {
                System.out.println(get(queue, 5));
                assertTrue(false);
            } catch(Exception e) {
                assertTrue(true);
            }
        }
    }

    public static void assertTrue(boolean v) {
        if(!v) {
            Thread.dumpStack();
            System.exit(0);
        }
    }

    public static int get(Deque queue, int index) throws Exception
    {
        // 1) Only fill in your code in this method
        // 2) Do not modify anything else
        // 3) Use of 'new' keyword is not allowed
        // 4) Do not use reflection
        // 5) Do not use string concatenation

        return queue.getList().get(index);
    }
}

class Deque {
    private List<Integer> items;

    public Deque() {
        items = new ArrayList<Integer>();
    }

    public void addFirst(int item) {
        items.add(0, item);
    }

    public void addLast(int item) {
        items.add(item);
    }

    public int removeFirst() {
        if(isEmpty()) throw new RuntimeException();
        return items.remove(0);
    }

    public int removeLast() {
        if(isEmpty()) throw new RuntimeException();
        return items.remove(items.size() - 1);
    }

    public boolean isEmpty() {
        return items.size() == 0;
    }

    public List<Integer> getList()
    {
        return items;
    }
}
</code>```

Thanks

~July

答:
You can use recursion to remove index-1 elements from the beginning of the queue, store the the first element and then, as you are unwinding the recursion, put removed elements back on the queue:

```<code>public static int get(Deque queue, int index) throws Exception {
    int tmp = queue.removeFirst();
    try {
        if (index == 0) {
            return tmp;
        } else {
            return get(queue, index - 1);
        }
    } finally {
        queue.addFirst(tmp);
    }
}
</code>```

Body:
You can use recursion to remove index-1 elements from the beginning of the queue, store the the first element and then, as you are unwinding the recursion, put removed elements back on the queue:

public static int get(Deque queue, int index) throws Exception {
    int tmp = queue.removeFirst();
    try {
        if (index == 0) {
            return tmp;
        } else {
            return get(queue, index - 1);
        }
    } finally {
        queue.addFirst(tmp);
    }
}


问:
refactor by inheritance or composition for large class that depend on common state
I have a huge class (>1000 lines), in which all methods depend on a small set of attributes in that class. I can think of 2 quick ways of refactoring.

I keep it as a huge object, but split related methods into separate classes from which I inherit (but I don't instantiate those separate classes, only the last one in the inheritance-chain). This probably has the disadvantage that conceptually, my object is still a huge monolith.

I make the common attributes, with a few helper functions, into a separate class. All other code that depends on this common state then are in their own class, but contain the common state through composition. Disadvantage is I end up with a lot of nested lookup calls similar to self.commonState.foo, instead of just self.foo.

The latter is getting a bit reminiscent of the MVC pattern of course. Is there a clear answer to which method is preferred?

答:
It is difficult to tell without having more conetxt information on what the class does, but I faced the same problem once and I took the composition approach to refactoring.

The first approach looks like the decorator pattern to me. Depending of what the nature of your class is, it could be a good solution but without knowing much more I can't tell.

Back again to what I did: In my case I had a very big "Report" class that read from a database and formatted the data in a tab separated fashion, applying formats to dates and numbers. I refactored uit sing composition, by separating all format information and operations into a separate class exactly like you propose and injected that "Format" class into the "Report" class. I managed to reduce the size of the original class dramatically but with a lot of what you call "nested lookup calls".

Being pragmatic, and since the composition approach worked for me, I can tell you it's a safe way to go. But I also suggest you read about the decorator pattern to see if it suits you conceptually.


问:
Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
The coding standards for the code hosted in drupal.org suggest to use two spaces to indent the code; other sites suggest to use tabs to indent the code.

What is the proper indentation character for everything, and in every situation? Please explain the answer you give.

答: I'm a 4 space kind of guy, tabs just aren't consistent.</p>


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: I was asked to load articles from a competitor's website inside an iframe that would be inside our website's skin, making it look like it came from us.</p>


问:
Efficient method for finding closest point to a line segment from a set of points including line segment's vertices
Let's say I have a list of points (in my case, point objects in a Python implementation). I then have a line segment connecting two of these points.

I want to know if there's a way to efficiently find the point from the list that is closest to the line segment. I realize I could step through all of the points and check distances individually, then select the smallest distance, but I'm eventually hoping to scale the program up to deal with perhaps millions of points. So, you know, maybe something more efficient than that?

If it helps, in terms of CCW all the points being questioned should either be to the "left"/"below" or the "right"/"above" of the line segment; I don't think my implementation will involve checking points to both sides of the segment.

The points will be point objects with (x,y) coordinates and some other junk not directly relevant to this question. The line segments are currently implemented as objects containing references to two point objects (its vertices) and its length.

As I mentioned this is part of a Python implementation. I'm trying to design a way to find a concave hull to a set of points (given some predefined parameters of how to decide whether a point not on the convex hull is on the concave hull or not). I want to find the convex hull first, then for each line segment on the convex hull find the closest point to it, make a triangle with that point, then decide if that triangle bears "deleting such that the internal point is now on the hull.

I considered putting this in Mathematics, but I don't need a distance equation - I need help with an efficient algorithm for finding points closest to a line segment. Note also that I am not looking for the closest point on a line to an input point; I'm looking for the closest point from a set to an input line segment.

Thank you all!

答:
For what it is worth, for a static set of points to check the line segment against:

Precomputation using voronoi diagrams (http://en.wikipedia.org/wiki/Voronoi_diagram) is helpful as it reduces the nearest neighbor problem to a polygon line intersection query.

The voronoi diagram is made up of polygons.  Each point from the set of points you are trying to compare against is inside it's own polygon.  No point is contained within more than 1 polygon and no other points are inside that polygon.

If you only intersect 1 polygon, then you have your answer.  If you intersect more than 1 polygon, you must check each polygon you intersected.

Precomputation of the voronoi diagram will not help for dynamic sets of points to query against.


问:
Managing types and conversions in a compiler
I am trying to determine how to manage types and conversions between types within a compiler that I am writing. The compiler is being written in C#.

There are a number of different kinds of types.

Classes (read only / not mutable)

Mutable Types (Which contain another type. Think the opposite of C++ const.)

Generic Types (With constraints referring to types)

etc

The problem I am trying to solve is, given two types, how can I determine whether one can be converted to the other. (eg. Allow a mutable type to be assigned to the read only version of the type)

My first thought was to use a virtual method and a visitor. However, since types can depend on others (e.g. A mutable type is a wrapper referring to another type.), this can cause the number of cases that need to be handled to balloon. I am looking for a design that keeps this to a minimum.

答:
The problem I am trying to solve is, given two types, how can I determine whether one can be converted to the other.

In your language design, you have a well defined set of rules for your type system. A is a subtype of B if and only if these conditions hold. C can be assigned to a variable of type D if and only if these other conditions hold.  And you do the paperwork to prove that your type system is consistent (you can't get into a state where the rules are broken).

Then, for implementation it's fairly straightforward. You define some classes to define your various type forms - often derived from some common type baseclass so the concrete types can be used wherever your language expects a type. Then you write these rules into nice static (possibly recursive) binary predicates that tell you if for these two types, do the conditions hold.

Yes, that often means a bunch of if T is GenericType ugliness. You can get around that a little by using dynamic and doing dynamic dispatch on the predicates. I'm not sure that's particularly cleaner.

The good thing about the static predicates is that they are absurdly easy to unit test, and should be a near 1:1 translation of your type system on paper. They're hard to screw up, and they provide clear documentation to future programmers (likely you) about what the rules are.


答:
Some agents are brilliant, others not so

As a contractor in the UK, I deal with many agents (headhunters) on a regular basis. Almost invariably they do not have strong technical skills and it doesn't really matter. Their business is to get their candidate to be accepted by their client. If they are good at their business then they will have carefully matched their clients requirements with your CV and come to the conclusion that you are worth a call. If not, then you just get a vague (automated) email inviting you to call them.

What good are they?

A really good agent will build a solid lasting business relationship with you. It is usually in their interest to keep hold of good candidates that can be recycled into other positions later on (particularly true of contractors/freelancers/temp coders). And, if you continue improving your skills, that makes you much more of an asset to them because they can charge their client much more for you, and their client gets value for money. Win-win-win, really.

As to whether they are useful or not, in my case they are definitely useful. They provide me with a constant stream of potential offers for my next contract and I don't have to spend any time sending CVs out to random companies or cold calling. In return, they take a percentage of the value of contract (I don't see this percentage I only know my rate).

Unfortunately, most of my dealings with agents are non-personal, routine chats with person X from agency Y. The exceptions (and you know who you are if you're reading this ;-) ) don't hide their office number and have taken the time to build up history, repeat contracts and face to face contact. They add considerable value, and I thank them for their efforts.

Title: How useful are IT headhunters/recruiters when looking for a new job?

Body:
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?


问:
Architecture question about data migration
I'm facing a new enterprise project in Java about data migration.
I did one of them in the past, now I want to do a better work and I think I need your considerations.

So, let me explain the problem:

I have a lot of DB tables without any logical wire. So in the most of the cases I need to perform a huge logic in the Java application for build the correct results.

In past I have tested some advice, but in the end I used a lot of HashMaps for store in memory the entries retrieved from db and perform the logic I wanted. I was really lucky because the entries were not much for the memory machine.

The question you maybe you think now is: why you need to store all the entries into HashMap?

Example: I have TABLE1 and I need to perform a logic to all the entries. So I have a HashMap with original data taken from db (key: the id of the table, value: the entry POJO) and they can be retrieved by a sequence of queries without load all on memory.

The second HashMap contains the modified data sets of the TABLE 1.

Then I have TABLE 2 to perform another logic but I need the first modified data sets to perform other task.

In the end I must necessarily have in memory all the HashMap that contains the modified data sets for do all the logic.

I searched a lot on the internet to see if you can put a caching mechanism, but I am very confused.

What I would need is an intelligent algorithm that saves me the entries of HashMap on disk in case of need, but it should be fast enough to recover data when I need. Another alternative would be to save the changed data on db and use a massive amount of queries,
but I would avoid it because the results that interest me will not be saved to the database.

答:
If you want a drop-in replacement of HashMap/TreeMap, then MapDB is what you're looking for. It has features such as transparent serialization to disk and multiple caching strategies (intelligent algorithm you've mentioned).

Also you may consider doing all the work inside the DB, using stored procedures and temporary tables. It might be faster, because of the lack of sending data over the network.

ContentLicense: CC BY-SA 4.0


问:
To integrate git versions as build numbers or not?
A colleague and I have been taking turns debating/discussing the issues/merits of integrating a version derived from the current git repository into our code whenever it builds.

We think the merits include:

No need to worry about human error in updating a version number

Traceability between what we find in a device and the source code it was derived from

The issues that have arisen (for us) include:

IDE derived build systems (e.g. MPLABX) can make it hard to figure out where to put these kinds of hooks in (and it can end up pretty cheesy in the end)

More work to actually integrate this into the build scripts/makefiles

Coupling to a particular build approach (e.g. what if one person builds with XCode and the other MPLABX) may create downstream surprises

So we're curious where others have landed on this debate. It's really easy for the discussion to become anecdotal. There are lots of people out there who are insistent on end-to-end automation, hang the amount of up front work and coupling it creates. And there are a lot of others on the other side of the debate, who just do the easiest thing that works and live with the risks.

Is there a reasoned answer to which side is best to land on?

答:
I would recommend the use of Autorevision.

You can get output in a variety formats, for example a c style header.

There are also a few examples (in the contribs dir) of how you can hook things up so that no matter who is building and how they are doing it they will always get the same version information, even if they are building from a tarball.

Also, since in addition to git Autorevision works with svn and hg it makes easier to switch away from svn without having to change too much once you have it set up.


问:
Condition before statement or statement in condition
I've come across this problem a few times:

Is there any "programming rule" for checking for an condition (error checking for example) before you want to do execute code, or only execute the code when that condition is true.

Checking before running the code:

```<code>$condition = false;

function someFunction() {
    if(!$condition) {
      throw new Exception("Cant execute code because the condition is false");
    }
    //Execute code
}
</code>```

Only run the code when the condition is true:

```<code>$condition = false;

function someFunction() {
    if($condition) {
      //Execute code
    } else {
      throw new Exception("Cant execute code because the condition is false");
    }
}
</code>```

Question

Which one of the code examples is the most efficient however they're doing the same thing?

答:
Check before, please.  Which would you rather read and debug, after the code has been modified a few times.

This?

```<code>function someFunction() {
    if($condition1) {
       if($condition2) {
           if($condition3) {
              //Execute code
            } else {
                throw new Exception("Cant execute code because the third condition is false");
            }
        } else {
            throw new Exception("Cant execute code because the second condition is false");
        }
    } else {
        throw new Exception("Cant execute code because the first condition is false");
    }
}
</code>```

Or this?

```<code>function someFunction() {
    if(!$condition1) {
        throw new Exception("Cant execute code because the first condition is false");
    }
    if(!$condition2) {
        throw new Exception("Cant execute code because the second condition is false");
    }
    if(!$condition3) {
        throw new Exception("Cant execute code because the third condition is false");
    }
    //Execute code
}
</code>```

Body:
Check before, please.  Which would you rather read and debug, after the code has been modified a few times.

This?

function someFunction() {
    if($condition1) {
       if($condition2) {
           if($condition3) {
              //Execute code
            } else {
                throw new Exception("Cant execute code because the third condition is false");
            }
        } else {
            throw new Exception("Cant execute code because the second condition is false");
        }
    } else {
        throw new Exception("Cant execute code because the first condition is false");
    }
}

Or this?

function someFunction() {
    if(!$condition1) {
        throw new Exception("Cant execute code because the first condition is false");
    }
    if(!$condition2) {
        throw new Exception("Cant execute code because the second condition is false");
    }
    if(!$condition3) {
        throw new Exception("Cant execute code because the third condition is false");
    }
    //Execute code
}


问:
When to Use Shared Libraries
Note: I'm not sure if this question is more suitable for Stack Overflow or Programmers.  The thought process behind putting it here was that it doesn't actually relate to coding itself.

I noticed a small freeware utility I have on my computer uses a couple of DLLs.  From their names ("RenderAllChunks" and "RenderSlice"), it looks like they're being used just for specific functions.  If outsourcing program-specific functions is really necessary, wouldn't it be better to just stuff them in a separate header file?  It seems quite pointless to go through all the trouble of compiling, linking and distributing DLLs just for one function.

Is it bad to use shared libraries for small projects?

When/why are shared libraries preferable over static libraries (or even header files)?

答:
Particularly if you work in commercial/mass market software, its best to limit the number of external dependencies.  In my software, I only use a library when I cant compile it directly into an executable (for example, calling a c-made DLL from a Delphi program).  Limiting the number of dependencies limits the number possible problems relating to them during deployment to machines whose environment you dont control.

Years ago when hard drives were small and expensive there might have been some use for using DLLs to cut down on disk space, but that age is long gone on PCs, imo.  And probably even on phones and most devices these days.

Title: When to Use Shared Libraries


问:
Why do mainstream OO languages not have immutability on class-level built-in?
I regularly write classes which can only have immutable instances, much like string.

I am wondering why Java or C# or VB.NET don't  have immutability built-in into the language? That way, I can communicate immutability better to my fellow programmers and also make assumptions about state in the class.

For instance:
    immutable class Foo {
        public string Name { get; set; } //compile error: mutable property on immutable class
    }

答:
C# does have immutability built in.  So does Java, and VB.NET.

Mutable:

```<code>public class Counter
{
   private int count;

   public Counter(int initialCount)
   {
       count = initialCount;
   }

   public void Increment()
   {
       count++;
   }
}
</code>```

Immutable:

```<code>public class Counter
{
   private readonly int count;  // `final` for Java

   public Counter(int finalCount)
   {
       // set at construction time, but readonly, so can't modify.
       count = finalCount;
   }

   public void Increment()
   {
       // Invalid operation
       count++;
   }
}
</code>```

Note that I'm using "immutability" hear to mean "set once during object construction." Constants are not very useful in this context, because they can only be set at compile-time.

If you dig deep enough, every programming language mutates state under the hood, because that's how the processor instructions are designed.

Body:
C# does have immutability built in.  So does Java, and VB.NET.

Mutable:

public class Counter
{
   private int count;

   public Counter(int initialCount)
   {
       count = initialCount;
   }

   public void Increment()
   {
       count++;
   }
}

Immutable:

public class Counter
{
   private readonly int count;  // `final` for Java

   public Counter(int finalCount)
   {
       // set at construction time, but readonly, so can't modify.
       count = finalCount;
   }

   public void Increment()
   {
       // Invalid operation
       count++;
   }
}

Note that I'm using "immutability" hear to mean "set once during object construction." Constants are not very useful in this context, because they can only be set at compile-time.

If you dig deep enough, every programming language mutates state under the hood, because that's how the processor instructions are designed.


问:
Stateless Web Applications Defeat DBContext Somehow?
In Entity Framework, the DBContext class is said to implement the unit-of-work pattern. As I interpret this, it means that if you make a DBContext, manipulate its data, and then dispose of it, then these manipulations will either all succeed together or all fail together, and get rolled back. Moreover, there is the potential for a performance benefit, as the underlying infrastructure gets to see everything you're doing at once, and do things like combine operations. This instantiate/manipulate/dispose sequence would typically comprise a using block in most C# code.

This all seems eminently logical, but when I try to read about DBContext as it performs in an ASP.NET MVC application, I run into statements I just don't quite get, e.g.:

"DBContext relies on several managed features and flags that keep track of changes in items that have been queried from the datastore... [t]he stateless nature of ASP.NET MVC prevents the default functionality of Entity Framework from working, however."

(Developing ASP.NET MVC 4 Web Applications, Exam Reference 70-486 by William Penberthy, Microsoft, 2013, p. 5)

I'd really like some more specifics about this supposed breakdown in the "default functionality of Entity Framework". Am I to understand that if I build a using block around a DBContext and some manipulations thereon, say, in a controller method, then a trip through this using block no longer comprises a single unit-of-work? Can I no longer expect each set of manipulations to either get committed as a whole unit or rolled back as a whole unit under ASP.NET MVC?

Or, alternately, does the breakdown in the "default functionality of Entity Framework" relate solely to the performance benefits obtainable from the use of a DBContext? I guess one possible interpretation of the statement I'm asking about is just that multiple, concurrent requests (e.g. to my example controller method) won't have their database manipulations combined for increased performance.

For example, if 999 people update a single column of the same row in a database, in quick succession, then all of these updates will end up happening individually... which is something I wouldn't have thought required mentioning. It certainly doesn't mean that using blocks build around a DBContext work any differently in ASP.NET MVC.

In any case, if you understand the statement I quoted better than I do, then I would appreciate your help in understanding it.

答:
The problem amounts to maintaining server state in an application environment that is stateless by design.

Consider what happens when you implement a shopping cart.  Shopping carts involve several steps: you must choose the items you want (usually one at a time while looking at product pages), put in your address, select the shipping type, supply a method of payment, and finalize the order.

Each page that you submit to the server during this process is essentially a complete transaction.  REST architecture assumes that, once the request/response cycle is complete, there's nothing left to do.

To track progress on a shopping cart using a DBContext, one would have to open a DBContext, say, whenever the user puts their first item into the shopping cart.  The problem is, where do you hold this object open?  DBContexts are normally closed when the page is submitted.  What happens if several users open shopping carts?  Now I have to keep track of all those DBContexts.  What happens if someone abandons a shopping cart?

What we're really talking about are SESSIONS.  Martin Fowler talks extensively about SESSION state in his P of EAA book, including whether to store SESSION state on the server or the client, and the advantages and disadvantages of each approach.


问:
Securing service calls
I have a ServiceCallContext object that must be passed in as the first parameter of any service call. I would like to put a User object on the context object but I know I can't force the caller to send back the User object they received from the service and I can't prevent them from filling that in with any information they like.

So as I understand it, I would need to use a security token (via something like OAuth) to authenticate them and would always need to look up any User information I need on the service side after authentication rather than putting it on the context object.

However, I know it's common to make a hash for a data file in order to verify that its contents haven't been tampered with. Would it be reasonable to do this for user information I put on a context object so that I don't have to make a call to the persistence layer for every service call? What are the risks of doing it that way?

答:
A hash of the user's login information would essentially be a badly implemented security token. Since you still have to authenticate every single request, I don't see what you'd gain from rolling your own authentication. Use a well-tested solution like OAuth or XAuth.

You can easily and securely stop "middle men" from tampering or eavesdropping by using HTTPS.

Title: Securing service calls


问:
is a Model exactly the same as a Business Entity?
I've been programming for a long time now, and I have always seen Model classes exactly as a business entity. For instance: sales, users, products, orders, etc...

But I have come to certain source codes (specifically in MVVM applications in WPF) where Model not only include business entities, but several other types, and now I'm confused.

What exactly represents model classes, are they limited to business objects or what else do they include? If I could get a couple of examples, that'd be good.

答:
My understanding of MVVM is that the term model doesn't refer to a specific model, but to the entire domain model.

I think the confusion comes from the fact that many View Models (in my experience) exist to enable CRUD operations on an Entity.  That makes it seem like model refers only to a single entity model.

But a View Model doesn't need to be confined to that simple scenario.  The entirety of your domain data and logic (the domain model) could be exposed through a single View Model without violating MVVM.


问:
Should we avoid object creation in Java?
I was told by a colleague that in Java object creation is the most expensive operation you could perform. So I can only conclude to create as few objects as possible.

This seems somewhat to defeat the purpose of object oriented programming. If we aren't creating objects then we are just writing one long class C style, for optimization?

答: I did a quick microbenchmark regarding this and I have provided full sources in github.  My conclusion is that whether creating objects is expensive or not is not the issue, but continuously creating objects with the notion that the GC will take care of things for you will make your application trigger the GC process sooner. GC is a very expensive process and it is best to avoid it whenever possible and not try to push it to kick in.</p>


问:
What is the point of making a syntactic distinction between standard and user-defined types?
Although here I will refer specifically to C++ and Bjarne Stroustrup's naming conventions, in principle, I've seen that people use somewhat similar rules for other languages here and there.

So, the basic idea is that one should be able to distinguish standard types from user-defined types while reading the code. For instance, Bjarne Stroustrup suggests that one uses

an initial capital letter for types (e.g., Square and Graph)

which, taking into account that

The C++ language and standard library don't use capital letters

allows achieving the goal mentioned above.

But why do we need to do so? What can be the purpose of distinguishing standard and user-defined types?

I could not find any Bjarne Stroustrup's reasoning on that matter, and besides, I myself think in diametrically opposite way. :D I know, I know, "Who am I to dispute Stroustrup?" But, listen, a bunch of the C++ language features, e.g. operator overloading, serve the purpose to allow user-defined types a similar level of syntactic support as standard types. And then all this is baffled by a different naming discipline...

P.S. Not to mention that often one word is not enough to name a class and an underscore-separated word that starts with a capital letter looks so foreign.

答:
Naming conventions are about supporting human (i.e. programmer and maintainer) comprehension of the code.

UDTs can be specified so that declaration of variables, initialisation, expressions, and statements work on them differently than is the case for standard types.   For problem finding, it is useful for the maintainer to have some cue that some section of code might do funky things (e.g.  the implementation of a user-defined integral type used within some function might have a flaw in how it does addition).

There are many ways of providing such cues (comments, design specifications, etc).   The advantage of naming conventions is that they are present in the code, whereas comments can be omitted, out of date, etc.


问:
Should a lockfree queue use a condition variable?
Suppose I have a lockfree queue in a multithreaded setting. I already provide a try_dequeue() method which allows for an optional failure (communicated via the return type) if the queue is empty.

I've found it convenient to have an always-succeeding T dequeue() method which will not return while the queue is empty. As a consumer, I don't really care when I get my product, I just want to know as soon as one's available.

My implementation of dequeue() is pretty simple:

```<code>while (true) {
    if (try_dequeue succeeded) return result;
    std::unique_lock<std::mutex> lk(mtx_);
    cond_.wait(lk, [this]{ return !empty(); });
}
</code>```

Where cond_ is signalled by enqueuers and mtx_ guards cond_.

The excess serialization and between-dequeuer contention caused by lk seems to slow things down. empty() certainly doesn't need anything to be locked.

In any case, does cond_ seem out of place here? The only reason I'm hesitant to remove it is the case where there's a dequeuer (or multiple dequeuers) that are waiting for a new item to come in and are spinning idly on the CPU with no indication for the enqueuing thread to get priority.

It would seem that perhaps this_thread::yield() is more appropriate here, but the standard only guarantees that the method is a hint, so there is a possibility of starving here.

It appears that boost::lockfree::queue does not provide a dequeue-like method at all. Hopefully the nuclear option is avoidable.

As user rwong points out, we may consider a solution to this problem as a "hybrid" or "semi-blocking" approach because it would be desirable to have dequeuers block on empty queues, yet it would also be nice for enqueuers not to have to make a full context switch to the kernel at the same time.

Note: Yes, technically the inclusion of mtx_ in the queue removes the lockfree attribute, but I think this is an accurate characterization anyway since dequeue() is the only method that uses mtx_ (enqueuers signal without locking).

答:
You can use try_lock for signaling the cond_ when enqueueing. This will have a race condition that can be circumvented by making the wait timed.

The idea is that if the try_lock fails then either another enqueuer is also trying to wake the dequeuers so we might as well let him do the work or the dequeuer is trying to wait and he may or may not have check the condition yet. If he hasn't then fine he'll see the queue isn't empty and release and try again, if he has checked then he'll check again after the timeout expires.


问:
Closest Point to Moving Target
I have a target which is constantly moving, and only its current position is ever known.  I also have about one hundred objects surrounding it, and for each of these only the current position is known.

I am trying to find a more efficient way to find the closest object to my target at any given moment in time.  I have looked at a bunch of algorithms, but none of them seem to fit this (nearest neighbor, closest pair of points, etc.).

My objects are unsorted.  It does not need to be exact.  The closest I have been able to think of is the brute force algorithm:

```<code>Objects objects = MyListOfUnsortedObjects();
Object closestObj = objects[0];
for each (Object obj in objects){
    if(obj is closer than closestObj){
        closestObj = obj;
    }
}
return closestObj;
</code>```

Obviously, this is terribly inefficient.  Would I be better off sorting and then dividing and conquering?  Or am I way off base?

Any suggestions?

答:
The solution is some form of spatial partitioning, which is arguably equivalent to "sort it and then divide and conquer", so you're not off-base at all.

There are many data structures used for this, such as quadtrees, BSPs, k-d trees, and so on. In my personal experience people normally recommend the quadtree as a good starting point.

Title: Closest Point to Moving Target


答:
One reason I use capitalized words for types, is to distinguish variables from types. This allows to declare a variable with, apart from the capitalization, the same name:

```<code>Foo foo;
Graph graph;
</code>```

This can be useful for classes of which only one instance is used in each context, e.g. configuration settings.

Title: What is the point of making a syntactic distinction between standard and user-defined types?

Body:
Although here I will refer specifically to C++ and Bjarne Stroustrup's naming conventions, in principle, I've seen that people use somewhat similar rules for other languages here and there.

So, the basic idea is that one should be able to distinguish standard types from user-defined types while reading the code. For instance, Bjarne Stroustrup suggests that one uses

an initial capital letter for types (e.g., Square and Graph)

which, taking into account that

The C++ language and standard library don't use capital letters

allows achieving the goal mentioned above.

But why do we need to do so? What can be the purpose of distinguishing standard and user-defined types?

I could not find any Bjarne Stroustrup's reasoning on that matter, and besides, I myself think in diametrically opposite way. :D I know, I know, "Who am I to dispute Stroustrup?" But, listen, a bunch of the C++ language features, e.g. operator overloading, serve the purpose to allow user-defined types a similar level of syntactic support as standard types. And then all this is baffled by a different naming discipline...

P.S. Not to mention that often one word is not enough to name a class and an underscore-separated word that starts with a capital letter looks so foreign.

Body:
One reason I use capitalized words for types, is to distinguish variables from types. This allows to declare a variable with, apart from the capitalization, the same name:

Foo foo;
Graph graph;

This can be useful for classes of which only one instance is used in each context, e.g. configuration settings.


问:
If you take a year or two out from being a developer, is it really that hard to get back into it?
I've been working as a developer for about 3 years now (straight from uni), I'm wondering, if I take a year or two out would it be impossible to get back into the industry?

I didn't get the gap year thing out of my system after uni, and I'm thinking that I should probably do it before I hit 30 (24 now), my main concern is that if I leave the industry now, I might not get back into it at all and end up working some dead end job.

The way I see things is, that general concepts / design patterns etc remain similar over the years, and it is mostly coding syntax / actual implementation that evolves, so it shouldn't move on dramatically.

Also, women developers (yes there are some out there!) take years out to have kids and still carry on with their career afterwards, so it can't be impossible.

Ultimatum : Would taking a year or two out destroy the (small) career I've built up so far?

答:
Will it be harder to find a job? Sure. An employer is likely going to prefer someone who is working in the field over someone who worked in the field.

But that said, it's not uncommon at all, I would think, for people to be out of work for a year while looking for a job (bad region, recession, etc.) nor is it uncommon for people to take sabbaticals.


问:
Strategy to use version control on a modular system
Let's suppose (for simplicity) that we have an application featuring client and server; is there a better idea to use one repository for both or a pair of separate repositories?

Mixing them will probably make easier to track correlated changes and maintain correlated branches (i.e. protocol evolution), but on the other hand will make the individual development more cluttered...

答:
The simplest approach is to use a single repository, so unless you like complexity for complexity's sake, then that should be the default choice in the absence of compelling arguments otherwise.

Is the client and server development going to be carried out by different organisations? Will there be multiple implementations of the client (or server)? Is the client open source and the server implementation secret? If the answer to all these questions is "No", then anything more complex than a single repository is likely to bring only inconvenience for no benefit.

If you do choose to maintain separate codebases, you will need clear policies about how this is administered, in order to avoid incompatibilities and dependency hell. After working through the first few hiccups, you might end up discovering that the safest thing is to always check out both repositories together, build them together, and deploy them together...which obviously defeats the whole purpose of separating them!

Modularity is a nice property to have, but splitting repositories is not a tool to achieve that. As the previous paragraph implies, you can have highly coupled components that are split over multiple codebases (undesirable), and likewise you can have highly modular components within the same codebase (desirable).

On more than one occasion, I have advocated (successfully) for my team to merge existing git repositories, because it simplified development and deployment.


问:
How to avoid chatty interfaces
Background:
I am designing a server application and creating separate dll's for different subsystems. To simplify things, let's say I have two subsystems: 1) Users 2) Projects

Users's public interface has a method like:

```<code>IEnumerable<User> GetUser(int id);
</code>```

And Projects's public interface has a method like:

```<code>IEnumerable<User> GetProjectUsers(int projectId);
</code>```

So, for example, when we need to display the users for a certain project, we can call GetProjectUsers and that will give back objects with sufficient info to show in a datagrid or similar.

Problem:
Ideally, the Projects subsystem shouldn't also store user info and it should just store Ids of the users participating in a project. In order to serve the GetProjectUsers, it needs to call GetUser of the Users system for each user id stored in its own database. However, this requires a lot of separate GetUser calls, causing a lot of separate sql queries inside the User subsystem. I haven't really tested this but having this chatty design will affect the scalability of the system.

If I put aside the separation of the subsystems, I could store all info in a single schema accessable by both systems and Projects could simply do a JOIN to get all project users in a single query. Projects would also need to know how to generate User objects from the query results. But this breaks the separation which has many advantages.

Question:
Can anyone suggest a way to keep the separation while avoiding all these individual GetUser calls during GetProjectUsers?

For example, one I idea I had was for Users to give external systems the ability to "tag" users with a label-value pair, and to request users with a certain value, e.g.:

```<code>void AddUserTag(int userId, string tag, string value);
IEnumerable<User> GetUsersByTag(string tag, string value);
</code>```

Then the Projects system could tag each user as they are added to the project:

```<code>AddUserTag(userId,"project id", myProjectId.ToString());
</code>```

and during GetProjectUsers, it could request all the project users in a single call:

```<code>var projectUsers = usersService.GetUsersByTag("project id", myProjectId.ToString());
</code>```

the part I'm not sure about this is: yes, Users is agnostic of projects but really the information about project membership is stored in the Users system, not Projects. I just doesn't feel natural so I'm trying to determine if there's a big disadvantage here that I'm missing.

答:
What is missing in your system is the cache.

You say:

However, this requires a lot of separate GetUser calls, causing a lot of separate sql queries inside the User subsystem.

The number of calls to a method doesn't have to be the same as the number of SQL queries. You get the information about the user once, why would you query for the same information again if it didn't change? Very probably, you may even cache all the users in memory, which would result in zero SQL queries (unless a user changes).

On the other hand, by making Projects subsystem query both the projects and the users with an INNER JOIN, you introduce an additional issue: you are querying the same piece of information in two different locations in your code, making cache invalidation extremely difficult. As a consequence:

Either you won't introduce cache at all any time later,

Or you will spend weeks or months studying what should be invalidated when a piece of information changes,

Or you will add cache invalidation in straightforward locations, forgetting the other ones and resulting in difficult to find bugs.

Rereading your question, I notice a keyword I missed the first time: scalability. As a rule of thumb, you may follow the next pattern:

Ask yourself whether the system is slow (i.e. it violates a non-functional requirement of performance, or is simply a nightmare to use).

If the system is not slow, don't bother about performance. Bother about clean code, readability, maintainability, testing, branch coverage, clean design, detailed and easy to understand documentation, good code comments.

If yes, search for the bottleneck. You do that not by guessing, but by profiling. By profiling, you determine the exact location of the bottleneck (given that when you guess, you may nearly every time get it wrong), and may now focus on that part of the code.

Once the bottleneck found, search for solutions. You do that by guessing, benchmarking, profiling, writing alternatives, understanding compiler optimizations, understanding optimizations that are up to you, asking questions on Stack Overflow and moving to low-level languages (including Assembler, when necessary).

What is the actual issue with Projects subsystem asking for info to Users subsystem?

The eventual future scalability issue? This is not an issue. Scalability may become a nightmare if you start merging everything into one monolithic solution or querying for the same data from multiple locations (as explained below, because of the difficulty to introduce cache).

If there is already a noticeable performance issue, then, step 2, search for the bottleneck.

If it appears that, indeed, the bottleneck exists and is due to the fact that Projects requests for users through Users subsystem (and is situated at database querying level), only then should you search for an alternative.

The most common alternative would be to implement caching, drastically reducing the number of queries. If you're in a situation where caching doesn't help, than further profiling may show you that you need to reduce the number of queries, or add (or remove) database indexes, or throw more hardware, or redesign completely the whole system.

Title: How to avoid chatty interfaces


问:
How useful are IT headhunters/recruiters when looking for a new job?
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?

答:
I was placed by a recruiter in my current position. He is a specialist in programming jobs, and seems like he worked as a programmer himself. His business seems to be providing high quality candidates.

He called me up and did a whole prescreening process, asking a whole lot of programming questions from the most basic to the very technical. Then once he was convinced I actually knew what I said I did, then he forwarded my details for an appropriate position.

If you can get a recruiter like that, then yes they are very useful.


问:
Choose approaches for updating an object
Say I have a simple object created by from user input:

```<code>var input = { url: 'http://example.com/', path: 'abc', user: 'adam' };
</code>```

And I am to write function(s) that update url and path properties according to some business logic, there are many approaches:

A. functional

```<code>input.url = validate(input);
input.path = convert(input);
</code>```

B. side-effect

```<code>update(input);
</code>```

C. create a new object internally

```<code>input = process(input);
</code>```

For javascript, is it always better to use the functional approach, for easier debug and speed? Or a general thought process on deciding which is more appropriate.

答:
I wouldn't call the first approach functional. One of the key aspects of the functional paradigm is to avoid mutable state. So any kind of reassignment is not in the functional style. Once you've defined input is, you wouldn't change it. This might be more functional:

```<code>const validatedInput = {
    url: validate(input.url),
    path: convert(input.path),
    user: input.user
};
</code>```

The advantages would be code that's easier to reason about. You know what input and validatedInput are and that they won't change after being created. However, this will be slower and use more memory than the other approaches, using plain JavaScript objects at least, as a whole new object is created. It's possible that the change in performance is negligible in this instance but there are likely to be cases where it's not.

Personally, I would go with a functional approach wherever possible to ensure clarity and correctness. But in cases where that is likely or proven to be too slow, use some mutation in a very limited scope. For example, change a variable only within a certain function. This will limit the likelihood of subtle bugs caused by interactions between lines of code that are far apart or in different files.

Body:
I wouldn't call the first approach functional. One of the key aspects of the functional paradigm is to avoid mutable state. So any kind of reassignment is not in the functional style. Once you've defined input is, you wouldn't change it. This might be more functional:

const validatedInput = {
    url: validate(input.url),
    path: convert(input.path),
    user: input.user
};

The advantages would be code that's easier to reason about. You know what input and validatedInput are and that they won't change after being created. However, this will be slower and use more memory than the other approaches, using plain JavaScript objects at least, as a whole new object is created. It's possible that the change in performance is negligible in this instance but there are likely to be cases where it's not.

Personally, I would go with a functional approach wherever possible to ensure clarity and correctness. But in cases where that is likely or proven to be too slow, use some mutation in a very limited scope. For example, change a variable only within a certain function. This will limit the likelihood of subtle bugs caused by interactions between lines of code that are far apart or in different files.


问:
Throw exception or let code fail
I am wondering if there are any pros and cons against this style:

```<code>private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}
</code>```

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

答:
All answers add valuable ideas, I would like to combine them:

Decide on the intended and expected semantics of the LoadMaterial() operation.  At least the following options exist:

A precondition on name ∉ LoadedMaterials: →

When precondition is violated, the effect of LoadMaterial() is unspecified
(as in answer by ComicSansMS).  This allows to most freedom in the
implementation and future changes of LoadMaterial().  Or,

effects of calling LoadMaterial(name) with name ∈ LoadedMaterials are
specified; either:

the specification states that an exception is thrown; or

the specification states that the result is idempotent (as in answer
by Karl Bielefeldt),

possibly returning a "has the collection changed" boolean (as
proposed by User949300 and proposed (in some
interpretations) by Mrlveck.

When having decided on the semantics, you must choose an implementation.  The following options and considerations where proposed:

Throw a custom exception (as suggested by Ixrec) →

The benefit is that your "custom" exception has an error message
  that's meaningful to anyone calling this function — Ixrec and User16547

To avoid the cost of repeatedly checking name ∉ LoadedMaterials you
can follow Marc van Leeuwen's advise:

... Instead consider plunging into _Materials.Add unconditionally, then
  catch a potential error and in the handler throw a different one.

Let Dictionay.Add throw the exception →

The exception throwing code is redundant. — Jon Raynor

Although, most voters agree more with Ixrec

Additional reason to to choose this implementation are:

that callers can already handle ArgumentException exceptions, and

to avoid loosing stack information.

But if these two reasons are important you can also derive your custom
exception from ArgumentException and use the original as a chained
exception.

Make LoadMaterial() idempotent as anwser by Karl Bielefeldt and
upvoted most often (75 times).

possibly returning a "has the collection changed" boolean (as
proposed by User949300 and proposed (in some
interpretations) by Mrlveck.

The implementation options for this behaviour:

Check with Dictionary.ContainsKey()

Always call Dictionary.Add() catch the ArgumentException it throws
when the key to insert already exists and ignore that exception.  Document
that the ignoring of the exception is what you intent to do and why.

When LoadMaterials() is (almost) always called once for each name,
this avoids the cost repeatedly checking name ∉ LoadedMaterials cf.
Marc van Leeuwen.  However,

when LoadedMaterials() is often called multiple times for the same
name, this incurs the (expensive) cost of throwing the
ArgumentException and stack unwinding.

I thought that there existed a TryAdd-method analogue to TryGet()
which would have allowed you to avoid the expensive exception throwing and
stack unwinding of failing calls to Dictionary.Add.

But this TryAdd-method appears not to exist.

Title: Throw exception or let code fail


问:
Choosing between Single or multiple projects in a git repository?
In a git environment, where we have modularized most projects, we're facing the one project per repository or multiple projects per repository design issue. Let's consider a modularized project:

```<code>myProject/
   +-- gui
   +-- core
   +-- api
   +-- implA
   +-- implB
</code>```

Today we're having one project per repository. It gives freedom to

release individual components

tag individual components

But it's also cumbersome to branch components as often branching api requires equivalent branches in core, and perhaps other components.

Given we want to release individual components can we still get the similar flexibility by utilizing a multiple projects per repository design.

What experiences are there and how/why did you address these issues?

答:
For me, the main difference in using one or more than one repository are the answers to the following questions:

Are the multiple parts developed by the same team, have the same release cycle, the same customer? Then there are less reasons to split the one repository.

Are the multiple parts highly dependent on each other? So splitting model, controller and UI (even when they are different parts) is not very sensible, due to the high dependency on each other. But if 2 parts only have a small dependency, which is implemented by a stable interface that is only changed every few years, so it would be wise to divide the 2 parts in 2 repositories.

Just as an example, I have a small application (client only), that checks the "quality" of a Subversion repository. There is the core implementation, that could be started from the command line, and works well with Java 6. But I have started to implement a UI, that uses JavaFX as part of Java 8. So I have split the 2, and created a second repository (with a second build process), with different schedule, ...

I like the answers above (voted them up), but I think they are not the whole true story. So I wanted to add the arguments for splitting repositories as well.  So the real answer (when to split) may be somewhere in the middle ...


问:
Splitting single Class into multiple Classes
I am writing automated test scripts with Selenium Webdriver (Python) and I try to follow the correct programming practices, specifically the Object Oriented methodologies, where possible.

At the moment, I represent every test scenario as a single Class. That class is basically has the following structure:

Imports (Selenium modules as well as Python stuff)

Logging configuration

Class definition that includes the below:

Driver Instance initialization

Specific test scenario variables

Generic methods (some wrappers I created that are used in multiple testing scenarios)

Specific application methods

So that's something like that:

```<code>imports
logging

class AppName(object):
    def __init__(self):
        self.driver = webdriver.Chrome()

        self.localAppVar = "..."
        ...

    def genericFunction(self):
        #This is a generic function that is going to be used in many other test scenarios as well as in this one

    def specificAppFunction(self):
        #This is a specific application function. This function is only relevant withing this test. This function will use "genericFunction" internally.

app = AppName() #Initialize an AppName object
app.specificAppFunction()

...
</code>```

What I would like to do is to separate the above Class into 2 new Classes and a launcher file:

Generic functions Class. This one will define the driver object as well as all generic functions that are going to be used by multiple tests.

Specific functions Class. This one will contain the application specific function that are irrelevant for other applications.

Launcher file that will initialize\instantiate the above mentioned classes and will control the scenario on a higher level. (kind of main in C if you like).

The above idea makes sense to me but I am a bit confused about the practical approach. How should that be implemented properly?

I was thinking about following options:

Creating a generic class instance withing a specific application class.

Make the generic class a base class and then inherit it by specific application class.

I am not sure about pros and cons of both approaches and currently a bit stuck with the implementation. It will be great if someone could give me some insight on how such task should be implemented.

Hopefully my question is clear enough. If it's not, please comment and I will elaborate or/and edit.

答: Generic functions should not go into classes. Python is not Java, it does not require pure functions to live inside classes. Only use classes if you want to store state of some kind. Put the functions into a standalone utility module, and import that into the module that contains your test classes.

OwnerDisplayName: Eugene S

OwnerDisplayName: Daniel Roseman


问:
Are there well-known PowerShell coding conventions?
Are there any well-defined conventions when programming in PowerShell?

For example, in scripts which are to be maintained long-term, do we need to:

Use the real cmdlet name or alias?

Specify the cmdlet parameter name in full or only partially (dir -Recurse versus dir -r)

When specifying string arguments for cmdlets do you enclose them in quotes (New-Object 'System.Int32' versus New-Object System.Int32

When writing functions and filters do you specify the types of parameters?

Do you write cmdlets in the (official) correct case?

For keywords like BEGIN...PROCESS...END do you write them in uppercase only?

It seems that MSDN lack coding conventions document for PowerShell, while such document exist for example for C#.

答:
Microsoft has written and published a very good set of Cmdlet Development Guidelines

Excerpt:

The topics in this section provide development guidelines that you can use to produce well-formed cmdlets. By leveraging the common functionality provided by the Windows PowerShell runtime and by following these guidelines, you can develop robust cmdlets with
  minimal effort and provide the user with a consistent experience. Additionally, you will reduce the test burden because common functionality does not require retesting.

In This Section

Required Development Guidelines

Strongly Encouraged Development Guidelines

Advisory Development Guidelines

These guidelines are not limited to any language (they do not mention a language), and are perfectly applicable when writing Cmdlets in PowerShell.

Using these guidelines will help you write clear, discoverable, usable and reuseable Cmdlets. I find after creating several PowerShell modules following these guidelines is not hard, and helped me become a better PowerShell developer. That skill is directly usable when writing simple scripts as well.


问:
Describe closures to a non programmer
I will have a presentation about closures, and a non programmer friend of mine asked, what closures are. With what analogy would you describe that?
I mean "take a look at the lamba calculus" wouldn't be that nice.</p>

答:
Based on your comment I'm going to assume the target audience doesn't fully understand what a "function" is either, so here are my best attempts at defining "function" and "closure" to somebody who has not ever written code of any sort.

A function is a piece of code that I can give some data, and it will
give me back a result. For instance, I might have a function to compute
the square root of a number.

A closure is one way of making a function that can also "save" data
and "remember" it later. For instance, I might have one closure to
change an image's size, and another to check what the image's size
currently is.

Title: Describe closures to a non programmer


问:
How to separate different plugins with the same name
I'm writing the installation code of my modular web application and I stumbled on writing the update code for the plugins.

The problem I am having is: how do you know if the plugin is already installed? Developers can give their plugin a very basic name like: "News". There will probably be more plugins with that name and now the system think it's the same plugin and will overwrite it.

What can I provide to the plugin to make it unique when installing and knowing it's an update when a user provides a new installation package?

The idea is that there is only an installation service, not an install and update.
The system should be able to know if it's a new installation or a update.

答:
You've correctly noticed that a package has a name, an author, and a version. These three uniquely identify a package. If you need to map this to a file system, you could choose a structure such as

```<code>./plugins/author-id/package-id/version/
</code>```

This allows two authors to offer different packages under the same name, and multiple versions of one package to be installed at once. If no support for multiple versions is needed, you can drop the version level.

The question is how to assign author IDs. Java uses the nice trick of simply using domain names, since they should be unique anyway. This works well if every developer can be expected to own a domain (this would seem to be the case in web application development). However, Java reverses the order of subdomains so that the hierarchically most important information is at the front of the name. The domain dev.example.com is mapped to the prefix com.example.dev.

It is useful to have a file in each package that describes metadata. This file could declare information about dependencies, a summary of what this package does, an a version number.

With this structure, installing or upgrading a package would work like this:

The new package is unpacked into a temp directory, and the metadata is read.

The directory of installed modules is searched for a package of same name from the same author. If no match is found, this package is installed.

If a match was found and the version number is higher, then the old package is removed and the new package installed.

Before installation, the presence of dependencies is verified.

There are tons of package managers which you can steal ideas from. Take a look at CPAN (Perl), pip (Python), gem (Ruby), npm (Node.js). Each of these have some strengths and some weaknesses.

Body:
You've correctly noticed that a package has a name, an author, and a version. These three uniquely identify a package. If you need to map this to a file system, you could choose a structure such as

./plugins/author-id/package-id/version/

This allows two authors to offer different packages under the same name, and multiple versions of one package to be installed at once. If no support for multiple versions is needed, you can drop the version level.

The question is how to assign author IDs. Java uses the nice trick of simply using domain names, since they should be unique anyway. This works well if every developer can be expected to own a domain (this would seem to be the case in web application development). However, Java reverses the order of subdomains so that the hierarchically most important information is at the front of the name. The domain dev.example.com is mapped to the prefix com.example.dev.

It is useful to have a file in each package that describes metadata. This file could declare information about dependencies, a summary of what this package does, an a version number.

With this structure, installing or upgrading a package would work like this:

The new package is unpacked into a temp directory, and the metadata is read.

The directory of installed modules is searched for a package of same name from the same author. If no match is found, this package is installed.

If a match was found and the version number is higher, then the old package is removed and the new package installed.

Before installation, the presence of dependencies is verified.

There are tons of package managers which you can steal ideas from. Take a look at CPAN (Perl), pip (Python), gem (Ruby), npm (Node.js). Each of these have some strengths and some weaknesses.


问:
When to Use Shared Libraries
Note: I'm not sure if this question is more suitable for Stack Overflow or Programmers.  The thought process behind putting it here was that it doesn't actually relate to coding itself.

I noticed a small freeware utility I have on my computer uses a couple of DLLs.  From their names ("RenderAllChunks" and "RenderSlice"), it looks like they're being used just for specific functions.  If outsourcing program-specific functions is really necessary, wouldn't it be better to just stuff them in a separate header file?  It seems quite pointless to go through all the trouble of compiling, linking and distributing DLLs just for one function.

Is it bad to use shared libraries for small projects?

When/why are shared libraries preferable over static libraries (or even header files)?

答: My rule is if it is a logical chunk of code that can perform a function or groups of functions that has a possibility of reuse it should be in a dll. dll Should not contain only one function or functions that can only work dependent on other functions in another dll. </p>

Title: When to Use Shared Libraries