问:
Creating an interface of interfaces
Background:

We have a class that both listens on a socket and sets values on itself based on what it reads off the socket.  I believe that adheres to SRP.

To adhere to ISP we created one interface for socket stuff (eg. StartListening, StopListening) and another interface which contains read only fields for the values read off the socket and modified our class to implement both.

The idea was that we pass ISocketStuff (not its real name) to code that needs to start/stop listening and we pass ISocketValues to places that need to know the values.

The Question:

I was reviewing a co-worker's code and he had something like:

public interface ISocketStuffAndValues : ISocketStuff, ISocketValues {};

And he was passing it to a constructor.

This felt wrong, but I couldn't think of any reason not to do this.  It was to work around a thorny design issue, he could have just passed in ISocketValues, but he wanted to do it that and I couldn't tell him why it was a poor choice.

So, is it a poor choice?  What reasons could I have given for just passing in ISocketValues and not creating ISocketStuffAndValues?

答:
Your coworker was trying to reduce another code smell; having many and/or redundant parameters in method calls. If you adhere to ISP, SRP and DIP by allowing different implementations of the two interfaces to be passed into a method that needs an implementation of each, but you have one class that implements both interfaces, then when you call this method you'll be passing the same instance twice, once as an ISocketStuff and once as an ISocketValues. Your coworker thought that smelled bad (and he's right), and refactored to allow a single passed reference.

It's always a good idea, instead of blindly following the SOLID rules, to remind yourself why these rules exist; what's their purpose? in the case of ISP, the purpose of the rule is to prevent having to make changes to a consumer of an interface that does not consume the particular method of that interface that is being changed. However, if all usages need all methods, that's clear evidence that the methods of the interface are cohesive, at least as far as your system is concerned, and they don't need to be split up.

The right answer to your question thus depends on the answer to this question: will all consumers of an implementation of ISocketStuff be expected to need ISocketValues as well?

If so, then your assertion that these need to be separate interfaces is unfounded. If every implementation of one implements the other, and every consumer of one consumes both, then if the interfaces change, all implementations and usages of both interfaces will change, and so you gain nothing in segregating them. The members of both interfaces would be highly cohesive in a single interface. The code smell of re-joining both interfaces into a child interface used by implementations and consumers is your red flag that you have over-segregated given the needs of your system, and ISocketStuff should simply expose the members of ISocketValues.

If not, then you have other problems. It's not bad, per se, for an object to implement multiple interfaces; that's part of why interfaces exist and why implementing many of them is allowed by language specs in the first place. However, in this case, an object with the single responsibility of socket listening and an object with the single responsibility of storing status/data values are two objects with two responsibilities and should not have a single, shared implementation. Instead, consider making the implementation of ISocketValues a "thin" data class (a DTO), that is produced by a method exposed by ISocketStuff.

ISocketValues could be cheap and disposable, and you get one whenever you need an update and then throw it away, or alternately instances of ISocketValues could be longer-lived and receive "live" updates from ISocketStuff. Which is better depends on how you prefer to use both interfaces, and which of the interfaces you want other objects to have to know about. If most or all consumers need to control the listener based on updates, then they need ISocketStuff; make ISocketValues' implementation a DTO, expose a factory method to generate them, and pass ISocketStuff around to consumers, who can generate ISocketValues instances as needed. If all your consumers need is data/status info, then ISocketStuff is too much power; the owner of ISocketStuff that is injecting these dependencies into callers should generate and pass "live-updating" ISocketValues implementations to consumers, who will no longer have to know ISocketStuff even exists.

Title: Creating an interface of interfaces


问:
Making Simple IF Statements Shorter
If we assume we have this little snippet of code:

```<code>string str = "checked";
bool test1;

if (str == "checked")
{
    test1 = true;
}
else
{
    test1 = false;
}
</code>```

Is it bad practice to change a simple statement like this to the following?:

```<code>bool test2 = (str == "checked");
</code>```

Because they work exactly the same, and work as required, so I can't imagine how it would be. However, as a young, inexperienced programmer I am not aware of whether such a thing is frowned upon or not. Can anyone tell me, if this is NOT ok, why not?

The following test program:

```<code>using System;

public class Test
{

    public static void Main()
    {
        string str = "checked";

        bool test1;

        if (str == "checked")
        {
            test1 = true;
        }
        else
        {
            test1 = false;
        }

        bool test2 = (str == "checked");

        bool test3 = (str != "checked");

        Console.WriteLine(test1.ToString());
        Console.WriteLine(test2.ToString());
        Console.WriteLine(test3.ToString());
    }
}
</code>```

Outputs:

```<code>True
True
False
</code>```

Any insight etc is appreciated.

答:
Who will see your code?

If you think that others who might see your code will be confused with one-line if statements, then use the full spelled-out version.  Also, if you think that you might accidentally reverse the logic, then spell it out.

Example:

At a previous job, I had coworkers that required the full, spelled out logic.  When they tried to use the one-liners, they would get the logic backwards on a regular basis.  Where I'm at now, the company is filled with intelligent people who would very rarely (if ever) make that mistake.  Here, we nest the ternary if statements with no confusion.

ContentLicense: CC BY-SA 3.0

Title: Making Simple IF Statements Shorter


问:
In API design, when to use/avoid ad hoc polymorphism?
Sue is designing a JavaScript library, Magician.js. Its linchpin is a function which pulls a Rabbit out of the argument passed.

She knows its users may want to pull a rabbit out of a String, a Number, a Function, perhaps even a HTMLElement. With that in mind, she could design her API like so:

The strict interface

```<code>Magician.pullRabbitOutOfString = function(str) //...
Magician.pullRabbitOutOfHTMLElement = function(htmlEl) //...
</code>```

Each function in the above example would know how to handle the argument of the type specified in the function name/parameter name.

Or, she could design it like so:

The "ad hoc" interface

```<code>Magician.pullRabbit = function(anything) //...
</code>```

pullRabbit would have to account for the variety of different expected types that the anything argument could be, as well as (of course) an unexpected type:

```<code>Magician.pullRabbit = function(anything) {
  if (anything === undefined) {
    return new Rabbit(); // out of thin air
  } else if (isString(anything)) {
    // more
  } else if (isNumber(anything)) {
    // more
  }
  // etc.
};
</code>```

The former (strict) seems more explicit, perhaps safer, and perhaps more performant -- as there are little or no overheads for type checking or type conversion. But the latter (ad hoc) feels simpler looking at it from the outside, in that it "just works" with whatever argument the API consumer finds convenient to pass to it.

For the answer to this question, I'd like to see specific pros and cons to either approach (or to a different approach altogether, if neither is ideal), that Sue should know which approach to take when designing her library's API.

答:
When you write, Magician.pullRabbitOutOfInt, it documents what you thought about when you wrote the method.  The caller will expect this to work if passed any Integer.  When you write, Magician.pullRabbitOutOfAnything, the caller doesn't know what to think and has to go digging into your code and experimenting.  It might work for an Int, but will it work for a Long?  A Float?  A Double?  If you are writing this code, how far are you willing to go?  What kinds of arguments are you willing to support?

Strings?

Arrays?

Maps?

Streams?

Functions?

Databases?

Ambiguity takes time to understand.  I'm not even convinced that it's faster to write:

```<code>Magician.pullRabbit = function(anything) {
  if (anything === undefined) {
    return new Rabbit(); // out of thin air
  } else if (isString(anything)) {
    // more
  } else if (isNumber(anything)) {
    // more
  } else {
      throw new Exception("You can't pull a rabbit out of that!");
  }
  // etc.
};
</code>```

Vs:

```<code>Magician.pullRabbitFromAir = fromAir() {
    return new Rabbit(); // out of thin air
}
Magician.pullRabbitFromStr = fromString(str)) {
    // more
}
Magician.pullRabbitFromInt = fromInt(int)) {
    // more
};
</code>```

OK, so I added an exception to your code (which I highly recommend) to tell the caller that you never imagined they would pass you what they did.  But writing specific methods (I don't know if JavaScript lets you do this) is no more code and much easier to understand as the caller.  It sets up realistic assumptions about what the author of this code thought about, and makes the code easy to use.

Body:
When you write, Magician.pullRabbitOutOfInt, it documents what you thought about when you wrote the method.  The caller will expect this to work if passed any Integer.  When you write, Magician.pullRabbitOutOfAnything, the caller doesn't know what to think and has to go digging into your code and experimenting.  It might work for an Int, but will it work for a Long?  A Float?  A Double?  If you are writing this code, how far are you willing to go?  What kinds of arguments are you willing to support?

Strings?

Arrays?

Maps?

Streams?

Functions?

Databases?

Ambiguity takes time to understand.  I'm not even convinced that it's faster to write:

Magician.pullRabbit = function(anything) {
  if (anything === undefined) {
    return new Rabbit(); // out of thin air
  } else if (isString(anything)) {
    // more
  } else if (isNumber(anything)) {
    // more
  } else {
      throw new Exception("You can't pull a rabbit out of that!");
  }
  // etc.
};

Vs:

Magician.pullRabbitFromAir = fromAir() {
    return new Rabbit(); // out of thin air
}
Magician.pullRabbitFromStr = fromString(str)) {
    // more
}
Magician.pullRabbitFromInt = fromInt(int)) {
    // more
};

OK, so I added an exception to your code (which I highly recommend) to tell the caller that you never imagined they would pass you what they did.  But writing specific methods (I don't know if JavaScript lets you do this) is no more code and much easier to understand as the caller.  It sets up realistic assumptions about what the author of this code thought about, and makes the code easy to use.


答:
Answering under the assumption that this boolean statement will always be this simple, I have no doubt that the simplified one-liner:

```<code>bool test2 = (str == "checked");
</code>```

would be sufficient, and it definitely produces fewer lines of IL. In my experiment with Mono I found the one-line statement produced:

```<code>IL_0000: ldstr "test"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr "test"
IL_000c: call bool [mscorlib]System.String::op_Equality(string, string)
IL_0011: stloc.1
IL_0012: ldloc.1
</code>```

While the traditional if-else statement produced:

```<code>IL_0000: ldstr "test2"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr "test2"
IL_000c: call bool [mscorlib]System.String::op_Equality(string, string)
IL_0011: brfalse IL_001d

IL_0016: ldc.i4.1
IL_0017: stloc.1
IL_0018: br IL_001f

IL_001d: ldc.i4.0
IL_001e: stloc.1

IL_001f: ldloc.1
IL_0020: ret
IL_0013: ret
</code>```

It appears that in my case the Mono compiler created several subroutines and manages a stack of calls in order to handle the if-else.

That being said, if your boolean operation becomes any more complex, then for readability's sake, in a professional development environment, I would at least change it to:

```<code>if (/*complex boolean operation*/)
    // set state in case of true evaluation
else
    // set state in case of false evaluation
</code>```

Without further context I can't provide you with a better solution.

Title: Making Simple IF Statements Shorter

Body:
If we assume we have this little snippet of code:

```<code>string str = "checked";
bool test1;

if (str == "checked")
{
    test1 = true;
}
else
{
    test1 = false;
}
</code>```

Is it bad practice to change a simple statement like this to the following?:

```<code>bool test2 = (str == "checked");
</code>```

Because they work exactly the same, and work as required, so I can't imagine how it would be. However, as a young, inexperienced programmer I am not aware of whether such a thing is frowned upon or not. Can anyone tell me, if this is NOT ok, why not?

The following test program:

```<code>using System;

public class Test
{

    public static void Main()
    {
        string str = "checked";

        bool test1;

        if (str == "checked")
        {
            test1 = true;
        }
        else
        {
            test1 = false;
        }

        bool test2 = (str == "checked");

        bool test3 = (str != "checked");

        Console.WriteLine(test1.ToString());
        Console.WriteLine(test2.ToString());
        Console.WriteLine(test3.ToString());
    }
}
</code>```

Outputs:

```<code>True
True
False
</code>```

Any insight etc is appreciated.

Body:
Answering under the assumption that this boolean statement will always be this simple, I have no doubt that the simplified one-liner:

bool test2 = (str == "checked");

would be sufficient, and it definitely produces fewer lines of IL. In my experiment with Mono I found the one-line statement produced:

IL_0000: ldstr "test"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr "test"
IL_000c: call bool [mscorlib]System.String::op_Equality(string, string)
IL_0011: stloc.1
IL_0012: ldloc.1

While the traditional if-else statement produced:

IL_0000: ldstr "test2"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr "test2"
IL_000c: call bool [mscorlib]System.String::op_Equality(string, string)
IL_0011: brfalse IL_001d

IL_0016: ldc.i4.1
IL_0017: stloc.1
IL_0018: br IL_001f

IL_001d: ldc.i4.0
IL_001e: stloc.1

IL_001f: ldloc.1
IL_0020: ret
IL_0013: ret

It appears that in my case the Mono compiler created several subroutines and manages a stack of calls in order to handle the if-else.

That being said, if your boolean operation becomes any more complex, then for readability's sake, in a professional development environment, I would at least change it to:

if (/*complex boolean operation*/)
    // set state in case of true evaluation
else
    // set state in case of false evaluation

Without further context I can't provide you with a better solution.


问:
How can I keep a production Python environment secure?
Most of my work is creating websites in Django (a Python web framework) and deploying them to my own or clients' servers. I work from a virtualenv to separate site from system packages and have perhaps 60-80 packages installed in there and that lot is  shared between two-dozen sites.

This obvious limitation to this approach is needing to test every site if I upgrade a package it uses. I consider that a fair trade-off for not needing to keep on top of umpteen separate virtualenvs.

And that is essentially my whole problem. How on earth are you supposed to keep on top of virtualenv deployments? People just seem to treat them like a dumping ground but if the programming universe has learnt anything this past week from the Ruby on Rails explosion, using old versions of software is unacceptable.

I have a simple script that attempts to check for current package versions with the latest pip counterpart but it's quite inacurrate. It also doesn't differentiate between security upgrades and feature upgrades (which require days of testing and fixing).

I am looking for something better. I am looking for something that can let me know if Django has a new security release out, or if something is end-of-life. I want something to help me (and other Python devops) not become the next batch of people crying after a wave of kids with scanners and scripts convert our servers into a botnet.

Does such a thing exist?

答:
We use buildout to create deployments that are reproduceable and isolated.

A buildout acts like a virtualenv in that it lets you install eggs, keeping them separate from your Python installation, and it acts like pip in that you can control what versions are used. But buildout is also a build tool, with recipes you can make it build arbitrary parts as needed to fit your application and testing.

My virtual env does not contain anything beyond the zc.buildout egg to create new bootstraps for new projects.

A typical buildout I build has several config files, to fit development, continuous integration, and production environments, but the base.cfg invariably looks something like:

```<code>[buildout]
extends =
     versions.cfg

newest = false

eggs = customer_project_name

[django-base]
recipe = djangorecipe
settings = settings
eggs = ${buildout:eggs}
project = customer_project_name
projectegg = ${:project}

[python]
recipe = zc.recipe.egg
interpreter = python
eggs = ${buildout:eggs}
initialization =
   import os
   os.environ['DJANGO_SETTINGS_MODULE'] = '${django:projectegg}.settings'
</code>```

with a versions.cfg to pin all versions to prevent accidental upgrades.

Because we use a versions.cfg file, it is easy to parse all versions files to see what projects are affected (it's just a ConfigParser file, after all), and upgrading the package is just a question of updating those pins and re-testing the project.

Once tested, push the updated versions updates to the customer server, rerun buildout.

Note that upgrading security fixes should be a dedicated maintenance task anyway, as you need to plan, test and find a upgrade window for your customers.

Body:
We use buildout to create deployments that are reproduceable and isolated.

A buildout acts like a virtualenv in that it lets you install eggs, keeping them separate from your Python installation, and it acts like pip in that you can control what versions are used. But buildout is also a build tool, with recipes you can make it build arbitrary parts as needed to fit your application and testing.

My virtual env does not contain anything beyond the zc.buildout egg to create new bootstraps for new projects.

A typical buildout I build has several config files, to fit development, continuous integration, and production environments, but the base.cfg invariably looks something like:

[buildout]
extends =
     versions.cfg

newest = false

eggs = customer_project_name

[django-base]
recipe = djangorecipe
settings = settings
eggs = ${buildout:eggs}
project = customer_project_name
projectegg = ${:project}

[python]
recipe = zc.recipe.egg
interpreter = python
eggs = ${buildout:eggs}
initialization =
   import os
   os.environ['DJANGO_SETTINGS_MODULE'] = '${django:projectegg}.settings'

with a versions.cfg to pin all versions to prevent accidental upgrades.

Because we use a versions.cfg file, it is easy to parse all versions files to see what projects are affected (it's just a ConfigParser file, after all), and upgrading the package is just a question of updating those pins and re-testing the project.

Once tested, push the updated versions updates to the customer server, rerun buildout.

Note that upgrading security fixes should be a dedicated maintenance task anyway, as you need to plan, test and find a upgrade window for your customers.


问:
Does Turing-complete implies possibility of malware?
Is it possible to build an operating system that contains some Turing complete compiler (language?) but is unable to run any malware? Or is there any definition for a malware?

This question popped on my mind as I was wondering why Windows has more malware than Linux. If Linux contains a C programming language and its compiler, I think it is possible to write a Linux program that works similarly than Windows viruses. But there are less malware for Linux than for Windows although there is a Wine for Linux to simulate Windows programs.

答:
Malware's goal is to find a security vulnerability so that it can give itself permissions to perform actions on the attacked computer that the computer's security would not otherwise allow, up to and including deletion of files, wiping the hard disk, copying itself to other computers, and other types of mayhem.

To illustrate, I'll cite two examples:

SQL Injection

Buffer Overruns

SQL injection is prevented by using prepared statements.  Buffer overruns are prevented by doing bounds checking on arrays.  ANSI SQL is not Turing complete.  The C language (which is where most buffer overruns occur in the wild) is Turing complete.

The way you build a programming language that is resistant to hacking is by sandboxing it in certain ways.  Many modern languages, for example, simply do not allow you to access elements beyond the end of an array, so they are not vulnerable to buffer overrun exploits.


答:
Malware, you know malicious software, can be broadly defined as software that performs a function you don't want it to perform. Beyond a simple bug or error, the goal of the software is counter-productive to the user's welfare. Like providing access to those that shouldn't have it, wiping data, or say, tracking your actions and reporting them to a third party.

So while it's somewhat awkwardly asked, I'm going to go with yes, executing software that is given enough freedom to qualify as "Turing Complete*" has enough freedom to at least attempt to be malicious. Operating systems by and far are made to run other programs within them and so they should be made with the knowledge that the software could be malicious.  Hence, access privileges, passwords, and memory management.

*Being Turning Complete involves an infinite amount of memory by the way. It's a term that gets thrown around a lot into situations where it really isn't warranted. I think you mean "software written by other people".

Title: Does Turing-complete implies possibility of malware?

Body:
Is it possible to build an operating system that contains some Turing complete compiler (language?) but is unable to run any malware? Or is there any definition for a malware?

This question popped on my mind as I was wondering why Windows has more malware than Linux. If Linux contains a C programming language and its compiler, I think it is possible to write a Linux program that works similarly than Windows viruses. But there are less malware for Linux than for Windows although there is a Wine for Linux to simulate Windows programs.


问:
IDE Generated Code
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?

答:
The difference between the IDE auto-generating some code and building that directly into the language is very simple: I can edit the code after the IDE generates it.

The IDE can generate some code template for a getter/setter, and then I am free to add additional functionality to that getter/setter as my requirements dictate. If the getter/setter was an integrated part of the language, then if I ever wanted to customize the behaviour, I'd have to write the getter/setter myself anyway...

ContentLicense: CC BY-SA 2.5

Title: IDE Generated Code


答:
No. It is not possible in the general case to define and discern the purpose of Turing complete code. This is somewhat related to the halting problem and is something that DRM must grapple with constantly (go ahead and try to distinguish between malware and DRM - one is protected by law in the US and the other is against the law in many places, interestingly enough).

The way we have generally solved the malware problem is by requiring the user to grant necessary permissions to programs. This prevents programs from accessing resources outside of the permissions. This, of course, will fail in as many cases as you'd expect based on the user, but it moves the onus to the user from the system.


答:
"Malware" is just short for "malicious software".  Software is malicious if it was written with malicious intent, which is intent to cause harm.  (Technically it doesn't even need to succeed at causing harm, or even have the capability of doing so, it just needs to have the intent of causing harm.)

Therefore, by definition, if the machine that you are using is capable of running software (using whatever definition of software you care to use, and regardless of whether or not it is Turing Complete) it can run malware.


问:
Are There Any Programming Focused Notebooks?
I know that engineering paper exists, but are there any companies that make programmer-specific notebooks for notes/pseudo-code/designs?

Paper is my preferred way of outlining things, so the addition of a specialized pad to my list of tools would be greatly beneficial.

答: I obsess over stationary and have been trying to answer this question for myself for ages. My favorite solution is a Rhodia wirebound graph pad with a Micron Pigma pen. Rhodia paper is superior to all I've tried and they have a number of size formats to suit your writing style. I also find a small architect's template to be handy for making diagrams. Both pen & pad are easily acquired in the US at any art supply store.</p>


问:
Proper Price Markup Formula
Ok, so this is not the most advanced programming question - and it kind of borders on e-commerce, but it has specifically come up twice in my career - which is only 10 years old, so I figured I would ask it.

Question: I want to markup a price 10% from its original cost for a website, which is the proper way to do it:

NP = (P * 1.1)

or

NP = (P / 90) * 100

Where P is the original Price and NP is the New Price?

Background:
I am a web developer. I have worked on several e-commerce sites in my time. A few years back, I was building a freelance site for a tool shop. The guy had been in business for years and was moving into online sales. I wrote a script that took his core inventory list, cycled through it and automatically marked up the price 10% before inserting into the Database. I used formula #1. When he reviewed it he said the price was too low and to use formula #2.

Using formula #1, a 15 dollar product is now equal to 16.5, using two it is $16.66.

His logic was that 15 is 90% of $16.66 and thus 16.66 a 10% markup, by which 16.5 is only about a 9% markup.

Flash forward a  few years to today and and I hit the same problem. My company has a massive list of inventory that gets marked up and down in a number of ways. Our old DBA was marking up the price for distributors 10%. He was using formula 1. Our new DBA rewrote a stored procedure and started using formula two.

A few people flipped out and started saying that the distributor prices were way too high and that the old formula was correct. We sell large quantities of relatively low-cost items, the fear is that our distributors would balk at the cost.

Logically it seemed that formula #1 was the proper way to markup, but the experienced business owner told me the other way was. Now I am hearing people say the opposite.

EDIT: My Using the original 15 example. It has always seemed  to me that 15 is actually a 10% markdown of 16.66 where as 16.5 is the proper 10% markup of 15.

答: They are confusing profit margin and markup.  Profit margin is formula 2, and is based on the selling price of the item.  Profit margin can never be higher than 100%.  Markup is formula 1, and is based on the wholesale cost of the item.  Markup has no upper limit.</p>

Title: Proper Price Markup Formula


问:
best (web) architecture for my project
So I'm not sure if this is really the right place to ask or even the right question but I want to give it a try.

Requirements:

We should have a database & webservice (or something similar) which runs in OUR office, clients cann access the application via the internet ("wohooo").
Clients must be able to create orders in a simple mask. There is a basic mask (which all clients have), but the mask can also have some client-specific stuff.
When they created the order, a label with a barcode (which contains the order number) is printed locally (and automatically) at their office on a label-printer.
They take the label and put it on a sample, which they then send us (on the real post-way).
We get the sample, scan the barcode on the label and the order appears in our "administration-screen". We then have every information we need about the order (and the sample).
Surely we also need a backend where our staffmembers can edit the client-specific mask and add some fields (for specific-clients) and other master-data.

All in all this doesn't sound too complex. The only thing which stands out a little, may be the automatic print of labels at their place I guess. Because of this reason it may not be possible to use a "server-side only" architecture (like jsf or spring with jsp and so on), because you have to have access directly on their local printers.

So I thought a good way is maybe to use spring (with Hybernate, JavaBeans (JEE)) together with JavaFX which would allow to access local printers and so on. I thought we could just make a webinstaller/webstart for the application, which installs the JavaFX clients for the clients. The JavaFX client could then communicate with the webserver (spring) and insert the order there, get all required information like the order-number for printing the label and so on.
For the backend in our office I could also imagine to use JavaFX...

So where's my question?

Well its simple: Is this a good way to do it? Are these fitting technologies for doing it? Or is it already to complicated and this could be accomplished in a much easier way? If so what do you suggest?

Naturally I also want to lay a big focus on easy extensibility and maintainibility.

答:
Do all clients have a label printer?  Is the only way to be an effective client is with a label maker?

Can you just as easily scan a plain old sheet of paper with a barcode that might be included or contained with a packing list that a client would include in their material shipment to you?

In any case, a special client side solution beyond browser HTML/CSS/JS would probably not be necessary from what was described here.

A bar code can be generated dynamically on the server side.

A recommended packing list that includes the bar code can be sent to the browser as accompanying documentation with their order receipt.

A browser can be coerced to automatically suggest a page be printed.  The page could be an order receipt (which includes the recommended packing list with bar code).  The user still has to choose to proceed with the print job, but are not obligated to.

Provide a facility to view and reprint past/recent/last order receipts (including the recommended packing list that contains the bar code) in case a user unknowingly cancels the first, workflow induced, prompt to print.  Printers can be problematic so having a recovery opportunity is a good thing.

Perhaps there are other features that necessitate a particular client side solution, but so far, I do not see it.

Title: best (web) architecture for my project


答:
I think this is a good question, but it doesn't really have the simple answer others have tried.

The most basic problem that malware exploits is the required, and even desired, sharing of resources between the simulated Turing machines of computer programs. The fundamental limitation of a computer that prevents it being a perfect Turing simulant is finite resources; conceptually, the symbol tape of a Turing machine is of infinite length, meaning the machine has access to infinite state data which it can read or write as it chooses. The inference is also that each Turing machine gets a separate tape on which to work, and the state data of any single Turing machine is never seen by another machine, unless that data is provided as the initial state of the second machine's tape. Neither of these are possible, and sometimes not even desirable, in a real computer; we like our computers to multitask (to simulate multiple Turing machines simultaneously), meaning that we must efficiently divide and re-use our finite resources, and in general we actually like it when one program knows what the heck is going on in another program.

A second and related problem is that the conceptual Turing machine doesn't have to worry about the long-term persistence of its data; it "writes" state symbols to its tape and expects that state to persist indefinitely, whether the machine ever returns to that position of the tape or not. In a computer, there are practical concerns about fast but volatile memory versus slower must more persistent memory. This generally necessitates a transfer of memory between volatile and persistent forms that our program, a Turing simulant, ideally shouldn't have to care about.

A third problem is that Turing machines are automatons (Turing's original term was "automatic machine"). They do exactly what they're told to exactly what they're given, nothing more or less. A more intelligent actor is required to configure (program) the machine to do the right thing and give it the proper initial data. That actor must have good intentions, and their resulting design must function correctly in all circumstances.

It is possible, in theory, to create an operating system that can maintain multiple Turing machines without allowing the sharing of resources. However, to do so, the following conceptual rules must be followed:

No sharing of volatile memory between multiple Turing machines executing concurrently.

No sharing of persistent memory between multiple Turing machines, whether executing or not.

Any deviation from the first two rules must be performed directly by the intelligent owner of the computer, who must be assumed to be benevolent and infallible.

It's that last rule that is problematic to our modern use of computing devices and very likely puts the kibosh on the whole thing. The absolute prohibition on shared resources between machines (programs) means that the programs being executed by a computer can only ever be provided with initial state data, and can never be given new data while running by external sources (at least not without stopping the program cold and resetting its tape with new data before restarting it).

The requirements that the intelligent actor actually be benevolent and infallible are beyond the scope of a computer (though we try), and the directive that the actor must directly make any state changes requires the actor to have the knowledge and skill to do so, as well as the ability, good intentions and perfection of operations. Modern operating systems, especially in consumer devices, typically assume the opposite of all of this; that the user does not possess the knowledge, skill, good intention or perfection to make necessary data changes directly, and so does not give them the ability. This is usually a good assumption to make; I program for a living, and yet would have no clue how to make direct changes to the binary data of a program currently running on my Android phone.

However, if the actor can't change the data of a program directly, then the system will either only run the machines it was initially given with the data they were initially given forever (possibly good for complex, open-ended mathematical computation, such as figuring out pi to the bajillionth place, but not real good for updating your Facebook profile when you can't even load that profile into the memory of a running program), or the operating system must provide a means for the actor to make some changes that are desirable in a safe way. This is typically by providing the user with one or more other machines, that violate the "no shared resources" rule in order to change the data in a way that is assumed to result in correct and desired changes in execution of the program that really owns that data.

This is where malware gets in. Simply being required to allow violations of the no-shared-state rule, for any reason, allows multiple machines to make changes to data that they all depend on. The assumption that must be made is that all designers of all these programs are benevolent and infallible. Neither are true of human computer programmers, who are the ultimate endpoint in the design of any program, no matter how many steps along the path of generating the machine code for the program are automated. A fallible programmer can introduce an error in the program that causes it to corrupt not only its running state but cause problems with any other program using the same data. A malevolent programmer can intentionally do similar things.

So, until machines start doing all our coding for us, while it may be theoretically possible, it is practically impossible to create a system that is usable by and useful to the average end user of a computer product in our modern society, that has zero chance of being affected maliciously.


答:
The original answer I gave was, I think, correct and useful, and I didn't want to blow it away, but I think the answer can be arrived at much more concisely.

There are some assumptions that are typically made about Turing machines, which are the basis for calling any other machine including a logical one "Turing complete".

One tape per machine and one machine per tape. In other words, "no shared state".

Only the machine alters the tape's data from the initial state given to it when it starts; "no dynamic input".

Therefore, theoretically, you could design a system that, with some understood limitations (like finite resources), would simulate a single-tape Turing machine, and such a system would be impervious to malicious software (or even bugs caused by human fallibility), for the simple reason that none of the Turing machines the system may simulate at any given time, or indeed has ever simulated, could ever affect the execution of another machine.

But real computers don't work that way; or at least, we don't want them to. We like programs, and even full systems, to share information. We like programs to ask us for input halfway through, and to accept input that may fundamentally change the way the program executes. Sometimes, we even like one program to change the state of another program on our behalf. Our programs therefore allow us to do these things for benevolent purposes; performance, memory economy, automation, ease of use.

However, this same willingness to share resources requires the assumption that all actors or agents of actors that are sharing the resource are doing so benevolently and infallibly. Neither is an adjective that applies to 100% of computer programmers or the programs they write to act on their behalf. This is how malware gets in; we allow what is technically a violation of the behavior of an ideal Turing machine, in order to perform a task that allows a desirable change in the behavior of a program. That same accepted violation allows someone to do the same thing to effect an undesirable change in behavior.


问:
What could be the use of forking a repository in a github's organization?
I'm trying to figure it out some nice workflow for our company, and we have so far the main  repository on the github's organization account and we all, the members of the team working on the branches of that repo.

Could you please mention some advantages on forking the repo or some use, by the members of the organization?

I was thinking, that for example, I could make a fork and perform a upgrade of the libraries, but  someone pointed that, "what is the differences on doing it simply in another branch,without forking?

Thank you in advance, for your time.

答:
The main benefit of github forking is allowing a gatekeeper workflow, where untrusted people can work on a feature and a trusted gatekeeper pulls it in after a review.  That model is not very popular within a company, because employees are generally considered trusted.

However, it can be useful if you want an experienced employee to control who can change certain parts of the code, or if you want a repository that only contains commits that QA signed off on, that sort of thing.


问:
How to convince team members of the existence of a "mandelbug"
We are developing an application; it includes a library developed by another coder, this library communicates with server via multiple network connections, and this involves multiple threads working together. The server side code is quite complicated, and we don't have access to the source code.

Recently I've discovered a mandelbug making application crash sometimes. I could reproduce it once and got a stack trace, so I opened a bug report. The bug itself is easy to fix (uncaught web exception in one of background threads, that makes CLR terminate the program).

The problem is that developer is refusing to fix the bug, because "he is not convinced it exists". Unfortunately for me the boss is siding with him and says this bug cannot be fixed unless I make a "solid test case" to prove existence of the bug, and to make unit test verifying that it's gone. What is basically impossible due to a nature of the bug.

Any advice?

答:
The stack trace is clear evidence the bug exists, or at least did exist in a certain build.  What you don't have is evidence the bug was fixed.  They are foolish to ignore it.  I've had "impossible to reproduce" bugs after hundreds of thousands of automated tries on multiple systems that triggered every single time on a customer's system.

I get a couple bugs like that per year, most without even the benefit of a stack trace.  In nearly every case, even though I couldn't reproduce it beforehand, I could pretty easily make an automated test for it once it was fixed.

For example, a few months ago I fixed a bug that only occurred when the user typed faster than 96 words per minute.  Before I fixed it, all I knew was that the bug happened "sometimes."  It would never occur to me to write a unit test for fast typing.  However, after I knew the root cause, making a test for it was trivial.

Even in those rare cases where a bug can't be reproduced even after being fixed, you can close it by code inspection.


问:
How Much Of A (Broken) Legacy Framework To Keep
I've inherited a hosted system (system "A") which can be used to manage products, inventory, and orders, and can send those products to various third-parties.

Quite simply, system "A" doesn't work. The product and inventory systems are slow, convoluted, and buggy. The third-party integration doesn't work at all. The code is an unholy, spaghettied mess, so fixing things is not simple.

My task is to try and salvage the system into something usable, and my original plan was to just refactor, refactor, and refactor some more until the system worked.

However, my company also has a separate system (system "B") that we use to build e-commerce websites. Among other things, system "B" can manage products, inventory, and orders as well - just in a lesser capacity in some cases. System "B" is also constantly being worked on and updated by a team.

My new plan is to essentially throw out system "A", and re-create it based on system "B".

Since my refactors would have eventually restructured system "A" entirely, I figure I can just save time by starting over with a different, existing framework. However, if I go that route, I would still have to re-code the third party integration, and minor functionality that system "A" has and system "B" does not.

Right now, system "A" is basically defunct - nobody is really using it, so I do have the freedom of a slightly extended rewrite period if I choose.

Is this a good idea, or should I stick with the original plan of refactoring system "A"?

答:
It is good you asked before starting.

According to Joel Spolsky (an experienced and respected software developer as well as one of the people behind stack exchange), the number one "biggest strategic mistake" a company can make is deciding to re-write code from scratch.

In that blog post, Joel points out that it is much more fun to write your own code than to try to understand an existing code base -- so programmers have a bias towards writing their own systems instead of re-factoring. The problem with this is that existing code bases have lots and lots of "knowledge" of built in. The existing code almost certainly deals with many specific little issues/details that are absolutely key to making the software actually useful. When you throw away a legacy system, you throw all of that knowledge away. Replacing it is likely way harder and more time consuming than you imagine.

I have personally fallen into this trap. I completely re-wrote a complex legacy system for the same reasons that you cite (many bugs, confusing code, missing certain features). Once I had the system re-built, I ended up having to re-fix a whole lot of problems that had already been fixed in the original system. The non-technical people who used the software did not see my "clean code" -- they just saw a new system that had little problems that had already been (painfully) solved. In retrospect I should have re-factored not re-written.

If the code is buggy--fix the bugs. If the code is disorganized, organize it. But don't throw the whole thing away.


答: For getters/setters, that is true for Java (which I guess is what you are talking about) since that language lacks properties as a language construct. The IDE can help you compensate for that somewhat.</p>

Title: IDE Generated Code

Body:
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?


问:
Software License: Open Source, but no distribution (for free or for profit)
I wrote a program in PHP. I want people to be able to use the code to learn from and even include bits in their own apps but I also want to maintain the right to sell it and make it clear that others are not to distribute copies either for free or for profit. I haven't used anyone elses code so I don't have to worry about license compatibility. Which license out there is right for that?

I know I can't stop people from ignoring the license but I just want them to at least know it's there and know they're doing something wrong if they try. I can't find anywhere that explains licenses in plain English and yes, I have tried to read the GNU and BSD licenses but I can't get it. Thanks.

Ok so here are the clarifications other have asked for:
I am going to sell this program for very cheap. People are free to use as much code as they want from it so long as they have first purchased the program and they do not profit from my code.

I wouldn't mind if people just took the whole thing and added on and made it better but then people wouldn't be honest and they would just add something on and give it free and then no one would buy my product.

I suppose I should just let people have it and ask for donations. So maybe I should GPL or BSD it.

EDIT:
I understand why everyone is getting confused. It is contradictory but the thing about legalese is that everything seems black or white. I'm trying to achieve a gray area. I want people to buy this thing from me, not copy it and give it away to people, and even use parts of it. By "use parts", what I'd say if someone asked me casually would be "just be reasonable". So basically don't use a majority of my code in your work and then totally outshine what I did because you'll have it easy as I did most of the dirty work already! I mean, sure, use my DB connect script in your project, I don't care. OR... use all the code and add to it! But only for personal use and don't you dare start giving it out because I'm going to be making money off this thing and that totally undermines my work. And it'd be nice to show me your additions and I'll give credit but the main thing is don't be redistributing my software that I have to earn a living with. Its hard to put that sentiment into legalese. And I just can't understand all these licenses.

答:
```<code>I suppose I should just let people have it
and ask for donations. So maybe I should GPL or BSD it.
</code>```

so from a strictly practical standpoint a well crafted pay what you want set up (aka donation page) might make you more money, unless you actually expect to make a good amount of money selling it (you said sell it cheap so I don't know what that means, like 20 copies at $0.50 or 500 at $10, more). If it's only like $0.50 I woudln't bother because bear in mind if people pay for it, there is some obligation to support it, if you give it away for free, not so much.

OwnerDisplayName: Bill

Body:
I suppose I should just let people have it
and ask for donations. So maybe I should GPL or BSD it.

so from a strictly practical standpoint a well crafted pay what you want set up (aka donation page) might make you more money, unless you actually expect to make a good amount of money selling it (you said sell it cheap so I don't know what that means, like 20 copies at $0.50 or 500 at $10, more). If it's only like $0.50 I woudln't bother because bear in mind if people pay for it, there is some obligation to support it, if you give it away for free, not so much.


答:
What you are doing is considering the options of a) Upgrade to "System B" or b), Maintaining "System A".

We cannot give you a straight answer - far to many variables. The most significant is usually the least technical, and requires significant consultation with you managers and financial controllers. Assuming A is deployed and mostly working, the cost of remaining on A is low upfront investment with high ongoing costs. The advantage of B - lower ongoing costs, is offset by an initial (usually not insignificant) cost.

In this context, cost includes all the things a business considers - Dollars, Opportunity cost, Risk, along with tax implications (A might be all maintenance, B, all capitalized for tax purposes).

Into this you can, and should, put in 'soft' things like "No one wants to work on crufty old code", and "It's easy to recruit developers to work on the new shiny stuff", as well as "No matter what we do, A will always be buggy, but we have a choice with B and make is buggy as you like"

What you should do to weigh these up is put together a plan for both options, outlining the the relative costs (Time, Money, Risk.....) and rewards of each option, and make the decision on the commercials.

before you chose going to 'System B' Do read the answer by @akh2103, and read up on "Second System Effect"

Title: How Much Of A (Broken) Legacy Framework To Keep

Body:
I've inherited a hosted system (system "A") which can be used to manage products, inventory, and orders, and can send those products to various third-parties.

Quite simply, system "A" doesn't work. The product and inventory systems are slow, convoluted, and buggy. The third-party integration doesn't work at all. The code is an unholy, spaghettied mess, so fixing things is not simple.

My task is to try and salvage the system into something usable, and my original plan was to just refactor, refactor, and refactor some more until the system worked.

However, my company also has a separate system (system "B") that we use to build e-commerce websites. Among other things, system "B" can manage products, inventory, and orders as well - just in a lesser capacity in some cases. System "B" is also constantly being worked on and updated by a team.

My new plan is to essentially throw out system "A", and re-create it based on system "B".

Since my refactors would have eventually restructured system "A" entirely, I figure I can just save time by starting over with a different, existing framework. However, if I go that route, I would still have to re-code the third party integration, and minor functionality that system "A" has and system "B" does not.

Right now, system "A" is basically defunct - nobody is really using it, so I do have the freedom of a slightly extended rewrite period if I choose.

Is this a good idea, or should I stick with the original plan of refactoring system "A"?


答: While the shorter form is more elegant and compact, there's an advantage to the long form: You can easily set a breakpoint at test1 = true, while you can't with the shorter form.

Title: Making Simple IF Statements Shorter


答: At the risk of being downvoted into oblivion, I would say use the long form because of clarity and maintainability. In the example given, the difference is small. But getting in the habit of writing "clever" one-liners will just make it more difficult for anyone else to maintain your code.</p>

Title: Making Simple IF Statements Shorter


问:
How do you distinguish your public API interfaces from the interfaces you use for testing/mocking?
Mocking frameworks are useful for creating mock objects that isolate the code under test from its surrounding software environment.  Some mocking frameworks cannot mock non-virtual methods, so they require that you create an Interface for each class, if you don't want to make the methods virtual.

How do you distinguish those Interfaces from the "real" ones?  That is, if you have a public API, do you name the interfaces that you intend your customer to use something else, or do you hide the testing Interfaces in a separate assembly or namespace?

As an aside, is it really necessary to create all those Interfaces?  I don't like the idea of making all my methods virtual, but I really don't like the idea of creating that many interfaces just to make them accessible to a mocking framework.

答:
I don't.

Either the class is (effectively) sealed/final or it has an interface. I don't buy the whole internal classes are somehow above the law: abstraction exists to protect you from change, and your internal types are just as likely to change.

Basic structures (DTO's, tuples, and other usually sealed/final objects) are fine in my experience to just use as is in tests. They are effectively part of the public interface of your modules.


问:
How do you stay focused at work?
Sometimes, the things I have to do for my job are interesting and engaging.  Sometimes, they aren't.  Occasionally, they really aren't.

Do you have any particular strategies or tricks for dealing with those dull stretches when your brain would rather be doing anything other than what you're supposed to be doing, particularly when the Internet and its boundless opportunities for interesting Slack beckon?

答: Stress.  I give in to temptation and surf StackExchange/Reddit until the last possible minute, then bang out what needs to get done.  Nothing like a 1 hour deadline to keep you focused.</p>

Title: How do you stay focused at work?


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
There are two distinct sets of skills involved in being a developer:

The Generic relating to how to analyse, design and construct decent applications

The specific relating to the toolset you use to implement those applications

There are - or certainly have been - people who exist at a level of "coder" and whose skillset is limited to a single language but, I think, progressively less so as any programmer is (or at least should be) expected to be more rounded.

If you have the former and an ability to adapt to new variations or alternative toolsets then you shouldn't have a problem.

Right now I write .NET applications - have done for 8 years, will probably continue for a long time... but in doing so I've also needed to understand HTML, SQL, XML, XSLT, and JavaScript amongst other things. I'm learning the wonders of jQuery and also of XAML. I'm looking at F# (amongst other things) because I might usefully be able to apply it. Neither the .NET framework nor the languages you can use are standing still. And I mustn't forget PowerShell...

Prior to that was VB.OLD and some Turbo Pascal and prior to that a variety of stuff.

I've also, over the past 25 years, looked at and learnt about a variety of different industries and businesses as I endeavour to learn the domains as I develop solutions for them. I also have a moderately decent understanding (though not to a sysadmin standard) systems and networks and making things talk to each other - simply from the need to be able to have the platforms to develop on.

Right here, right now, .NET is a vast and capable platform with decent languages and tools and as good a place to be employed as anywhere - more important (I think) are the broader skills, unit-testing, agile methodologies, application of patterns (understanding of good principals like inversion of control) and good practice (use of VCS and build servers and the like) - these are portable skills that need to be kept up to date as things develop.

I could go on (in case you hadn't noticed) - but the simple answer is that so long as you grasp that you are a "developer working on the .NET platform" rather than a ".NET developer" (or worse a "C# developer") you'll be fine.


问:
What's a typical team size using a Git repo?
We've been using Git as our version control but as the team grows, there are more and more pains when it comes to getting all our changes onto a single branch ready for a deployment.

I'm wondering if maybe we're outgrowing Git as an effective collaboration tool.  I know there are large OSS projects with many developers that use Git but there also tend to be some gatekeepers responsible for the merging of branches into the final build/deployment branch.

In an office environment, where the developers are relatively independent and can be trusted to merge their own changes, how many people can effectively collaborate on Git?

Additionally, are there any tips for effective use of Git? We've been using the rebase workflow, I'm not entirely convinced switching to a merge based workflow would improve the situation but then, I haven't seen a formal description of how a large group would work together in a merge workflow (It seems like the history would just turn into merge hell).

Addendum:

So that it's easy to find for anyone else wondering:

We're using a feature branch strategy

The code base is well organized and pretty clean. It's Python (with some HTML/JS), MVC via pyramid for the web app, separate package (different top level folder in same repo, itself split up into well defined layers) for a large chunk of the non-web specific application functionality.

We experience pain as far as merging code because developers are frequently making changes in the same files, like, one dev owns auth, so they're touching the views, etc... related to auth, but another dev is handling internationalization, so they're touching all the views, etc.

答:
Well, git is up to the task to handle the linux kernel, right? It worth a look to feel the number of patches, branches, contributors....

Based on that I don't think there is a size limit. Also I doubt there exist any better source control system these days, so even if it had, nothing to switch to.

However I feel for your problems, those are definitely real. You need project organization. You need check-in rules, code policies, branching policy, culture, and a lot of other teamwork related things for good results. git is merely a database with convenient features to store and manipulate sources and history.  It never pretended as a "system" or replacement for one.  Or a general collaboration tool.

For non face-to-face collaboration there are actually good supplement tools like bugzilla, wikis, project planners.   We use FogBugz with Kiln -- the latter just learned git, and it allows to streamline many workflows related to assigment of tasks, verification and especially reviews. You need to assemble some system like that.  And certainly keep up real people interactions and a learning environment.

For git history handling, yes, I also suggest rebasing for most times, especially single patches. But use branch merges, even on top with --no-ff if for a single topic.  Before integration to master make the code reviewed and consolidated (rebasing on self) to meld fixups and post-review work.  Don;t be afraid to fix the master if it goes out of shape.

To avoid "upstream reabase" related problems my rule is to create an amend_NN branch on the old and fixed_NN on the new state with matching numbers, so anyone can easily discover that his work must be rebased and avoiding resurrect of dropped things.

The branching policy must be based on the general work and release approach.  I keep a single master but you can find more elaborate schemas that have a separate development master.

NOTE: By 'bugzilla' I meant the tracker genre in general not the particular product directly, in decision making I got great help from tracker compare wiki . OTOH I do have positive experience with Bugzilla itself from previous places too.


答:
I absolutely agree with akh2103's advice against rewriting from scratch. You may rewrite isolated pieces of it (if that is possible), but not the complete system. Why?

From my experience, only the code contains the knowledge about the underlying business cases. Even if you would ask all the non-technical guys that work with your legacy application, you wouldn't get all the requirements and your rewritten system would initially fail to met the real demands. And then you have to start patching it...

Although there is no silver bullet in that situation, I think there are some guidelines:

Be sure to have automated tests before you start refactoring. Chances are high that your legacy system has none. Writing tests for legacy system can be quite tricky, however, as dependency are often hard-wired.

Keep your legacy code running, but whenever it is possible try to implement new features separately (e.g., add new services). The idea is that over the time, your active code base slowly moves away from the legacy system. Martin Fowler calls it Strangler Application.

Only refactor larger pieces of code if you have a reason to touch it. The reason can be quite small, e.g. changing a text that is displayed. But don't start to rewrite a component that works perfectly without having been changed over the last 6 months, just because its code looks ugly. Concentrate on the code that you have to modify the most because these are also the parts that will annoy you the most.


问:
Semantic versioning for desktop applications
I can easily follow the Semantic Versioning recommendations if I develop a library or API, but what if the developed product is a website or a desktop application?

When would you increment a major component in that case?

In case of a complete UI redesign? Or something else?

Thoughts?

答: Semantic Versioning seems to be at conflict with most desktop application numbering. We solved this by handing over "product versioning" to the marketing department, and we maintain completely separate (but logical to us) versions for all the components. A specific product version then becomes a defined collection of compatible components. Maintaining semantic versioning between components is much easier.</p>


问:
Using <= for every dependency in case of following semantic versioning idea
As Semantic Versioning (and common sense) declares - the major version is incremented in case if non backward compatible change is introduced.

Now let's assume we have a project called Project that has a current version 1.0.42 and a library Lib it depends on that is of a 2.1.3 version at the moment.

Does that mean that following semver ideology we should constraint the dependency of the Project to be Depends: Lib (< 3)?

From my experience - no one does that, but I find it semantically correct and very self-descriptive.

What do you think of this?

答:
The RubyGems package management system has the pessimistic version constraint for precisely this reason:

```<code>~> 1.2.3
</code>```

means "chop off the last component of the version number and treat it is a wildcard, but don't use a version less than specified", IOW

```<code>~> 1.2.3
</code>```

means

```<code>1.2.* && >= 1.2.3
</code>```

and

```<code>~> 1.2.3.4
</code>```

means

```<code>1.2.3.* && >= 1.2.3.4
</code>```

In other words, it means: any version at least as new as the one that was specified, but only within the same "category". So, if you specify a bugfix release, you will get newer bugfix releases but no new minor version. If you specify a minor verso, you will get newer minor versions but no new major version.

Body:
The RubyGems package management system has the pessimistic version constraint for precisely this reason:

~> 1.2.3

means "chop off the last component of the version number and treat it is a wildcard, but don't use a version less than specified", IOW

~> 1.2.3

means

1.2.* && >= 1.2.3

and

~> 1.2.3.4

means

1.2.3.* && >= 1.2.3.4

In other words, it means: any version at least as new as the one that was specified, but only within the same "category". So, if you specify a bugfix release, you will get newer bugfix releases but no new minor version. If you specify a minor verso, you will get newer minor versions but no new major version.


问:
Team switching from TFS Source Control to TFS with Git, not sure how to handle complex project structure
I've used git for my personal projects for years, but that's always working alone, not needing to branch much, etc.

Our development team at work has decided we are definitely switching to git, and as one of the most experienced git user on the team I have the task of figuring out our project structure.

Our current structure has a single Source Control, with many Projects.  Those source control "projects" may contain multiple folders which contain multiple Visual Studio Solutions which can contain multiple Visual Studio Projects, some of which are shared.

An example:

Main Directory

Folder 1

Solution 1

Project 1

Shared Project 1

Folder 2

Solution 2

Project 2

Project 3

Solution 3

Project 4

Shared Project 1

Shared Project 2

Folder 3

Solution 4

Shared Project 1

Shared Project 2

I am not sure at all how to translate this to git properly.  The main concern that has been mentioned to me is that if we use git submodules, when checking in changes it has to be applied to multiple repositories.  Is there a way around this?  Does TFS in Visual Studio handle this in an easy to manage way?

Anyone have any good information about this kind of thing?

答:
TFS treats everything as a single repo, so you can't do much harm starting with all stuff in a single git repo retaining the previous structure.  Or splitting off only the obviously disjunct elements.

You can split the big repo with subtree after-the fact anytime preserving the history.

Having a single repo has many actual advantages and unless clone size is considered relevant the drawbacks are easy to mitigate.

If you start with multiple repos you immediately need some tool to sync them all for fetch and tag all on release points. Also moving code around is inconvenient (from app to shared lib, should be common and straightforward).

Sure you may fight your way  with submodules, or something similar but many folks find those kept as last resort.

We moved from tfs to git a year and a half ago, I created a bin repo for external components, one for "data", and kept all the sources that are built with VS in one repo. Only splitting the fortran sources on which one programmer is working and he has a bin repo to release the output -- that supplements the bin repo.    And I immediately wrote a tool in python that knows about all the repos (we also have installer, tests, tools, etc) and allows basic operations (fetch, status, synch), and more importantly, that "creates" the development environment copying the external includes, libs, dlls...

The source repo has some 1.6M lines of code in ~4000 files and ~90 projects. I have no plans to split it.  The bin and data repos are fortunately quite cold. Still a few times it was PITA to go back with sources and need to manually go back with others too bisecting a problem.


问:
C++ Using Intrinsics in a Cross-platform Manner
I have a cross platform math library that I am working on and I want to make sure that some common operations are performed in an optimized manner, so I wish to use some intrinsic functions wrapped in inline functions to compute things such as sqrt(float/double). I should mention that at this point I only plan on targeting a select few platforms which are mentioned in the source below.

I have started a single prototype of the a sqrt() function but before I proceed any further I want to know if I am doing anything blatantly wrong.

I am following the documentation at:
http://msdn.microsoft.com/en-us/library/windows/desktop/ff471376%28v=vs.85%29.aspx

http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

Also, you will note I have a blank line under the pound define for macintosh. I know the newer versions are using clang/llvm. How do you get access to intrinsic functions under the newer versions of mac os and its associated compilers?

```<code>#ifndef INTRINSICS_H_INCLUDED
#define INTRINSICS_H_INCLUDED

#if defined(_WIN32)
#elif defined(__gnu_linux__) || defined(__linux__)
#elif defined(__ANDROID__)
#elif defined(__CYGWIN__)
#elif defined(macintosh)
#else
#include <cmath>
#endif

#if defined(_WIN32)
#pragma function( sqrt )
#endif
template<typename T>
inline float sqrt(T &val)
{
#if defined(_WIN32)
  return sqrt(val);
#elif defined(__gnu_linux__) || defined(__linux__)
  return __builtin_sqrt(val);
#elif defined(__ANDROID__)
  return __builtin_sqrt(val);
#elif defined(__CYGWIN__)
  return __builtin_sqrt(val);
#elif defined(macintosh)
  // How do I do this
#else
  return std::sqrt(val);
#endif
}
#if defined(_WIN32)
#pragma function( sqrt )
#endif
#endif
</code>```

答:
Let me begin with a rhetoric.

If there is a superior implementation that doesn't have any negative trade-off, then why aren't the standard libraries already using it?

It is not a question of premature optimization, if the function is used in a mathematical or large-data processing library where the performance gains will be multiplied by millions or billions. A prime example is the OpenCV library, where performance gains - even if just a few percents here and there - translate into a reciprocal increase in the number of video frames processed per seconds. So let's take a look at the square-root implementation in OpenCV.

https://github.com/Itseez/opencv/blob/master/modules/core/src/mathfuncs.cpp

Summary:

If the caller is interested in the reciprocal of square root, go straight for that.

If the caller is interested in comparing the magnitudes of two values after taking square root on each one, try to eliminate that square root step (with some additional logic).

If the caller is interested in calculating the square roots (or their reciprocals) for an array of values, use the SIMD equivalents.

Otherwise, fall back to std::sqrt.

(Edited)

If the caller only needs the crude approximate of the square root, see the Wikipedia article on this topic. (This topic is so huge that it's not possible to summarize here.)

Edit:

I stand corrected (by dan04's answer) by some important omissions from my original answer.

Compiler needs to be told the target CPU's architecture.

Example: /arch:SSE2 in MSVC

Compiler needs to be told to favor speed over precision

Example: /fp:fast

Compiler needs to be given permission to omit input range checks

Example: sqrt being compiled into a library call

In this example, the library function validates that the input value is not negative. If it is, it calls an error handler, which then throws a C++ exception. These additional behaviors makes it impossible to omit the library call.

The CPU needs to be told to flush-to-zero, and to treat denormals-as-zeros

This is done at runtime.

(I'm giving examples in MSVC, but other compilers would also need to be explicitly told to generate fast code.)

Since these are compiler options, they need to be specified in the makefile, not in the source code.

Suggestion:

It may be necessary to use a makefile configuration utility such as CMake to verify the compiler's support and optimality of the various intrinsics (and for using the fastest version available on that platform).

Mathematical details:

There's a long article on Wikipedia on methods of computing square roots and its rough approximations, including the "Carmack trick" invented by Walsh and Tarolli.

Some of these techniques are suitable for VLSI implementation. If so, it is typical that they are already employed in modern general purpose CPUs. Some of these accelerated functions require the caller to make one or several Newton's method or Goldschmidt iteration in order to converge from an initial estimate.


答: Instead of cluttering up your source code with all these macros, you could use optimization flags, such as /Oi in MSVC++, to have the compilers do this optimization for you.

Title: C++ Using Intrinsics in a Cross-platform Manner

Body:
I have a cross platform math library that I am working on and I want to make sure that some common operations are performed in an optimized manner, so I wish to use some intrinsic functions wrapped in inline functions to compute things such as sqrt(float/double). I should mention that at this point I only plan on targeting a select few platforms which are mentioned in the source below.

I have started a single prototype of the a sqrt() function but before I proceed any further I want to know if I am doing anything blatantly wrong.

I am following the documentation at:
http://msdn.microsoft.com/en-us/library/windows/desktop/ff471376%28v=vs.85%29.aspx

http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

Also, you will note I have a blank line under the pound define for macintosh. I know the newer versions are using clang/llvm. How do you get access to intrinsic functions under the newer versions of mac os and its associated compilers?

```<code>#ifndef INTRINSICS_H_INCLUDED
#define INTRINSICS_H_INCLUDED

#if defined(_WIN32)
#elif defined(__gnu_linux__) || defined(__linux__)
#elif defined(__ANDROID__)
#elif defined(__CYGWIN__)
#elif defined(macintosh)
#else
#include <cmath>
#endif

#if defined(_WIN32)
#pragma function( sqrt )
#endif
template<typename T>
inline float sqrt(T &val)
{
#if defined(_WIN32)
  return sqrt(val);
#elif defined(__gnu_linux__) || defined(__linux__)
  return __builtin_sqrt(val);
#elif defined(__ANDROID__)
  return __builtin_sqrt(val);
#elif defined(__CYGWIN__)
  return __builtin_sqrt(val);
#elif defined(macintosh)
  // How do I do this
#else
  return std::sqrt(val);
#endif
}
#if defined(_WIN32)
#pragma function( sqrt )
#endif
#endif
</code>```


问:
Value of MVVM in a Line of Business Application (and a Rant of Current Development Practices)
After 2 years, I'm still struggling with MVVM as a practical method of producing working software.  In some cases it's great.  I did a multithreaded application that controlled a small assembly line that would have been a nightmere without MVVM concepts.  An abstraction from the physical assembly line was almost a no brainer.

However, my career mostly revolves around internal line of business applications - formalizing and optimizing the operations of a business.  In such apps, there is generally a business teir revolving around CRUD and compound operations.  In LOBs, my view models end up being a very simple collections of one line wrapper functions of the business class methods and in the end only end up complicating the simplest of tasks like showing a message box or opening a window.  Doesn't anybody else find it odd when people go into long discriptions of "dependency injection" and "messaging providers" for a Window.ShowDialog call that has been around for decades?  How many other questions are there on stack overflow asking for advice for tasks that were extremely simple in winforms?

Don't get me wrong - I get MVVM and how it could be invaluable to large teams doing horizontal development of a shrink-wrapped and marketed software package.  Unit testing the view models could save millions by avoiding a bad RTM bug and dedicated UI developers could give a rich experience.  But when the cost of redeployment is minimal and all the business cares to pay for is simple working software, why should i spend time unit testing a simple "wrapper" vm when my business logic is already unit tested? How much time is the business really going to allow me to spend on cute animations and color schemes?  Is there anything left for a junior developer to do (tracking down a bug in a save functionality used to be looking at "Save_Click", but now you have to understand the patterns and the project as a whole especially if you're relying on templating to marry up the VM with the view).

Admittedly, I really like the databinding of WPF.  To take advantage of it, I set the data context to the window itself, where it has access to the business class as well as any other observable properties.  Yes I break nearly every MVVM "rule" by doing so.  But at least I have simple event driven code that's easy to read AND I get to take advantage of the new databinding and validation.  The problem is in the designers - which I don't use all that much but hope to now that it's better integrated in 2012 - the designer shows the hundreds of properties that a window and its base classes have.

For those that can relate can you point me to resources, books, or even just changes in perspective that made this easier to swallow.  I'll give MVVM another shot, but the last time I felt pretty stupid for worrying about dependency injection just to show a message box from a VM I had no intention of unit testing.  Even if I did unit test are we really getting more quality by trading run time testing for compile time errors of those dreaded "tightly-coupled" applications?

I realize one answer is to just stay in winforms.  But as one of the last supporters of WebForms (I have much of the same critique of the trend of web developement), i felt a little like a dinosaur as it is when I descovered there's no more WebForms left in the Microsoft certification tracks.  Moving forward is the only option, even if I don't like it.

答:
My perspective is from years of experience working with Winforms, the "old fashioned way," with events and code-behind. So I can tell you with absolute certainty that, once you get beyond the simplest of applications, your code quickly becomes a big ball of mud.  It was inevitable, because that's the way applications were written back then.

Webforms is just the same, except that it throws in the additional complication of being a stateful abstraction over a stateless system (the web).  As Rob Conery put it:

WebForms is a lie. It’s abstraction wrapped in deception covered in
  lie sauce presented on a plate full of diversion and sleight of hand.
  Nothing you do with Webforms has anything to do with the web – you let
  it do the work for you.

This, from the guy that wrote a fully functional object-relational mapper using the dynamic keyword in C# and only four hundred lines of code.  When he speaks authoritatively about something, I listen.

The application I'm currently working on is a Winforms application, with several tabs in the main form.  I can dynamically load forms into each of the tabs.  While I didn't follow MVVM or MVP (you can, with libraries like this one), I did aggressively push every bit of code I could out to a separate assembly, leaving only that code that is absolutely required to run the form.  There's still several hundred lines of code in there, not counting the partial class containing the form's control definitions, properties and event handler assignments, but I should never have to touch it again, unless I need to add something new to the form.

I have a static method that I can hand a form and a collections of Key/Value pairs, and it will (using Reflection) automatically match up the keys to the fields in the form, and populate the form with the collection's values.  I can also do the reverse, getting a collection of Key/Value pairs from the form's fields.  That whole thing is about twenty lines of code, but it pays for itself every time I use it, because I don't have to write forty custom assignment statements for forty controls on a form.

I can take that Key/Value list, and serialize it to XML, allowing me to persist it to a file.  I have other forms that I can hand a conventional DTO, and map its fields to the form. None of this would be practical in the "big ball of mud" style of Winforms.  It's almost trivial when adequate decoupling is utilized.

Does any of this sound familiar?  It should; it's essentially a poor-man's form of data binding.

Admittedly, I really like the databinding of WPF. To take advantage of
  it, I set the data context to the window itself, where it has access
  to the business class as well as any other observable properties.

Good for you.  It doesn't have to be MVVM compliant.  But remember, patterns like MVVM were created to help developers build big systems.  If you just need to display a dialog, you may not need all of that plumbing.

Part of the complexity of systems like WPF is inherent in all programmer libraries that seek to solve a specific problem in a generalized way.  To do that, you have to account for every practical way a programmer might use your library.  That adds complexity, but for those who design their libraries well, it also brings to the table a philosophy of doing things in a uniform and consistent way.

Consider John Resig's jQuery library: it is the very essence of a coherent design, and it hides a lot of weird details about the DOM, and variations in the way browsers handle it.  Is it simpler just to write a few lines of Javascript?  Sometimes.  But the benefit of writing jQuery code in a coherent, uniform API makes it easier for the next person who comes along to understand what you did, and maintain that code if needed.

My real experience with "big application" models is in using ASP.NET MVC.  ASP.NET is to ASP.NET MVC as Winforms is to WPF.  When I worked in ASP.NET, I always struggled to bend it to my will.  ASP.NET MVC bends to you.  It is a joy to use; it produces a system structure that is clear and organized, and gives you full control over your application and markup.  You can use Javascript, jQuery and CSS liberally, and ASP.NET MVC stays out of your way.

My only hurdle was getting used to it, and getting to know it on its own terms.

Further Reading

You Should Learn MVC by Rob Conery


问:
Properties under ARC: Always or public-only?
After reading an article humbly named "The Code Commandments: Best Practices for Objective-C Coding" by Robert McNally a little less than two years ago, I adopted the practice of using properties for pretty much every data member of my Objective-C classes (the 3rd commandment as of may 2012). McNally lists these reasons for doing so (my emphasis):

Properties enforce access restrictions (such as readonly)

Properties enforce memory management policy (strong, weak)

Properties provide the opportunity to transparently implement custom setters and getters.

Properties with custom setters or getters can be used to enforce a thread-safety strategy.

Having a single way to access instance variables increases code readability.

I put most of my properties in private categories, so number 1 and 4 are usually not issues I run in to. Arguments 3 and 5 are more 'soft', and with the right tools and other consistencies they could become non-issues. So finally, to me the most influential of these arguments was number 2, memory management. I've been doing this ever since.

```<code>@property (nonatomic, strong) id object; // Properties became my friends.
</code>```

For my last few projects I've switched to using ARC, which made me doubt whether creating properties for pretty much anything is still a good idea or maybe a little superfluous. ARC takes care of memory managing Objective-C objects for me, which for most strong members works fine if you just declare the ivars. The C-types you had to manually manage anyway, before and after ARC, and the weak properties are mostly public ones.

Of course I still use properties for anything that needs access from outside of the class, but those are mostly only a handful of properties, while most data members are listed as ivars under the implementation header

```<code>@implementation GTWeekViewController
{
    UILongPressGestureRecognizer *_pressRecognizer;
    GTPagingGestureRecognizer *_pagingRecognizer;
    UITapGestureRecognizer *_tapRecognizer;
}
</code>```

As an experiment I've been doing this a bit more rigorously, and the move away from properties for everything has some nice positive side effects.

Data member code requirements (@property/@synthesize) shrunk down to just the ivar declaration.

Most of my self.something references cleaned up to just _something.

It's easily distinguishable which data members are private (ivars) and which are public (properties).

Lastly, it 'feels' more like this was the purpose Apple intended properties for, but that's subjective speculation.

On to the question: I'm slowly sliding towards the dark side, using less and less properties in favor of implementation-ivars. Can you provide me with a bit of reasoning for why I should stick to using properties for everything, or confirm my current train of thoughts as to why I should use more ivars and less properties only where needed? The most persuasive answer for either side will receive my mark.

EDIT: McNally weighs in on Twitter, saying: "I think my main reason for sticking with properties is: one way to do everything, that does everything (including KVC/KVO.)"

答: I've also been pondering on this question. In my humble Opinion, only using properties for accessors makes the code much more readable. You can immediately see what variables are meant to be accessed publicly. And personally, always typing @property (...) in front of a variable is time consuming. </p>


问:
alternative to environment variables
The amount of servers and the complexity of our application is growing and we now have servers in different regions (hosted on AWS).  Certain database operations require low latency so we have stuck a database in each region (which is basically a user cache) to keep the network latency low.  The way the application server currently knows which user cache/database to make its call to depends on an environemnt variable set in it.  This has been working fine, but it seems hacky and not optimal.  Is there any way for this to be done automatically?

I was considering using a package like fping and pinging each database when the app server reloads (or caching it the first time) and using the corresponding latencies to decide which database has the lowest latency for each app server.  Not sure if this is the best idea though.

答:
You can use cloudformation templates to inject the database into configuration files or startup scripts. If the database changes ip address then you would need to automate via some orchestration script that changes the files and reloads. See fabric or saltstack.

Use ec2 api calls to autodiscover the db ip address by quering list of machines by tag.

Instead of rolling your own db. Use one if amazon's storage services such as simpledb.

Title: alternative to environment variables


答:
Your plan of chucking System A and rewriting it based on System B can work, but only if a few conditions are met:

System B must already provide a significant portion of the functionality that System A has. Otherwise, you are just rewriting from scratch and the cautions in the answer from @akh2103 apply.

The architecture of System B lends itself well to add extensions to the system. If this isn't the case, trying to add the additional functionality that System A needs will create just as big a mess as System A currently is.

The excess functionality that System B has (but System A doesn't need) and the new functionality don't interfere with each other, or multiple deployments with subsets of the overall functionality are possible for the updated System B+.

If these conditions are met, it can work to migrate to a system that incorporates both the current System A and the current System B. In doing so, I would try to use a 'copy - refactor' cycle as much as possible in adding the System A functionality to the new System, instead of rewriting all the new features from scratch.


问:
Which approach to follow for developing applications targeting multiple platforms?
For applications targeting multiple platforms, I see mainly two development approaches-

Go for some JAVA-like development platform. Have one code solution and let the intermediate runtime handle different platforms. If something goes wrong in any platform, tweak the code a bit. But keep it same for all.

Make modular code separating core logic and UI. Develop separate UIs for respective platforms which will be calling same core libraries. Build the application separately for each of the target platforms.

So, which one to follow? I know, the answer will start with "It depends". But I want to hear your opinions on these approaches and the factors to be considered to choose any of them.

答:
Everyone makes a big fuss about languages like Java being "cross platform" but what they are really talking about is that you can compile once and run everywhere. Even in a language like Java (or C#/mono) you are going to still need abstraction layers to deal with OS specific details in some areas.

C++, and in fact most languages, are cross platform, you just have to compile to target each platform.

They key is the process rather than the tools/languages:

Make sure you have an integrated build process that builds and runs the unit tests for all target platforms.

Make sure every developer tests on all target platforms before checking in code - This obviously means making sure ever developer has access to the appropriate number of machines/vms.

Abstract well. Abstract everything that calls into native apis. Write libraries that wrap these calls.

If you are doing anything beyond fairly simple forms UI that just caters to the lowest common denominator, just accept that GUI code is not cross platform. Abstract your GUI/presentation layer out and code it separately for each platform. Yes there are cross platform GUI toolkits, which are fine for straight forward apps but if you are doing anything more advanced you will want to code to the native platform capabilities.

These steps are the same no matter what language/toolset/framework you use.


问:
Do I need JUnit tests for the controller layer on a MVC when I have a database layer
I have a MVC which has this structure:

ui

controller

db

model

Basically the controller doesn't really do much more than connection ui with db layer.

Do I need to provide JUnit tests for the controller (if the program's point matters, it's my semester project)?

Would that help me somehow as there isn't much code - I basically take all the parameters and put them, shouldn't this be covered by model layer tests?

Example methods I have in the controller:

Inserting:

```<code>public int createEmployeeJob(String jobName)
{
    int result = -3;

    try
    {
        EmployeeJob newEmployeeJob = new EmployeeJob();

        newEmployeeJob.setJobName(jobName);

        DBConnection.startTransaction();

        IFEmployeeJob dbEmployeeJob = new DBEmployeeJob();
        result = dbEmployeeJob.createEmployeeJob(newEmployeeJob);

        DBConnection.commitTransaction();
    }
    catch (Exception e)
    {
        DBConnection.rollbackTransaction();
    }

    return result;
}
</code>```

Retrieving:

```<code>public ArrayList<EmployeeJob> printAllEmployeeJobs() throws SQLException
{
    IFEmployeeJob dbEmployeeJob = new DBEmployeeJob();

    return dbEmployeeJob.printAllEmployeeJobs();
}
</code>```

答:
You need unit tests in proportion to the risk that the code in that class introduces an error.

Complex code is more risky than simple code. Long methods are more risky than short ones. Code that implements decisions is more risky than code that simply funnels values to somewhere else, etc. Therefore, as long as your controller layer does nothing but copy values from one place to another, it has the lowest priority for writing tests. But having tests is still better than not having them - even the simplest code can introduce errors, particularly since you believe it's simple and check it last if something goes wrong.

Note that if the entire layer is so straightforward and repetitive that it really only repeats actions at another layer, the right thing to do is to have it auto-generated, write a test for the auto-generator, and then never worry about it again.


问:
Branching strategy to avoid multiple release branches for different customers
I am currently thinking of the following branching strategy

Main branch

Development branch

Feature branch

Release branch

Basically the whole idea is to have a release branch so that hot fix can be applied quickly for specific release.

Here is the issue what if I have an urgent feature that I need to do for a specific customer and I do not want those feature to be applied to other customer using the same release version until it is fully tested. At the same time I do not wish to create multiple release branches for different customers as this will complicate stuff.

What is the best way to handle such situation?

答:
Rather than having a separate SCM repository for each customer - you could have something like a feature toggle in the same code-base.

A feature toggle is something you could configure in the database, based on a particular attribute that uniquely distinguishes the customer.

For eg; assume a feature F, and customers C1 and C2. C1 wants the feature, and C2 doesn't. Your feature_list table would have entries like:

```<code>Feature     Customer     Available?
  F            C1           Y
  F            C2           N
</code>```

Together with a caching strategy (since the above data would be consulted on a frequent basis), your code could decide whether or not a feature needs to be made available for a given customer.

Body:
Rather than having a separate SCM repository for each customer - you could have something like a feature toggle in the same code-base.

A feature toggle is something you could configure in the database, based on a particular attribute that uniquely distinguishes the customer.

For eg; assume a feature F, and customers C1 and C2. C1 wants the feature, and C2 doesn't. Your feature_list table would have entries like:

Feature     Customer     Available?
  F            C1           Y
  F            C2           N

Together with a caching strategy (since the above data would be consulted on a frequent basis), your code could decide whether or not a feature needs to be made available for a given customer.


问:
Why would you hire in-house software developers instead of outsourcing them to develop a product for your company?
Why would you hire in-house over outsourcing in developing a product for your company? I can only think of a few but I'm not entirely sure if they're good enough reason.

This is actually for a debate that I'm going to have in class. I'm more inclined on the outsourcing part but unfortunately, I was asked to switch to the in-house side of the debate.

Any ideas?

答:
It depends upon various factors:

If you are developing a software product; obviously you must be having some secret plans, confidentiality, new ideas, etc. associated with it which makes it more sensitive to be preferred to do in house rather than outsourcing your software development requirement.

On the other hand, if you have tight budget or you want to focus more on sales and marketing activities rather than hardcore development or if you have more workflow than your current team can handle; you can go with software development outsourcing.

So, it all depends upon your preferences; both the options have their own pros and cons. If I have to develop a simple website, I will prefer to hire a website development company to outsource it and if I have to make a software product say CRM or an ERP, I will prefer to do it in-house.


问:
What could be the use of forking a repository in a github's organization?
I'm trying to figure it out some nice workflow for our company, and we have so far the main  repository on the github's organization account and we all, the members of the team working on the branches of that repo.

Could you please mention some advantages on forking the repo or some use, by the members of the organization?

I was thinking, that for example, I could make a fork and perform a upgrade of the libraries, but  someone pointed that, "what is the differences on doing it simply in another branch,without forking?

Thank you in advance, for your time.

答: To add to Karl's answer, pull requests are a good place to discuss the code added since each individual pull request have their own comment thread that is also markdown supported. This serves as a good form of documentation when you're trying to find out the reason behind a certain change in the codebase.</p>