问:
Is machine language always binary?
I know absolutely nothing in low-level stuff, so this will be a very newbie question. Please excuse my ignorance.

Is machine language - the series of numbers to that tell the physical computer exactly what to do - always binary? I.e. always composed of only zeros one ones? Or could it also be composed of numbers such as 101, 242, 4 etc.?

答:
Almost all "computers" these days use binary logic. However, the meaning of "computer" post-WW II has come to mean a computing device with persistent storage and stored programs, rather than just a simple computing engine like a calculator.

A few examples of the exceptions are:

There might be a few odd-ball trinary (or more) logic systems in labs.

There are a few analog computing systems are in use.

An example of a future high performance computing system not using binary logic might be the D-Wave quantum annealing systems.

Title: Is machine language always binary?


问:
Implementing TDD for existing code
I've just been learning Unit Testing and I'm trying to understand how I could incorporate it with a project with existing code. Say I wanted to write tests for a specific class in that project, but that certain class requires an instance of another class for the the methods to be run and/or tested. How should I approach this? </p>

答:
This is a very complex question, in a legacy systems designed without testability in mind probably there are a lot of coupling and this coupling make testing in isolation (unit testing) more difficult. </p>

<p>I can give concrete answer if you ask a concrete question, with code and a concrete situation, but if you ask for general advice the best thing i can do is recommend to you the fantastic book form michael feathers working effectively with legacy code (http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052). </p>

ContentLicense: CC BY-SA 3.0

Title: Implementing TDD for existing code

Body:
This is a very complex question, in a legacy systems designed without testability in mind probably there are a lot of coupling and this coupling make testing in isolation (unit testing) more difficult.

I can give concrete answer if you ask a concrete question, with code and a concrete situation, but if you ask for general advice the best thing i can do is recommend to you the fantastic book form michael feathers working effectively with legacy code (http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052).


答:
It's not always easy and sometimes you just have to be pragmatic and use integration tests or end-to-end tests to begin with until you have refactored code to be more testable.

Perhaps try to refactor the class to use an interface instead of a concrete class and inject in the implementation during construction.  Then use a mocking framework or roll your own mock class and inject that in instead during testing.

Some mocking frameworks are able to mock concrete classes but it depends on the language.

Title: Implementing TDD for existing code

Body: I've just been learning Unit Testing and I'm trying to understand how I could incorporate it with a project with existing code. Say I wanted to write tests for a specific class in that project, but that certain class requires an instance of another class for the the methods to be run and/or tested. How should I approach this? </p>


问:
What goes within the Architecture Overview of a Design Specification?
I have designed an management system for a medical practice and I am writing the design specification and I am kind of stumped by what to write for a section. </p>

<p>It asks for me to write about the components of a system but I am perplexed. What exactly are components within a system? Is this generally considered as the features that a system has or does it mean something else altogether? </p>

答:
Component can mean several things depending on, heck, a lot of things actually. Generally it's a distinct unit of functionality.

A little red warning light popped on when you said you were unsure "what to write for a section". It suggests you're either doing a college project, or using a pre-created template. Neither of these are bad things, but it does mean that the definition of component may have a very specific definition, as will the scope of the section.

TOGAF (serious architecture) gives a bunch of good definitions which I'll quote below, but if you are completing an assignment, your best bet is really to ask the people setting the assignment. Academia has some weird ideas about what happens in the real world sometimes ;)

I've grabbed a bunch of TOGAF from one section because all of these, could fall under one person's definition of a component, not just the two with component in the title :)

TOGAF defintions:

Actor: A person, organization, or system that is outside the
    consideration of the architecture model, but interacts with it.

Application Component: An encapsulation of application functionality that is aligned to implementation structuring.

Business Service: Supports business capabilities through an explicitly defined interface and is explicitly governed by an
    organization.

Data Entity: An encapsulation of data that is recognized by a business domain expert as a discrete concept. Data entities can be tied to applications, repositories, and services and may be structured according to implementation considerations.

Function: Delivers business capabilities closely aligned to an organization, but not explicitly governed by the organization.

Information System Service: The automated elements of a business service. An information system service may deliver or support part or all of one or more business services.

Organization Unit: A self-contained unit of resources with goals, objectives, and measures. Organization units may include external parties and business partner organizations.

Platform Service: A technical capability required to provide enabling infrastructure that supports the delivery of applications.

Role: An actor assumes a role to perform a task.

Technology Component: An encapsulation of technology infrastructure that represents a class of technology product or specific technology product.


答:
I'll be quite radical but please read this fully before criticising.

In short: test-driven design is a kind of myth. It's impossible for implementation even for a new code unless all specifications are already fixed and won't change (that's classic "Waterfall" case but not a "Agile" one, opposed to the usually declared TDD application area). When it works out of one-shot projects, it works only because its principles are violated, not satisfied.

To understand this, one should imagine case the specification is changed and a new requirement is added, but it's already satisfied in existing code. Should the existing code be dropped and rewritten from scratch? Classic TDD description can't answer this at all - it doesn't deal with an existing code case.

The second question is what shall be tested. If a code piece shall satisfy tests but do nothing more, could be it only listed test cases in a big switch-case? If it doesn't, why? That's what is explicitly requested (at least in classical compact explanation).

The third question is how to check all marginal cases. If a routine multiplies numbers, shall it check INT_MIN*INT_MIN? Marginal cases knowledge is mainly discovered after some usage experience, but not a priori. (Yep, the more programmer's expertise is, the more ability to find such cases before writing the code he has. But 90% of any expertise is what one's shan't do, but not what one shall.)

My answer is that TDD fulfils two roles:

It shows an ideal, unreachable in practice (as infinity in mathematics) but ease to understand and so approximated as close as needed.

It provides an excuse for managers to require testing which is not postponed until "good times" but just now, before reporting a task finish.

So it shall be treated accordingly - "with enthusiasm but without fanaticism".

My personal attitude to TDD is formed with a specific experience of building complex systems which shall work "24*7*365" and an acceptance style approached to military grade. Such systems require, at developers' side, integrated testing of component chains and regular testing on the fly, at the same components and with the same algotithms, but with another tags (so, only final decision checker understands it wasn't real data). For our systems, TDD is intentionally replaced with the following approach:

Of course, the principle that code shall do what it is intended to, shall be more important that TDD (or analog) principle that a code is as small and simple as possible. This also means that code readability and debuggability is very important. (All this is not a Captain Obvious' comment but the written rule for those guys who tend to follow instructions in the most literal way, and who, regrettably, are present in every large team.)

Each component starts with a reasonably small test set which allows an experienced programmer to say it's checked, according to the current conditions and resources.

A part of time (of each programmer separately, or of the whole team) is dedicated to expanding tests for already existing components. This can be, according to goal specifics, 20% to 80%, but definitely not less. This work shan't stop until the whole project development is abandoned.

To answer the question whether a test works (which is answered by TDD in a one-shot, unscalable manner), the test itself shall have techniques to validate it. For this task, we use so-called inversions. An inversion is a change in incoming data or environment which shall break test in a known way. For example, if a function shall convert A1 to B1 and A2 to B2, its test which validates B1 is response to A1 shall fail if input value becomes A2, and, moreover, one can check failure details (generated exception type, error count, etc.) Not all tests shall have inversions; but, the more complex it is, the more principal inversions are.

P.S. For an initial guide to add tests to an existing project, you could start with M. Feather's book. It isn't based on TDD but, instead, is very practical in suggesting how to reform an existing code in a evolutionary manner.

Title: Implementing TDD for existing code


问:
What are some interesting but not too difficult projects for a beginner kernel hacker?
Having taken a course in Operating Systems I'm interested in expanding my knowledge of the Linux kernel and practice working with a big system. What are some interesting but not overly difficult projects I can try my hand at?

EDIT: a bit of background on what I did do with the kernel.

Implemented a new scheduling policy

Implemented User Threads and a corresponding mutex library (not really kernel hacking but contained kernel related theory)

答:
SourceForge.net for 'kernel drivers' lists 2800+ projects, maybe you can find something interesting there?

SourceForge.net for 'kernel' instead of 'kernel drivers' show 1403+ projects.

ContentLicense: CC BY-SA 2.5


问:
Best and safest API for a function which fills a buffer with variable-length data
I have a function which receives a buffer and returns some data in the buffer. The data can be smaller than the buffer capacity.

Which is the best and safest API for this?

int fn(void *buffer, size_t buffer_len): the size of the data written to buffer is returned by the function. Downside: the return value must also have a way to indicate that some error occurred (in-band error indicator).

errno_t fn(void *buffer, size_t *buffer_len): in this case, buffer_len works both as input (the buffer capacity) and output (the data size). The function can return an error code. I think this is OK, but somewhat awkward.

errno_t fn(void *buffer, size_t *data_len, size_t buffer_len): like the previous, but with input/output separated in two arguments. Also returns error code, but is also awkward due to too many arguments.

(Any other options?)

答:
I think the best API for such case is to create a buffer specification and deal with it, like:

```
struct sbuf {
  void *data;
  size_t size, pos, length;
};

// void if malloc() errors do abort(). int otherwise, to report error
void sbuf_alloc(sbuf *sb, size_t minsize);
void sbuf_free(sbuf *sb);

int /* or errno_t, whatever */ fn(sbuf *sb);
```

With such API, you'll avoid 1) long and cumbersome argument lists, 2) chance to mistake length for size and vice versa, and will gain instead understanding of object-like gist of your buffers.

Body:
I think the best API for such case is to create a buffer specification and deal with it, like:

struct sbuf {
  void *data;
  size_t size, pos, length;
};

// void if malloc() errors do abort(). int otherwise, to report error
void sbuf_alloc(sbuf *sb, size_t minsize);
void sbuf_free(sbuf *sb);

int /* or errno_t, whatever */ fn(sbuf *sb);

With such API, you'll avoid 1) long and cumbersome argument lists, 2) chance to mistake length for size and vice versa, and will gain instead understanding of object-like gist of your buffers.


答:
I'd support david's point of maintaining consistency, and since this seems to be C (and not C++), the required functionality is very much like the POSIX file read:

input buffer instead of a file.

output buffer for user, remains same.

number of bytes read or length, remains same.

So, I think sticking to POSIX is a good thing, and so the first option would be better, with a return of -1 for error (negative values for multiple errors is possible but appears clumsy):

int fn(void *buffer, size_t buffer_len)

Title: Best and safest API for a function which fills a buffer with variable-length data

Body:
I have a function which receives a buffer and returns some data in the buffer. The data can be smaller than the buffer capacity.

Which is the best and safest API for this?

int fn(void *buffer, size_t buffer_len): the size of the data written to buffer is returned by the function. Downside: the return value must also have a way to indicate that some error occurred (in-band error indicator).

errno_t fn(void *buffer, size_t *buffer_len): in this case, buffer_len works both as input (the buffer capacity) and output (the data size). The function can return an error code. I think this is OK, but somewhat awkward.

errno_t fn(void *buffer, size_t *data_len, size_t buffer_len): like the previous, but with input/output separated in two arguments. Also returns error code, but is also awkward due to too many arguments.

(Any other options?)


答:
If the code is already in production and has no tests for it, then by definition you cannot do TDD with it. At that point you have at least these alternatives:

Discard the code and start again using TDD. This can obviously be time consuming, but judging from previous experience it would often have been faster than the other alternatives.

Just use TDD for any new code. This leaves the old code to become a rotten core, a black box which eventually nobody will dare change and which is likely to drag down the performance, stability and security of the rest of the code for the lifetime of the project.

Add tests to the existing code incrementally, and use TDD for any new code. Surprisingly, in my experience this doesn't seem to help much. Unless the code is refactored (see next point) it will still, eventually, become a black box.

Use TDD for any new code, replacing bits of the old code with TDD code whenever you have to touch any of it. If alternative 1 is not going to happen, this at least gives you some chance that the project will not be chained to a ball of mud for the rest of time. But likely you'll find that pulling out one part of untested legacy code is likely to unravel it completely, and the combined effort of all the refactoring might take as much or more time than re-implementing.

Title: Implementing TDD for existing code


问:
When to build User Controls in ASP.NET
I am inheriting a legacy code. The legacy code has lot of web forms and each web form does not have much of functionality other than hosting a user control.

My question is -

Should we create a user control even if that control is not used in any other web form ?

Are there any hard benefits in creating user controls over web forms?

P.S - Web forms are .aspx files and User Controls are .ascx files.

答:
There are two approaches I can see:

One may use user controls just like one uses objects to make primitive data types and basic types within the language or framework more explicit or to enclose logic within them.

For example, in OOP, when you deal with percentage, one way is to use an int; a usually preferred way is to create Percentage class which will enclose the value, as well as its own logic, such as the limited range 0..100.

In the same way, instead of putting an <input type="text" /> for a temperature in Fahrenheit, one can create Temperature.ascx which, besides showing an input field, controls the value entered by the user (for example the range -459.67..∞) and adds the unit. Later, when business requirements change and the form should deal with Celsius, only Temperature.ascx has to be changed.

In this context, user controls may be a valuable tool for obtaining a clean architecture and limit code changes required by the changes in business requirements.

Another way is to create user controls for nearly every field, with no business logic inside, thinking that it may be useful in the future when the business requirements change.

For example, the uncontrolled (aside the maximum length) field Phone number may be enclosed within PhoneNumber.ascx control, expecting that one day, the app will check if the phone number is valid.

This is an extremely bad practice which violates KISS principle and should be avoided. If you encounter user controls which have no logic inside, remove them and put simple ASP.NET controls or fields instead.

Title: When to build User Controls in ASP.NET


问:
Should I strictly follow every single HTML and CSS Standard?
A few years ago I considered myself somewhat of a web developer, knowing the basic 3 languages (HTML, CSS, JS) and lots of PHP. Moving on from simple text to actual websites was a pain because of the so called "standards" out there, which at the time were ridiculously complicated for me. It pretty much boiled down to this (minus the IE related stuff):

Standards are there to replace old ways of doing things in a simpler way. However when trying to actually implement some of the stuff (Entirely CSS based layout for example), it took me 10x longer to actually do it then if I did the simpler and still working solution. If it rendered the same, then why should I use the more complicated example that takes 10x longer and breaks once you change browsers? This sparked many long religious debates in ##php, ##css, and ##js in Freenode IRC and actually got me banned from ##css because I messed with their little world over there.

My question: Should I follow every single standard and coding conventions even if they take me 10x longer but get me the same result as the simple one?

For the poll tag, those of you who have websites of any size (huge or small), do you follow all the standards?

答:
Don't follow stanards blindly.  Some standards are good, some are bad.  They serve various purposes and some, like the drafts of HTML5, serve to push a collection of the big browser makers and web developers in one particular direction that seems mostly good.  But always remember that there are loads of terrible things out there that have been standardized...

COBOL was a standard, too.


问:
Implementing a strategy pattern with dependency injection
Okay, so the goal here is to implement a strategy pattern that can be tested using any sort of automated testing tool.

I've been struggling with this problem conceptually for a few weeks now and I want to clarify it.

So the current setup is something like this:

```<code><?php
// CreateReportUseCase.php
class CreateReportUseCase
{
 protected $factory;
 public function __construct(Factory $factory)
 {
    $this->factory = $factory;
  }

  public function create($params)
  {
    // based on something in the params
    // ask the factory to give us one of the strategy classes

    // for this example, let's assume I'm going to execute
    // a different strategy based on the user role.
    // e.g. Admin
    $strategy = $this->factory->make($params['user_role']);

    // execute the strategy using the data out of the params
    $strategy->execute($params);
  }
}

// Factory.php
class Factory
{
  protected $admin_strategy;
  protected $user_strategy;
  public function __construct(AdminStrategy $admin_strategy, UserStrategy $user_strategy)
  {
    $this->admin_strategy = $admin_strategy;
    $this->user_strategy = $user_strategy;
  }

  public function make($role)
  {
    switch($role)
    {
       case 'Admin':
         return $this->admin_strategy;
         break;
       case 'User':
         return $this->user_strategy;
         break;
    }
  }
}

AdminStrategy implements RoleStrategy
{
  public function execute($params)
  {
    // it's not important what we do here.
    return json_encode($params);
  }
}
</code>```

Does this look sane to you? How could I improve it? To me, the factory looks like it's a bit awkward since it's just returning some injected dependency instead of instantiating a strategy.

答:
In the end, collecting all advice in the comments section, I went with making the Factory an actual Factory, providing it with a dictionary between some parameters like 'User' and a fully qualified namespace + class name.

This way the Factory isn't coupled with the actual strategies, and it actually builds instances instead of just passing an attribute back.

As suggested, the chosen strategy is then placed inside a property on the Context class.


问:
what is the javascript internal data structure?
Consider a basic js object:

```<code>var obj={x:1,y:'2'};
</code>```

Is this stored internally as a hashtable or does js use a different mechanism for key value pairs? If they are hash tables does anyone know how they handle collisions?

答:
Depends on the implementation.

From v8/src/objects.h (Chrome's V8):

```<code>// Inheritance hierarchy:
// - MaybeObject    (an object or a failure)
//   - Failure      (immediate for marking failed operation)
//   - Object
//     - Smi          (immediate small integer)
//     - HeapObject   (superclass for everything allocated in the heap)
//       - JSReceiver  (suitable for property access)
//         - JSObject
//           - JSArray
//           - JSArrayBuffer
//           - JSArrayBufferView
//             - JSTypedArray
//             - JSDataView
//           - JSSet
//           - JSMap
//           - JSSetIterator
//           - JSMapIterator
//           - JSWeakCollection
//             - JSWeakMap
//             - JSWeakSet
//           - JSRegExp
//           - JSFunction
//           - JSGeneratorObject
//           - JSModule
//           - GlobalObject
//             - JSGlobalObject
//             - JSBuiltinsObject
//           - JSGlobalProxy
//           - JSValue
//             - JSDate
//           - JSMessageObject
//         - JSProxy
//           - JSFunctionProxy
//       - FixedArrayBase
//         - ByteArray
//         - FixedArray
//           - DescriptorArray
//           - HashTable
//             - Dictionary
//             - StringTable
//             - CompilationCacheTable
//             - CodeCacheHashTable
//             - MapCache
//           - OrderedHashTable
//             - OrderedHashSet
//             - OrderedHashMap
//           - Context
//           - JSFunctionResultCache
//           - ScopeInfo
//           - TransitionArray
//         - FixedDoubleArray
//         - ExternalArray
//           - ExternalUint8ClampedArray
//           - ExternalInt8Array
//           - ExternalUint8Array
//           - ExternalInt16Array
//           - ExternalUint16Array
//           - ExternalInt32Array
//           - ExternalUint32Array
//           - ExternalFloat32Array
//       - Name
//         - String
//           - SeqString
//             - SeqOneByteString
//             - SeqTwoByteString
//           - SlicedString
//           - ConsString
//           - ExternalString
//             - ExternalAsciiString
//             - ExternalTwoByteString
//           - InternalizedString
//             - SeqInternalizedString
//               - SeqOneByteInternalizedString
//               - SeqTwoByteInternalizedString
//             - ConsInternalizedString
//             - ExternalInternalizedString
//               - ExternalAsciiInternalizedString
//               - ExternalTwoByteInternalizedString
//         - Symbol
//       - HeapNumber
//       - Cell
//         - PropertyCell
//       - Code
//       - Map
//       - Oddball
//       - Foreign
//       - SharedFunctionInfo
//       - Struct
//         - Box
//         - DeclaredAccessorDescriptor
//         - AccessorInfo
//           - DeclaredAccessorInfo
//           - ExecutableAccessorInfo
//         - AccessorPair
//         - AccessCheckInfo
//         - InterceptorInfo
//         - CallHandlerInfo
//         - TemplateInfo
//           - FunctionTemplateInfo
//           - ObjectTemplateInfo
//         - Script
//         - SignatureInfo
//         - TypeSwitchInfo
//         - DebugInfo
//         - BreakPointInfo
//         - CodeCache
//
// Formats of Object*:
//  Smi:        [31 bit signed int] 0
//  HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
//  Failure:    [30 bit signed int] 11
</code>```

Can't say for certain but I'd imagine it's a JSMap considering a JSReceiver is  "suitable for property access".

From mozjs-24.2.0/js/src/jsobj.h (Firefox's SpiderMonkey):

```<code>/*
 * JS object definitions.
 *
 * A JS object consists of a possibly-shared object descriptor containing
 * ordered property names, called the map; and a dense vector of property
 * values, called slots.  The map/slot pointer pair is GC'ed, while the map
 * is reference counted and the slot vector is malloc'ed.
 */
</code>```

Looks like a map again.

If you're really curious you might want to check out the source yourself.

Body:
Depends on the implementation.

From v8/src/objects.h (Chrome's V8):

// Inheritance hierarchy:
// - MaybeObject    (an object or a failure)
//   - Failure      (immediate for marking failed operation)
//   - Object
//     - Smi          (immediate small integer)
//     - HeapObject   (superclass for everything allocated in the heap)
//       - JSReceiver  (suitable for property access)
//         - JSObject
//           - JSArray
//           - JSArrayBuffer
//           - JSArrayBufferView
//             - JSTypedArray
//             - JSDataView
//           - JSSet
//           - JSMap
//           - JSSetIterator
//           - JSMapIterator
//           - JSWeakCollection
//             - JSWeakMap
//             - JSWeakSet
//           - JSRegExp
//           - JSFunction
//           - JSGeneratorObject
//           - JSModule
//           - GlobalObject
//             - JSGlobalObject
//             - JSBuiltinsObject
//           - JSGlobalProxy
//           - JSValue
//             - JSDate
//           - JSMessageObject
//         - JSProxy
//           - JSFunctionProxy
//       - FixedArrayBase
//         - ByteArray
//         - FixedArray
//           - DescriptorArray
//           - HashTable
//             - Dictionary
//             - StringTable
//             - CompilationCacheTable
//             - CodeCacheHashTable
//             - MapCache
//           - OrderedHashTable
//             - OrderedHashSet
//             - OrderedHashMap
//           - Context
//           - JSFunctionResultCache
//           - ScopeInfo
//           - TransitionArray
//         - FixedDoubleArray
//         - ExternalArray
//           - ExternalUint8ClampedArray
//           - ExternalInt8Array
//           - ExternalUint8Array
//           - ExternalInt16Array
//           - ExternalUint16Array
//           - ExternalInt32Array
//           - ExternalUint32Array
//           - ExternalFloat32Array
//       - Name
//         - String
//           - SeqString
//             - SeqOneByteString
//             - SeqTwoByteString
//           - SlicedString
//           - ConsString
//           - ExternalString
//             - ExternalAsciiString
//             - ExternalTwoByteString
//           - InternalizedString
//             - SeqInternalizedString
//               - SeqOneByteInternalizedString
//               - SeqTwoByteInternalizedString
//             - ConsInternalizedString
//             - ExternalInternalizedString
//               - ExternalAsciiInternalizedString
//               - ExternalTwoByteInternalizedString
//         - Symbol
//       - HeapNumber
//       - Cell
//         - PropertyCell
//       - Code
//       - Map
//       - Oddball
//       - Foreign
//       - SharedFunctionInfo
//       - Struct
//         - Box
//         - DeclaredAccessorDescriptor
//         - AccessorInfo
//           - DeclaredAccessorInfo
//           - ExecutableAccessorInfo
//         - AccessorPair
//         - AccessCheckInfo
//         - InterceptorInfo
//         - CallHandlerInfo
//         - TemplateInfo
//           - FunctionTemplateInfo
//           - ObjectTemplateInfo
//         - Script
//         - SignatureInfo
//         - TypeSwitchInfo
//         - DebugInfo
//         - BreakPointInfo
//         - CodeCache
//
// Formats of Object*:
//  Smi:        [31 bit signed int] 0
//  HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
//  Failure:    [30 bit signed int] 11

Can't say for certain but I'd imagine it's a JSMap considering a JSReceiver is  "suitable for property access".

From mozjs-24.2.0/js/src/jsobj.h (Firefox's SpiderMonkey):

/*
 * JS object definitions.
 *
 * A JS object consists of a possibly-shared object descriptor containing
 * ordered property names, called the map; and a dense vector of property
 * values, called slots.  The map/slot pointer pair is GC'ed, while the map
 * is reference counted and the slot vector is malloc'ed.
 */

Looks like a map again.

If you're really curious you might want to check out the source yourself.


问:
Strategy for generating unique and secure identifiers for use in a "sometimes offline" web app
I have a web based project that allows users to work both online and offline and I'm looking for a way to generate unique ids for records on the client side. I'd like an approach that works while a user is offline (i.e. unable to talk to a server), is guaranteed to be unique, and is secure. By "secure", I'm specifically worried about clients submitting duplicate id's (maliciously or otherwise) and thereby wreaking havoc on data integrity.

I've been doing some googling, hoping this was already a solved problem. I haven't found anything that's very definitive, especially in terms of approaches that are in use in production systems. I found some examples for systems where users will only access the data that they've created (e.g. a Todo list that's accessed on multiple devices, but only by the user who created it). Unfortunately, I need something a bit more sophisticated. I did find some really good ideas here, which are in line with how I was thinking things might work.

Below is my proposed solution.

Some Requirements

IDs should be globally unique (or at least unique within the system)

Generated on the client (i.e. via javascript in the browser)

Secure (as outlined above and otherwise)

Data can be viewed/edited by multiple users, including users who didn't author it

Doesn't cause significant performance issues for backend db's (such as MongoDB or CouchDB)

Proposed Solution

When users create an account, they would be given a uuid which was generated by the server and known to be unique within the system. This id must NOT be the same as the users authentication token. Let's call this id the users "id token".

When a user creates a new record, they generate a new uuid in javascript (generated using window.crypto when available. See examples here). This id is concatenated with the "id token" the user received when they created their account. This new composite id (server side id token + client side uuid) is now the unique identifier for the record. When the user is online and submits this new record to the backend server, the server would:

Identify this as an "insert" action (i.e. not an update or a delete)

Validate both parts of the composite key are valid uuids

Validate that the provided "id token" part of the composite id is correct for the current user (i.e. it matches the id token the server assigned to the user when they created their account)

If everything is copasetic, insert the data into the db (being careful to do an insert and not an "upsert" so that if the id does already exists it doesn't update an existing record by mistake)

Queries, updates, and deletes wouldn't require any special logic. They would simply use the id for the record in the same manner as traditional applications.

What are the advantages of this approach?

Client code can create new data while offline and know the id for that record immediately. I considered alternate approaches where a temporary id would be generated on the client which would later be swapped out for a "final" id when the system was online. However, this felt very brittle. Especially when you start thinking about creating child data with foreign keys that would also need to be updated. Not to mention dealing with urls that would change when the id changed.

By making ids a composite of a client generated value AND a server generated value, each user is effectively creating ids in a sandbox. This is intended to limit the damage that can be done by a malicious/rogue client. Also, any id collisions are on a per user basis, not global to the entire system.

Since a users id token is tied to their account, ids can only be generated in a users sandbox by clients that are authenticated (i.e. where the user successfully logged in). This is intended to keep malicious clients from creating bad ids for a user. Of course if a users auth token were stolen by a malicious client, they could do bad things. But, once an auth token has been stolen the account is compromised anyhow. In the event that this did happened, the damage done would be limited to the compromised account (not the entire system).

Concerns

Here are some of my concerns with this approach

Will this generate sufficiently unique ids for a large scale application? Is there any reason to think this will result in id collisions? Can javascript generate a sufficiently random uuid for this to work? It looks like window.crypto is fairly widely available and this project already requires reasonably modern browsers. (this question now has a separate SO question of its own)

Are there any loopholes that I'm missing which could allow a malicious user to compromise the system?

Is there reason to worry about DB performance when querying for a composite key made up of 2 uuids. How should this id be stored for best performance? Two separate fields or a single object field? Would there be a different "best" approach for Mongo vs Couch? I know that having a non-sequential primary key can cause notable performance issues when doing inserts. Would it be smarter to have an auto generated value for the primary key and store this id as a separate field? (this question now has a separate SO question of its own)

With this strategy, it would be easy to determine that a particular set of records was created by the same user (since they'd all share the same publicly visible id token). While I don't see any immediate issues with this, it's always better to not leak more info about internal details than is needed. Another possibility would be to hash the composite key, but that seems like it may be more trouble than it's worth.

In the event that there is an id collision for a user, there's not a simple way to recover. I suppose the client could generate a new id, but this seems like a lot of work for an edge case that really shouldn't ever happen. I'm intending to leave this unaddressed.

Only authenticated users can view and/or edit data. This is an acceptable limitation for my system.

Conclusion

Is above a reasonable plan? I realize some of this comes down to a judgement call based on a fuller understanding of the application in question.

答:
You need to separate the two concerns:

ID generation: client must be able to generate a unique identifier in distributed system

Security concern: client MUST have a valid user authentication token AND the authentication token is valid for the object being created/modified

The solution to these two unfortunately are separate; but fortunately they are not incompatible.

The concern about ID generation is easily solved by generating with UUID, that is what UUID is designed for; the security concern however would require that you make a check in the server that the given authentication token is authorized for the operation (i.e. if the auth token is for a user that does not own the necessary permission on that particular object, then it MUST be rejected).

When handled correctly, collision would not really pose a security issue (the user or the client will simply be asked to retry the operation with another UUID).

OwnerDisplayName: herbrandson


问:
Delphi 7 using RAM for database
I have an existing database app written in D7 with apollo databases.

The client has given me a fast desktop with 24gb ram

Can I somehow load the database files into ram to speed up processing?

With millions of records some procedures take 1/2 hour or more, mostly due to disk read/write

答:
Probably the easiest way is to use a "RAM Disk". There are various bits of software around.

http://www.softperfect.com/products/ramdisk/

Of course, loading large amounts of data into RAM will itself take some time. Fitting the computer with an SSD would give some performance boost without having to load the data into RAM.

-EDIT

As an aside, you don't say much about what processing you are doing on the data which can have a major effect. If, for instance, you are reading each record doing a calculation and writing the data back, then loading the data into RAM may actually slow things down as you will load into ram, load record from ram, process record, save to ram, save to disk instead of simply load a record to RAM, process record, save to disk.

Title: Delphi 7 using RAM for database


问:
Improving ZooKeeper to increase availability
Running Apache ZooKeeper (this applies to PAXOS style system just as well) with 2 members - which is not recommended - does not make sense, because if either

member1 goes down

member2 goes down

there's a network partition between member1 and member2

, ZooKeeper will declare business hours to be over, as there's no single sub cluster with a clear majority of members (in this case: > 1). So running ZooKeeper on 2 members makes it less available than running a single member.

Why can't the majority constraint be relaxed so that when the there's a sub cluster of exactly 50% of members, it is considered the active sub cluster if it contains the eldest member? (Eldest as of the just before the partition happened, i.e. when the cluster was member-complete) Who's eldest is information ZooKeeper already keeps track of, so implementation looks easy.

That way, we don't run into the dreaded split-brain scenario, and the ZooKeeper cluster could stay up in 2 of the 3 cases above, improving availability, especially when running 2 members only.

Anything speaking against this?

答:
The entire point of Zookeeper (as I understand it) is to make restart AFTER the partition goes away simple by making sure that there's only ONE portion (the majority) that was changing during the partition. It can then bring the minority up to speed when they reconnect and everything is running again with no further intervention on your part.

If you let two minority clusters run, then zookeeper has NO IDEA what to do when they reconnect. If you're lucky it won't take you too long to put the mess back together. If you aren't lucky, some incompatible change will have happened on both sides of the partition and you'll be days cleaning up the mess.

I suspect that if you need the minority portions of a cluster to operate independently, then you either need a solution different than Zookeeper, OR perhaps you don't actually want a cluster at all, perhaps you want a bunch of systems that replicate back and forth somehow and just sync data whenever they can.


问:
How does assembly relate to machine/binary code
How does assembly relate to machine/binary code.

For example here is how to print to the screen in mikeOS(a small pure assembly OS), mikeOS it uses NASM to assemble.

```<code>BITS 16
    ORG 32768
    %INCLUDE 'mikedev.inc'

start:
    mov si, mystring
    call os_print_string

    call os_wait_for_key

    ret

    mystring db 'My first MikeOS program!', 0
</code>```

Where os_print_string and os_wait_for_key are defined as

```<code>os_print_string     equ 0003h   ; SI = zero-terminated string
</code>```

and

```<code>os_wait_for_key     equ 0012h   ; Returns AL = key pressed
</code>```

in mikedev.inc respectively and defined as

```<code>os_call_vectors:
    jmp os_print_string     ; 0003h
</code>```

in kernal.asm

Now nasm must do a lot more work under the scene when assembling, I have no idea what.

In other words assembly language is a wrapper to some degree to machine code just as say C is a wrapper to assembly. If I said cout >> "Hello World" for example in C++, this is then compiled into it's assembly equivalent and them assembled into machine code.

So I am trying to understand out how 0003h and 0012h seem to dictate everything that is going on when printing to the screen. How do these two values,

a) Tell the CPU/PC system which bus to send the corresponding bytes that represent the required string to the monitor bus and not say to the sound card.

b) In this case the string is sent to the monitor, obviously, now my understanding is that you have a frame buffer that can store a maximum number of bytes. So say the resolution of your screen is set at 1024 x 768 which is 786432 pixels and a refresh rate of 60hz on the screen, therefore the FB will contain this number of byte values and hence will be sending this many bytes to the monitor every 1/60 sec. The first byte in the FB corresponding to the first pixel on the screen and the last to the last on the screen etc.

So how does the CPU/GPU know which byte to put in which position in the FB. It's like saying to the GPU 'ok I need this pixel at coord (245,232) green so I will leave it to you to put this pixels value in the correct position in the FB' etc.

How does this work.

答:
Paul Glover correctly explained the working of those system call values as being addresses that contain jump instructions to the actual OS routines.

That is to say, the CPU/GPU do NOT know where to put your pixels, but the OS routines, or drivers, do. You pass them arguments (x, y, r, g, b), and the OS routines put the r,g,b values to the byte positions correct for the buffer in use. If eg. you have a 10x10 pixel screen, its buffer is an array of 10x10x3 = 300 color intensities.

If each of them is a byte, setting pixel (3,5) to yellow might mean setting buffer[3*(3*10+5)] to 0xFF (fully red), buffer[3*(3*10+5)+1] to 0xFF (fully green), and buffer[3*(3*10+5)+2] to 0x00 (not at all blue). The screen itself (ie. it's controller) reads the values from the buffer and sets the individual color dots to the specified intensities.

If there is a GPU, the process may be different in that the OS routines put 'blueprints' into memory, tell the GPU to display them (passing the address, or placing them at a fixed address for that purpose), upon which the GPU calculates the pixels and places them in the buffer.

buffer[n] is just a shortcut for memory[buffer_start + n], where memory may be on the same bus as the RAM, or it may be on a designated I/O bus.

The asm instructions themselves are also numbers, and their 'arguments' or 'operands' are numbers too.

When trying to understand how these machine-level (as opposed to OS level) mechanisms work, some analogy to the physical world might help.

Suppose you have a car. There are three pedals, a lever for selecting a gear, and a steering wheel. Suppose that pedals can only be up or down, there are a maximum of 7 gears, and 4 states of the steering wheel. That setup would give you an 8-bit car ;)

Now the engineer who builds that car gets to decide about how to wire it. My proposal would be:

```<code>    Wheel                 Pedals                Gears
0 0  locked         0 0 0  roll (nop)       0 0 0  no gear
1 1  straight       1 0 0  change gear      1 1 1  7 = reverse
1 0  left           0 1 0  brake            0 0 1  1.
0 1  right          0 0 1  accelerate       0 1 0 ... 1 1 0   2., ..., 6.
</code>```

So, 'accelerate while turning left in 2nd gear' would have an assembled opcode of

```<code>1 0  0 0 1  0 1 0 == 0x8A
ie. (wheel << 6) | (pedals << 3) | (gears) = encoded instruction.
</code>```

Any opcodes having more than one pedal bit set would be invalid, except for the combination of 'change gear' and 'brake'.

Or maybe, the gear is only an operand when actually changing gears, and the opcode for simply 'accelerate while turning left in current gear' is 0x88. Or maybe, the engineer is not me (I'm not), the bits are placed differently, and diffferent opcodes result.

The point is, the engineer decides, and once it's built, the bits are 'wired' to have precise meaning, and the way they are loaded specifies the manner in which they must be chained to produce numbers that are valid instructions.

You should think of the bits as switches, or the user interface of the CPU itself. Quite similar to a church organ, where you have levers that determine which sets of pipes get the air pressure applied through playing notes on the keyboard.

As to the relation of assembler text and actual machine code:

each text representation of an instruction usually has one single way to be encoded.

each encoded instruction can have an arbitrary number of ways to write it textually, such as for JNE and JNZ, which both check the Zero flag and jump if it's not set (and produce the same encoded instruction), but represent different reasons to do it (previous operation result != 0 vs. previous comparison non-equal) as a way to simplify understanding the source code for humans.

There may be valid machine instructions that have no text representation at all.

If you want to fully understand instruction encoding for any given platform, there's no way around the instruction reference.

Body:
Paul Glover correctly explained the working of those system call values as being addresses that contain jump instructions to the actual OS routines.

That is to say, the CPU/GPU do NOT know where to put your pixels, but the OS routines, or drivers, do. You pass them arguments (x, y, r, g, b), and the OS routines put the r,g,b values to the byte positions correct for the buffer in use. If eg. you have a 10x10 pixel screen, its buffer is an array of 10x10x3 = 300 color intensities.

If each of them is a byte, setting pixel (3,5) to yellow might mean setting buffer[3*(3*10+5)] to 0xFF (fully red), buffer[3*(3*10+5)+1] to 0xFF (fully green), and buffer[3*(3*10+5)+2] to 0x00 (not at all blue). The screen itself (ie. it's controller) reads the values from the buffer and sets the individual color dots to the specified intensities.

If there is a GPU, the process may be different in that the OS routines put 'blueprints' into memory, tell the GPU to display them (passing the address, or placing them at a fixed address for that purpose), upon which the GPU calculates the pixels and places them in the buffer.

buffer[n] is just a shortcut for memory[buffer_start + n], where memory may be on the same bus as the RAM, or it may be on a designated I/O bus.

The asm instructions themselves are also numbers, and their 'arguments' or 'operands' are numbers too.

When trying to understand how these machine-level (as opposed to OS level) mechanisms work, some analogy to the physical world might help.

Suppose you have a car. There are three pedals, a lever for selecting a gear, and a steering wheel. Suppose that pedals can only be up or down, there are a maximum of 7 gears, and 4 states of the steering wheel. That setup would give you an 8-bit car ;)

Now the engineer who builds that car gets to decide about how to wire it. My proposal would be:

    Wheel                 Pedals                Gears
0 0  locked         0 0 0  roll (nop)       0 0 0  no gear
1 1  straight       1 0 0  change gear      1 1 1  7 = reverse
1 0  left           0 1 0  brake            0 0 1  1.
0 1  right          0 0 1  accelerate       0 1 0 ... 1 1 0   2., ..., 6.

So, 'accelerate while turning left in 2nd gear' would have an assembled opcode of

1 0  0 0 1  0 1 0 == 0x8A
ie. (wheel << 6) | (pedals << 3) | (gears) = encoded instruction.

Any opcodes having more than one pedal bit set would be invalid, except for the combination of 'change gear' and 'brake'.

Or maybe, the gear is only an operand when actually changing gears, and the opcode for simply 'accelerate while turning left in current gear' is 0x88. Or maybe, the engineer is not me (I'm not), the bits are placed differently, and diffferent opcodes result.

The point is, the engineer decides, and once it's built, the bits are 'wired' to have precise meaning, and the way they are loaded specifies the manner in which they must be chained to produce numbers that are valid instructions.

You should think of the bits as switches, or the user interface of the CPU itself. Quite similar to a church organ, where you have levers that determine which sets of pipes get the air pressure applied through playing notes on the keyboard.

As to the relation of assembler text and actual machine code:

each text representation of an instruction usually has one single way to be encoded.

each encoded instruction can have an arbitrary number of ways to write it textually, such as for JNE and JNZ, which both check the Zero flag and jump if it's not set (and produce the same encoded instruction), but represent different reasons to do it (previous operation result != 0 vs. previous comparison non-equal) as a way to simplify understanding the source code for humans.

There may be valid machine instructions that have no text representation at all.

If you want to fully understand instruction encoding for any given platform, there's no way around the instruction reference.


答:
Too bad that Delphi 7 is able to produce 32-bit binaries only. That leaves a good part of the 24 GB unused.

Options:

RAM disk (as Jadee proposed).

Dedicated caching system, like Memcached or, more recommendable, Redis

Have more than one instance of your program running and "shard" the data between them

AWE could be an option on a 64 bit OS

Comments:

Both RAM disk and external caches can be easily used by other processes. Altough it does not affect the solution to the problem, this may be an important benefit to have.

For Memcached and Redis and other systems, there are working Delphi adapters available for the Memcached protocol and STOMP as OSS. I personaly would prefer Redis, as it is available as pre-built package for Windows. Building Memcached on Windows is a real PITA, Redis is up and running within minutes.

AWE requires a non-standard privilege, and the allocated physical(!) memory is reserved to the calling process. Thus, I would consider that option at last.

Using sharding over multiple instances requires some clear partitioning logic. If you can't do that, you need a coordinator which will have an performance impact, so in that case it would be better to use the caching system approach instead.

Title: Delphi 7 using RAM for database

Body:
I have an existing database app written in D7 with apollo databases.

The client has given me a fast desktop with 24gb ram

Can I somehow load the database files into ram to speed up processing?

With millions of records some procedures take 1/2 hour or more, mostly due to disk read/write


问:
DDD / Optimizing a specific service belonging to a specific bounded context regarding hardware
Well known is the split of a whole application into several bounded contexts to emerge an Ubiquitous language. while practicing Domain-Driven Design.

In general, 1 bounded context = 1 archive file ready to be deployed (JAR / EAR / DLL etc..)

My question concerns the bounded contexts deployment regarding hardware optimization:

Suppose I want to optimize one specific service within a specific bounded context (optimization could be a more powerful CPU, more RAM, etc..), is it a good practice to create a specific archive file just for it? Meaning to split further the initial bounded context.
Thus, in order to deliver it on a specific hardware tunes for its usage.

Or should I consider 1 bounded context as being an indivisible unit and therefore optimizing the bounded context as a whole even if some specific services doesn't need this increase of hardware power?

答:
I consider software implementation (i.e. the writing of the code) to be a somewhat different thing than the conceptual design.  The conceptual design is there to see how all of the software components work together.  But a good conceptual design will always allow the underlying implementation to be altered to meet the software's performance and reliability requirements, and you don't necessarily have to reflect those implementation details in the top-level design.

When you design a car, you know that it's going to have a chassis, wheels and an engine.  That's part of the top-level design.  The wheels are going to be round, and they're probably going to be made of vulcanized rubber.  But the speed and mileage ratings of the tires are implementation details, and so are the engine specifications.

In short, the overall design should not change based on a hardware change or an infrastructure change.  Good top-level designs are independent of such details.


问:
At ping, why do we have to do array copying instead of passing on the source array that the client sent to us?
So I have been googling about this OpenSSL heart-bleed thing and somehow sees that it is caused by the heartbeat extension which requires client to ping the server to show its aliveness and it all comes to this memcpy function in C which is meant to copy from the source array to the destination array with the user specified size.

If the size was a lie (which means the source contains lesser byte than the size claims) then memcpy will grab the arbitrary memory around and allocated to the destination and in this case send back to the client…

Reference: Anatomy of OpenSSL's Heartbleed: Just four bytes trigger horror bug

payload is controlled by the attacker, and it's quite large at 64KB. If the actual HeartbeatMessage sent by the attacker only has a payload of, say, one byte, and its payload_length is a lie, then the above memcpy() will read beyond the end of the received HeartbeatMessage and start reading from the victim process's memory...

If my understanding above is correct, then I have a question here maybe naive one, why do we have to do array (char array here) copying here? Can't we just pass on the source char array that the client sent to us?

i.e. If you send me

```<code>function(char[] array)
</code>```

Then I would just need to send back that very array

```<code>send(array)
</code>```

答:
It's because of the way the network stack works in your operating system and standard libraries.  An ethernet packet is a continuous stream of bits coming out of your computer.  You can have gaps between packets, but not within them.  For a 1 Gbps connection, that means every billionth of a second you have to be ready to transmit the next bit.

In order to allow software which is not real time to meet those strict timing requirements, the network stack sets up a buffer.  Your non-real time server software fills the buffer, and the driver and hardware sends it out in real time.

Since you need different headers and other fields around the response (for example the source and destination addresses are reversed), and that information must be contiguous with the echoed payload in the transmit buffer, that necessitates a copy of the payload into the buffer.

Yes, you could avoid the copy by redesigning the network stack to use a different kind of data structure for the transmit buffer, like a list of pointers to arrays.  However, that would have its own set of complexities, security issues, and inefficiencies.

Personally, I'm surprised security sensitive apps still allow the use of a raw memcpy.  They have to do the bounds checking anyway, so why not create a safe buffer type and solve the problem once instead of continually having to watch out for these overflows via code review?


问:
How much time do you spend on design before coding?
In my experience, it is useful to spend a little while sketching plans for a project before getting into code. Such planning usually includes choosing frameworks/tools, writing requirements and expectations, and doing mockups.

I usually only do this for serious projects though, not so much for one-off or short-lived attempts.

I'd be interested to hear how much time you spend on planning/designing projects before starting to do the coding. Do you do it for every project, or just the "serious" ones?

答:
The famous Jamie Zawinski said in the book "Coders at Work" something along the lines of...
It's better to spend just enough time in order to be able to code something we can use, then go from there. Depending on the project and competition, if you spend TOO much time planning and thinking of THE best way to do something and don't have a working product in a given time frame, your competitors will be ahead of the game and it will be a huge loss.

I don't necessarily agree with it though, but you've got to give him credit for what he's accomplished.


问:
Refactor an old model of a LastUser Modification on every Object?
I have a software requirement, that needs to store the user that made the last modification to another object, for every object (assume that all objects are already mapped and into a BD).

So we have the ParamBase an object that holds the basic data for every object, this will be a super class, every other parameter in the system will Inherit this class, (Using @MappedSuperClass)

```<code>@MappedSuperclass
ParamBase {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Version
    private Long version;

    @Temporal(value = TemporalType.TIMESTAMP)
    private Date timeStampLastModification;

    @Column
    private User userOfLastModification;
    //constructors, getter setters, other stuff, etc
}
</code>```

The User object, this will represent the user, also mapped into a BD, for now is just simple Object mapped as Entity, all other Parameters will have to store this User into a field.

```<code>@Entity
User {
   //User stuff, cons, get, seters, etc
}

@Entity
Country extends ParamBase {
    //This class extends ParamBase so will have a field to hold the
    //userOfLastModification
}
</code>```

In an EJB I have business logic that will work with several operations and objects, when in this case a parameter is updated, the userSession (assigned at login) will update the userOfLastModification field.

THE PROBLEM:
All of the objects will have a relation with User, so all other Objects have a mapped field userOfLastModification_id, this creates a massive dependency of all clases to User.
To give you an idea, just picture on an Entity Relation diagram ER, all tables related to one single User Table, it's a mess!!!

THE REFACTOR!:
I think this model is wrong, I think breaks the equilibrium of software design  I don't think you need to create a relation between all the tables/object to one table (User) to accomplish this requirement, I will like some feedback or ides on how to:
1. Explain the design error, if there is one? (I always think that I can be wrong, and there's no problem with that)

Is there a better way to do this?

Thanks for your help!

答:
I like DougM's answer about how to handle in Java (a string for the user who last updated the table record). The goal here is to manage this inside your app. However, I don't think we have enough information here on the full-breadth of tracking updates in this system especially from the database perspective. Are you going to guarantee all changes to records are only going to occur in the app?

These are different requirements:

Track every change a user makes to every table record.

Track every change made to each record in the table regardless of who and how it was updated.

Only allow users (in user table) to make changes to records and track the last one.

Your requirements seem to match #3. I don't know enough about your app. That may be exactly what you need. In this case, I would enforce referential integrity between the user table and all the other tables. That way it doesn't matter if your app or some other source makes data changes, they have to reference a user account record.

The solution to #1 is to just put some sort of user name into the "UpdateUser" field. Users could get deleted from the user table, but your app won't care going forward. Lots of flexibility here. The client may or may not like that.

There are situations where #2 may be best. If you did an acquisition of Acme Company, you could import all these data and make the user = "Acme Import". There may be some nightly job that runs that brings in data from an external source, so call it "Nightly Update".

Of course performance and ease of managing the system will need to be considered. This isn't so much of an answer of exactly how you should do it, but how you should go about finding a solution and some things to consider. You may need to clarify the requirements depending on the knowledge your client has about security, logging, and data management.


问:
How much time a week do you spend on extracurricular programming?
Background: I'm a microsoft DBA/IT type person by day, an iOS and Mac developer by night. I have one app in the App Store and another one in the works. I try to spend as much time as possible working on my two apps, but with a new daughter and other (non computer) hobbies, I find it hard to spend more than a few hours every week programming.

I'm wondering how this compares to other developers. I see a lot of apps out there written by single developers who don't do iOS development as their main job. Are they spending 4 hours a night working on their projects, or do they just plug away for a year or two before releasing anything?

答:
I love hacking on code whenever I get a chance.  It gives me time to learn new languages and probably newer APIs.  My work generally involves working with PHP, but during my free time I build applications with python and enjoy doing them.

I even maintain a list of applications as soon as I get the idea for them and when I find free time I try to build them one by one.  I find that programming is probably the only way that I relax or I'm able to empty my mind of emotions.


问:
Is machine language always binary?
I know absolutely nothing in low-level stuff, so this will be a very newbie question. Please excuse my ignorance.

Is machine language - the series of numbers to that tell the physical computer exactly what to do - always binary? I.e. always composed of only zeros one ones? Or could it also be composed of numbers such as 101, 242, 4 etc.?

答:
Machine language is not an universal language but rather a strictly CPU-related language - the language the CPU understands.

You can design a CPU that has 42 states instead of 2 states for the smallest element of memory. The problem is that you cannot come with a good enough implementation for such a CPU. Actually, some of the first computers (including ENIAC) were decimal computers that implicitly used a decimal machine language.

The fact that it's decimal or binary or other value depends on the number of states the smallest element of memory (a bit) can take; 2 was not chosen for CPU design purposes but rather limited by electronic implementation: a transistor operates much better and faster with only 2 levels of voltage instead of 10 (or any other natural number larger than 2).

Title: Is machine language always binary?


问:
How to implement an algorithm out-of-core?
I want to implement a parallel clustering algorithm "out-of-core" in CUDA. My CPU has 12GB of RAM and GPU has 4GB of it.
What I want is that the entire dataset should be on the disk, and I can pick blocks of data from it, put the blocks on CPU memory, pass them to the GPU, process it there and store the result back on disk. The step complexity of the original (in-memory) algorithm is O(logN), N-> no. of data points.
For the external memory algorithm, suppose M points can fit in the memory at once, then according to me, the running should be

```<code>(N/M)*(logM)
</code>```

(N/M) -> equals the number of such sets of points that will have to be put in memory and during each pass, logM time to process it.

How does this running time relate to the I/O time between disk and memory, i.e., have I already considered the I/O time by using (N/M) or am I leaving something out? Is this analysis correct, or do I need to know more about Input/Output to implement an algorithm using external memory?

答:
The I/O time cost is going to be some number based on N, since you will ultimately read N objects from disk. So it might be included in your complexity estimate, assuming your method of "picking blocks" is constant time.

Remember, that just tells you the general order of complexity of the algorithm, and the factors that play the biggest role in that complexity for large values of N.


问:
long lines in git or svn
I am coding a program which has persistent data (the MELT monitor, related to GCC MELT). The data is persistent because it is expected to be read and overwritten by most executions. (That data is in particular made of abstract syntax trees)

Currently, this persistent data is an Sqlite database. Of course, I am backing up it in textual format, obtained by sqlite dump, and I want to manage this textual dump with a version control system (probably git, but perhaps also subversion ....).

Unless I take special precautions, these SQL dumps will probably have quite long lines (e.g. several dozens of kilobytes). Wide SQL columns would probably contain JSON text of many kilobytes.

Would git (and svn) be more happy with shorter lines (in particular would they perform slower with long lines, or have repositories using much more disk space)?

I'm probably not mostly interested in the diff commands (e.g. git diff or svn diff), because I expect that using them for such textual dump is not very interesting for the human developers.

I am coding the persistency routines, so I am able to change slightly the format (e.g. to add newlines in some JSON text, which sqlite3 dump is dumping verbatim).

If you are curious, my current code snapshot is on http://starynkevitch.net/Basile/monimelt-bgc-21apr2014.tar.bz2 and contains a state-monimelt.sql dump file (which will of course become much larger, perhaps near or above a megabyte)

答: Svn basically stores the diffs between subsequent versions, so breaking the lines as to minimize the size of the diff should minimize the amount of storage you use.  Git compresses its revisions somewhat differently, so breaking the lines may not matter as much.  Whether it's significant in practice you can only tell by measuring.  My recommendation is to try it manually both ways and see if it makes enough difference to bother automating.  Just make sure to run a git gc to get the full effect of git's compression.

Title: long lines in git or svn


问:
How to design routes for generalized/specialized resources
I hope I can explain what is troubling me.

Example: I have an object basket with a list of fruit objects. So normally I would build my routes like this baskets/{basketId}/fruits/{fruitId). But fruit is an interface and there are different implementations like apples and oranges that all require their own resource representation.

So how do I build my routes now?

Like one of those?:

baskets/{basketId}/fruits/{fruitId}/apple,

baskets/{basketId}/fruits/{fruitId)/orange and so on

baskets/{basketId}/fruits/{fruitId}/apples/{fruitId} ,
baskets/{basketId}/fruits/{fruitId}/oranges/{fruitId}

baskets/{basketId}/apples/{fruitId},

baskets/{basketId}/oranges/{fruitId}

What would be the restful way?

答:
The most RESTful way would probably be to define separate routes for each fruit type:

```<code>baskets/{basketId}/apples
baskets/{basketId}/apples/{appleId}
baskets/{basketId}/bananas
baskets/{basketId}/bananas/{fruitId}
... other fruits
</code>```

And use a different media type for each fruit, e.g.:

```<code>application/vnd.com.example.apple+json
application/vnd.com.example.banana+json
</code>```

In this case you would need to request a list of every possible type and handle them individually.

A less RESTful solution might be to treat fruit as the interface that it sounds like it is, and just get a list of them.

```<code>baskets/{basketId}/fruits
baskets/{basketId}/fruits/{fruitId}
</code>```

Since JSON is usually schema-less, each item can look completely different, and you could use some identifying characteristic to map each to the specific fruit class which understands its JSON representation and contains its behavior.

Body:
The most RESTful way would probably be to define separate routes for each fruit type:

baskets/{basketId}/apples
baskets/{basketId}/apples/{appleId}
baskets/{basketId}/bananas
baskets/{basketId}/bananas/{fruitId}
... other fruits

And use a different media type for each fruit, e.g.:

application/vnd.com.example.apple+json
application/vnd.com.example.banana+json

In this case you would need to request a list of every possible type and handle them individually.

A less RESTful solution might be to treat fruit as the interface that it sounds like it is, and just get a list of them.

baskets/{basketId}/fruits
baskets/{basketId}/fruits/{fruitId}

Since JSON is usually schema-less, each item can look completely different, and you could use some identifying characteristic to map each to the specific fruit class which understands its JSON representation and contains its behavior.


问:
What do these cocoonJS terms of use mean
I was looking at the terms of use for CocoonJS and noticed this section

License Grant. By uploading User Content via the Services, you expressly grant, and you represent and warrant that you have a right to grant, and do so grant, to Ludei, a royalty-free, non-exclusive, worldwide license to use, reproduce, modify, publish, list information regarding, edit, translate, and make derivative works of all such User Content and your name, voice, and/or likeness as contained in your User Content, if applicable, in whole or in part, and in any form, media or technology, whether now known or hereafter developed, solely for use in connection with the Services.

I am not too clear on the legal jargon, but to me this sounds like I'm basically giving someone unrestricted access to any intellectual property that I have submitted to their servers, and the ability to use my identity in any form as they wish.

Can someone clarify what the excerpt means?

答:
With much of the cloud and hosting services for various things (photographs, code, t-shirt designs, blogs), it is necessary to do things with that data to be able to do what you want the service to do.

Take for example an image that you've uploaded as a png for the icon for the page.   That license allows them to convert it to a jpeg. Or if they need to make a thumbnail for the gallery, that is a transformation of the image. If you upload the instructions for a game in English, they have the ability to translate them into French.  If you upload the associated files one at a time, they have the license to repackage them into a single deployable.  And in all cases, they have the permission to host the information that you've put up there to be hosted.

Without this license, they would not be able to legally host any files, resize the images, package up things into the proper executable format, and be on the hook for royalties.

This license is largely a very standard "if you upload something for other people to download (play online or whatnot) we have permission to host it without being charged a royalty and make associated tweaks necessary for hosting it on our site."


问:
Is it appropriate to use inheritance to prevent code duplication of the logic for a user control?
Suppose I have two or more UserControl implementations with vastly different implementations but near identical code-behind.  One strategy to avoid code duplication is as follows:

Change each UserControl to inherit from a new abstract class, AwesomeUserControl

Move all of the codebehind from each UserControl into AwesomeUserControl (AwesomeUserControl does not have an ascx file).

Add abstract getters to AwesomeUserControl for any controls from the ascx file of the original UserControls.

Implement these getters in each UserControl.

This strategy works extremely well and is easy to maintain.  However, it also introduces stupid scaffolding code; every new implementation of AwesomeUserControl has a bunch of getters to hook AwesomeUserControl the UI elements inside of the new control.  Any time I find myself using a strategy which requires copy-pasted scaffolding code, I worry that I am doing something wrong.  Though it does have a nice effect of failing to compile if the UI elements are missing (as opposed to skipping the scaffolding code in favor of reflection and required naming).

Is this use of inheritance reasonable?

答:
Vastly different implementations? Sounds like a bad candidate for a common abstract parent class, don't you think?

Otherwise, you have to be more precise than AwesomeUserControl. What are the exact controls which share the same logic? What logic is shared?

As an illustration, here's a copy-paste from an answer I wrote a few days ago:

Either two classes are related (for example both Cat and Dog can be fed, and it takes the same steps to feed them both, except the food which will change), in which case, create an inheritance (in my example, a parent class Pet),

Or two classes are unrelated, and just rely on the same method. For example, WebRequest class may rely on GetSlug¹ to find the slug of the current request; Customer may also rely on GetSlug to normalize the name of the customer for further search purposes. However, WebRequest and Customer are totally unrelated, and it makes no sense to create a common object for those classes.

Here, the solution would be to call a common method from those two classes, by instantiating the third class containing this method. For example, both RequestUri and CustomerName may become objects implementing ISlug interface.


答:
I would have to say that it depends vastly on the two classes.

If you have two classes that share many of the same methods AND share many of the same properties and fields then I would create a parent class. Inheritance is probably your best solution here.

An interface is nice, but I don't think it will help you with what you want, which I believe you are looking for code reduction.

I do not agree with the ISlug Interface example from MainMa, but again, that depends on the implementation of the objects. Interfaces are great, but you don't have to make one just because two classes share the same method names and parameters.

If you post a little bit more about what your two buttons do, and maybe just the functions and fields/properties they share, It would be a little more enlightening to the situation.

Title: Is it appropriate to use inheritance to prevent code duplication of the logic for a user control?

Body:
Suppose I have two or more UserControl implementations with vastly different implementations but near identical code-behind.  One strategy to avoid code duplication is as follows:

Change each UserControl to inherit from a new abstract class, AwesomeUserControl

Move all of the codebehind from each UserControl into AwesomeUserControl (AwesomeUserControl does not have an ascx file).

Add abstract getters to AwesomeUserControl for any controls from the ascx file of the original UserControls.

Implement these getters in each UserControl.

This strategy works extremely well and is easy to maintain.  However, it also introduces stupid scaffolding code; every new implementation of AwesomeUserControl has a bunch of getters to hook AwesomeUserControl the UI elements inside of the new control.  Any time I find myself using a strategy which requires copy-pasted scaffolding code, I worry that I am doing something wrong.  Though it does have a nice effect of failing to compile if the UI elements are missing (as opposed to skipping the scaffolding code in favor of reflection and required naming).

Is this use of inheritance reasonable?


问:
Cascading deletes from an aggregate root through out the entire aggregate doesn't make sense
Based on the same example for this question.

Within the Pro ASP.Net MVC 4 by Adam Freeman, there is a discussion on aggregates and aggregate roots with a simple auction system.  There are members who bid, items that are bidded upon, and bids.  The author says that there would be an aggregate of Item and Bid with Item being the aggregate root.  The author then mentions that aggregates roots can be used to do a cascading delete, which for this example means that if an item is deleted, all bids on the items are deleted.  This makes sense.  The problem is, bids only belong to the item/bid aggregate, and not to a member/bid aggregate.  If I delete a member of the system who places bids, it would seem reasonable that all their bids are deleted as well.  Yet, I can't do that without 'break' the aggregate.  I also can't simply get a members list of bids.

My level of confusion, given how simple the example is, makes me a bit worried.

Is this just a bad example, could member/bid be a valid aggregate instead and there is some level of arbitrariness in making the choice of your aggregates that is acceptable as long as you make a choice, is there some way to have models belong to multiple aggregates, or am I just missing something?

P.S.  The answer in the question I linked says that domain driven development is just very tricky, but it doesn't go into enough details as to how it is tricky and why the trickiness induces confusion and as such my questions about it still remains.

答:
Two bounded contexts can refer to the same object. But only one controls the lifespan of the object.

The bid belongs directly to the Auction BC. A book that I recommend to many people is Java Modeling in Color with UML it provides a great set of tools to help with domain modeling.

Color-based modeling categorizes domain objects into four archetypes: Person/Place/Thing, Role, Descriptor, and Moment/Interval.

I've gone back and forth about mapping the concepts in the book with DDD concepts. Specifically thinking about a heuristic for determining BCs and Aggregate Roots based on Archetypes.

What I do know is that Membership and Auctions are two separate BCs (in your example). The process of Managing membership has nothing to do with managing auctions (aside from the fact that members create/bid on auctions. Other than that, they're two separate systems

An Auction is an example of a Moment-Interval archetype, it happens over a given period of time (hence it's an Interval). Off of the Auction are several roles: the Auctioneer, the ItemForAuction, and possibly the WinningBidder. These roles are assigned to Person/Place/Thing archetypes.

For example there is a single Party in the system that represents me Mike Brown. Within the system, the Mike Brown entity might have several roles associated with it. One role would be Member (from the Membership BC) another might be Auctioneer (if I decided to put an item for auction) another might be Bidder (if I bid on an auction). The important thing is that no matter which role I play in the system, the data and functionality associated with that role is isolated to it. Think of roles as decorators, or hats that people wear depending on what they're doing.

If I have a hold of the Mike Brown entity. I can ask the entity "What roles do you have" or "Do you have the X role" and the entity should be able to answer. So I can say, Mike Brown give me your Auctioneer role. From the auctioneer role I should have operations like CreateAuction, CancelAuction, ListActiveAuctions, ListCompletedAuctions. In other words the Role is the engine of the system.

Remember I said that the Auction is an example of the Moment-Interval archetype. These represent significant events or periods within your domain. Another concept associated with a Moment-Interval is what's called Successors. For example a Bid is a Successor to an Auction. A bid only exist within the realm of a specific auction (i.e. a Bid is part of the Auction's Aggregate).

If the User or Member who created a bid is removed from the system, that does not negate the fact that a Bid was placed. (No more than Divorcing your wife negates that you had children together, the wife is no longer part of your Family aggregate, but the children very much are...let's ignore the fact that now the children belong to two Family aggregates).

What I am leaning toward as a hypothesis is that For every Moment-Interval, there is a primary Actor that would be the Role archetype. For instance, an Auctioneer is the primary Actor for the Auction M-I. He creates it. The other actors participate in it. I'm leaning toward saying the primary actor for an M-I would be the Aggregate root, except that a single Role entity can participate in multiple M-I.

So the Primary-Actor is a FACTORY for an M-I and controls the lifetime but the M-I itself would be the candidate for an Aggregate root. In this case Auction is an Aggregate root. And it's successors, roles, descriptors, and PPT, are part of its aggregate.

Membership as part of a separate bounded context shouldn't really have direct access to bids, or auctions. Deleting a member for me is actually terminating the Membership M-I (setting an end date on the membership). And any other logic involved in ensuring that the user does not have access. The member still exists, but is inactive. His historical bids are still there. Everyone is happy.


问:
How can I promote software reuse in a large company?
Take a large company, formed through many iterations of mergers and reorganizations. This company produces lots of different products that are all targeted to a specific industry. Most products share similar characteristics, such as communication standards and certification and safety requirements. But there is no unified development platform or model for the company. Each product has its own distinct hardware, and software is created in any number of languages. Most new products will be updates to older versions or target the same industry. What strategies would you use to promote software reuse?</p>

答:
Given your constraints, I'm not sure software reuse is even a good idea.  The teams for your individual products are already intimately familiar with the particular tools and platforms for each specific product, so reinventing them to promote code reuse may be a waste of time and money.

Any reworking of this kind would most certainly involve corporate strategy.  You would have to make a compelling case that the restructuring would save time and resources, improve efficiencies, and make the company more profitable.

A simpler approach: If you come out with any new products, you could try reusing pieces of your most successful platform.


问:
Linking against LGPL - How to share the code?
I'm working on an Open Source software project (LGPL) which uses another LGPL-licensed software. To make it easier for users and developers I'm delivering and linking against the compiled thirdparty.

As far as I know I have to include the sources and license-statements of LGPL software if I'm delivering and using it in binary form.

However this would mean that I have to put the compiled version as well as the code of that thirdparty into my repository. Not only would that make the checkout take ages, it would also be somewhat redundant.

Are there any techniques or best practices on how to solve this issue? My project is available on Github  if that matters.

Update:

Link to Project

Link to Thirdparty

答:
LGPL say that you have to make it available, not that you must pass it along with every binary.

just give a contact email for the source and auto reply with a link where you got the library from originally if you didn't modify it or a link to a zip in a dropbox with the modifications.


问:
What is a web API? (Application Programming Interface)
What is a web Application Programming Interface?

Many common sites provide APIs. Why are they needed, and what function do they provide?

How does one access a web API?

答:
Imagine you want to write a program that counted the number of friends you have on facebook whose names start with the letter B.

When you, as a person, interact with facebook, you go to "facebook.com" in your web browser and click on links and pictures. To perform this friend-counting task, you might go to your "friends" page, navigate to the "B" section, and then count the number of names you see.

But how do you make your program do the same thing? Technically, there are ways to make your own computer code "click" on things, or "navigate" accross different pages, but this is a large amount of work for what would ideally be a pretty simple problem.

An API is almost like a website designed specifically for interaction by programs, not humans. To see your list of friends as a human, on a pretty web page, you click the link which takes you to www.facebook.com/Chris/friends. Facebook sends you back that webpage. But if you were to visit (fake example URL) www.facebook.com/API/Chris/friends, you get back a much different result. Instead of a webpage with images, links, chat boxes, and lots of other display- and interaction-related extras, you get back a very plain, but very well-structured, block of text. Something like this:

```<code>[
    {
        "name": "Adam Smith",
        "id": "176399948"
    },
    {
        "name": "Bill Gates",
        "id": "8462993451"
    }
]
</code>```

This text describes the friend list in a manner that is easily understood and internalized by a program. It's a special notation for storing data (this one is called JSON, but there are many others), and most programming languages have functions to convert it into variables accessible from your program.

So in your program, to print a single friend's name you might say:

```<code>api_result = get_webpage("www.facebook.com/API/Chris/friends")
friend_list = convert_json_to_data(api_result)

first_friend = friend_list[0]

print("One of my friends is named ", first_friend{'name'})
</code>```

As you can see with friend_list[0], the content of the webpage is now a real array (or list, or whatever) of data, accessible and traversable through our programming environment.

So, in summary, and "Application Programming Interface" is... an interface allowing you to access an application (like facebook, microsoft word, etc.) using a programming language. A more clear name might be "Programming Langauge Interface to an Application". "API" refers to that whole other "site" designed for programs to access.

A few extra notes (sorry)

APIs often don't just let you see data, but alter it as well. The process is very slightly different usually, but it basically comes down to visiting a different address, like this one (to add a freind for Chris): www.facebook.com/API/Chris/add_friend?new_friend_id=34564573, or alternately, the same URL using a different method (like an HTTP POST to www.facebook.com/API/Chris/friends instead of a GET)

Technically that description I gave you only describes so-called "web APIs", which are APIs available on the internet through different URLs, and which usually correspond to websites. But the general idea applies to any API. It's just a well-structured and predictable way to interact with someone else's computer program using your own computer program. API is a really general term. In fact, it isn't even limit to refering to interaction with a stand-alone "application", but really just... any programming interface. So the "print" function above is part of an "API" which allows writing of text to some screen or file.

Body:
Imagine you want to write a program that counted the number of friends you have on facebook whose names start with the letter B.

When you, as a person, interact with facebook, you go to "facebook.com" in your web browser and click on links and pictures. To perform this friend-counting task, you might go to your "friends" page, navigate to the "B" section, and then count the number of names you see.

But how do you make your program do the same thing? Technically, there are ways to make your own computer code "click" on things, or "navigate" accross different pages, but this is a large amount of work for what would ideally be a pretty simple problem.

An API is almost like a website designed specifically for interaction by programs, not humans. To see your list of friends as a human, on a pretty web page, you click the link which takes you to www.facebook.com/Chris/friends. Facebook sends you back that webpage. But if you were to visit (fake example URL) www.facebook.com/API/Chris/friends, you get back a much different result. Instead of a webpage with images, links, chat boxes, and lots of other display- and interaction-related extras, you get back a very plain, but very well-structured, block of text. Something like this:

[
    {
        "name": "Adam Smith",
        "id": "176399948"
    },
    {
        "name": "Bill Gates",
        "id": "8462993451"
    }
]

This text describes the friend list in a manner that is easily understood and internalized by a program. It's a special notation for storing data (this one is called JSON, but there are many others), and most programming languages have functions to convert it into variables accessible from your program.

So in your program, to print a single friend's name you might say:

api_result = get_webpage("www.facebook.com/API/Chris/friends")
friend_list = convert_json_to_data(api_result)

first_friend = friend_list[0]

print("One of my friends is named ", first_friend{'name'})

As you can see with friend_list[0], the content of the webpage is now a real array (or list, or whatever) of data, accessible and traversable through our programming environment.

So, in summary, and "Application Programming Interface" is... an interface allowing you to access an application (like facebook, microsoft word, etc.) using a programming language. A more clear name might be "Programming Langauge Interface to an Application". "API" refers to that whole other "site" designed for programs to access.

A few extra notes (sorry)

APIs often don't just let you see data, but alter it as well. The process is very slightly different usually, but it basically comes down to visiting a different address, like this one (to add a freind for Chris): www.facebook.com/API/Chris/add_friend?new_friend_id=34564573, or alternately, the same URL using a different method (like an HTTP POST to www.facebook.com/API/Chris/friends instead of a GET)

Technically that description I gave you only describes so-called "web APIs", which are APIs available on the internet through different URLs, and which usually correspond to websites. But the general idea applies to any API. It's just a well-structured and predictable way to interact with someone else's computer program using your own computer program. API is a really general term. In fact, it isn't even limit to refering to interaction with a stand-alone "application", but really just... any programming interface. So the "print" function above is part of an "API" which allows writing of text to some screen or file.


问:
Using multiple Git repositories instead of a single one containing many apps from different teams?
I am migrating a 10-years-old big CVS repository to Git. It seemed obvious to split this multiple-projects repository into several Git ones. But the decision-makers are used to CVS, therefore their point of view is influenced by CVS philosophy.

To convince them to migrate from one CVS repo to different Git repositories I need to give them some arguments.

When I speak with mates working on Git repo for years, they say that using multiple Git repo is the way to use Git. I do not know really why (they give me some ideas). I am a newbie in this field so I ask here my question.

What are the arguments to use multiple Git repositories instead of a single one containing different applications and libraries from different teams?

I have already listed:

branches/tags impact the whole Git repository files => pollutes other team projects

4GB limit Git repo size but this is wrong

git annotate may be slower on bloat Git repo...

Eamon Nerbonne has noticed the related question:

Choosing between Single or multiple projects in a git repository?

The reason the team managers finally have accepted the split: the single Git repo (550 MB) was requiring 13 minutes to be cloned on Windows (one minute on Linux).

The bloat CVS repo split in 100 Git repositories:

each dead apps in one repo

each stabilized library in one repo (source code almost never changed any longer)

related apps/libs kept together in one repo

moved large files not used for compilation (config...) to other repos (Git does not like large files)

skipped other unrelevant files (*.jar, *.pcb, *.dll, *.so, *.backup ...)

Successfully installed the repo tool used by Android Open Source Project in order to handle all these Git repos:

easy installation on Linux

more difficult on Windows because of Cygwin and NTFS native symlinks requirements

答:
There doesn't seem to be an argument in favor of the big repo in this thread, so here's one:

The advantage of a big repo with all your code in it, is that you have a reliable source of truth. All the state in your overarching project is represented in that repo's history. You don't have to worry about questions like "What version of libA do I need to build libB from 3 months ago?" or "Did the integration tests start failing because of Susan's change in libC or Bob's change in libD?" or "Are there any callers left for evilMethod()?" It's all in the history.

When related projects are split into separate repos, git isn't keeping track of their relationships for you. Your build system needs to know where to find the code for all its dependencies, and more importantly what version of the code to build. You can "just build everything from master", but that makes it hard to reproduce past builds, hard to make changes (or rollbacks) that need to be synced across repos, and hard to keep branches in a stable state.

So the question isn't "One big repo or many small repos?" It's actually "One big repo or many small repos with tooling." What tool are you going to use? Repo (Android) and gclient (Chromium) from Google are two examples. Git submodules is another. All of those have major downsides that you have to weigh against the downsides of a big repo.

Edit: Here are some more answers Choosing between Single or multiple projects in a git repository?

PS: All that said, I'm working on a tool to hopefully make things better, for when you have to split repos or use other people's code: https://github.com/buildinspace/peru


答:
I think you need to consider a large company to be for all practical purposes a wild software ecosystem; maybe not so heterogeneous as the entire world but still you'll have to expect that tool and software practices are pretty well diffused.

So the question of how to promote code re-use in the company is not different from promoting it with the world. I am advocating, an essentially open source approach to development of commonly useful components. Let us know if you ever get it to work.

Title: How can I promote software reuse in a large company?

Body: Take a large company, formed through many iterations of mergers and reorganizations. This company produces lots of different products that are all targeted to a specific industry. Most products share similar characteristics, such as communication standards and certification and safety requirements. But there is no unified development platform or model for the company. Each product has its own distinct hardware, and software is created in any number of languages. Most new products will be updates to older versions or target the same industry. What strategies would you use to promote software reuse?</p>