答:
There is no error in your line of thought, you've just described something very close to how the original Java garbage collector worked

The original Java virtual machine [6] and some Smalltalk virtual machines use indirect pointers, called handles in [6],to refer to objects. Handles allow easy relocation of objects during garbage collection since, with handles, there isonly one direct pointer to each object: the one in its handle. All other references to the object indirect through the han-dle. In such handle-based memory systems, while object addresses change over the lifetime of objects and therefore cannot be used for hashing, handle addresses remain constant.

Space and Time-Efficient Hashing of Garbage-Collected Objects

In Sun’s current implementation of the Java Virtual Machine, a reference to
  a class instance is a pointer to a handle that is itself a pair of pointers: one to a table
  containing the methods of the object and a pointer to the Class object that represents
  the type of the object, and the other to the memory allocated from the Java
  heap for the object data.

The Java Virtual Machine Specification (1997)

So it does work, it has been tried, and its inefficiency led to the development of generational mark and sweep systems.


问:
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?)

答:
A question we have pondered frequently.

Look at how similar situations are handled elsewhere in your API. Consistency is a very high priority and if there are established principles, stick to them.

The language matters. It is hard/impossible to return values in parameters in some languages (Java).

Consider using a struct or collection instead of a raw pointer. The byte array in Java carries its length with it.

I/O parameters are horrible to code with. Avoid them!

A return value should not be both a success indicator and a length, but if you break any rules this one is the least serious.

Overall my preference in C/C++ generally is to return bool success/failure, and provide a secondary function (GetLastError()) to get the real error code.

In the case of Read (only) my preference is to return the length read as return value of function, with a special value for error (-1). Not the nicest, but convenient.

If the data you are reading is known to be Ascii, then return a null-terminated string to give the length, and bool true/false for the function return.

[Regrettably this is all a matter of opinion, which makes this a question at risk of being closed.]

ContentLicense: CC BY-SA 3.0


问:
Categorize tasks/bugs by risk of changes
The project I'm currently working on has an issue: bugs and tasks are often assigned to people who are too new or too inexperienced and their work ends up producing more bugs down the road. The problem is that parts of our software are much more "dangerous" to work on than others due to code quality issues. I've been trying to combat this issue by estimating the risk associated with tasks and paying close attention to which developers get assigned which tasks.

We use JIRA so I started labeling issues to keep track of this estimation. I've noticed that I've ended up using several metrics to categorize a bug/task:

How clear/straightforward it is. E.g. whether it's something that will need a lot of design work or just a simple UI bug fix.

How maintainable the affected area of the code is. Is it a well-designed area or a big ball of mud.

How much of the program I think will be affected by the required change.

My labels are kind of messy since I didn't have a clear idea when I started what the possible categories would be and I still don't. I'm thinking about requesting a new field be added (something like "Risk") so that we can require an estimate before assigning the work to someone.

Has anyone dealt with this sort of thing before?

答:
Yes, it is a good idea not to give inexperienced developers problems that are too complex.  But the flipside is that if you only let them do the easy stuff then they won't learn.

I suggest an alternative strategy is to institute a regime of code reviews.  Let the newbies work on work on the tricky stuff (within reason), but thoroughly review their work.

In the short term, this is more work for everyone.  In the longer term, you will end up with a whole team of developers who can handle the complex stuff, AND are "on the same page" as far as code quality is concerned.


问:
Typical instantiation of new object - is there a way to avoid repetitious syntax?
When learning C# (and OO concepts more generally at the same time) something I found very distracting is exemplified by the following line:

```<code>ExampleClass exampleObject = new ExampleClass();
</code>```

It's the apparent redundant repetition that bothered me. Some light dawned when I grasped the difference between declaring a variable and assigning it a value or reference (and that these processes can be separate). However, the above usage is extremely common.

Obviously, I've learnt to live with it (and am not expecting the C# syntax to change!) but I wondered if there is a better way. Would there be any merit in the following:

```<code>exampleObject = new ExampleClass();
</code>```

Where the variable exampleObject is strongly typed as ExampleClass when it is not specified?

EDIT

[after commenters pointed out ambiguity of above between a declaration of a new, and an assignment, of an existing, variable:]

An alternative hypothetical shortened syntax, which avoids the declaration/assignment ambiguity, is:

```<code>ExampleClass exampleObject = new();
</code>```

...where this would create a new instance of ExampleClass, the type having been specified in the declaration of its referencing variable, exampleObject.

.. but I'm sure this opens up other problems I haven't thought of!

/EDIT

Obviously, if for some reason we wanted exampleObjectto be of type Object, or - a more common requirement - to be of the type of a parent class of ExampleClass, we would specify these types in front of the variable name in the standard way, but is there any drawback to my suggested shorthand in this very common scenario?

答:
C# requires you to explicitly declare a variable, in addition to assigning it a value. This is done so that its clearer to both the compiler and the person reading the code that we're defining a new variable here, not using a previously-defined one, which can simplify parsing and make the code much clearer.

As you said, the statement ExampleClass c = new ExampleClass() is simply a contraction of both these actions, which is why you feel the duplication - it's two different actions. But it does feel clunky. This is why the C# 3.0 specifications (in VS2008) added the var keyword, which lets you skip a lot of the verbosity, even if it wasn't the primary motivation for the feature.

Using var, our example code becomes var c = new ExampleClass() - much easier to scan, but still explicitly declaring as well as assigning. It gets even more useful with long class names - var complexDictionary = new Dictionary<Tuple<int,int>, List<string>>(), for instance. Imagine writing that twice!

Of course, var was originally introduced to support anonymous types. These are used by lambda expressions and LINQ, and create types with names that are both clumsy (MyMethod<>Class5, or similar) and also not known to the developer, so that saves us a lot of problems.

Additionally, in your edit, you proposed a similar but inverse solution to the duplication - to keep the declaration explicit, but the instantiation implicit. This saves about as many characters as var, but is a lot less flexible. Consider that variable declaration is very simple - you simply state the type of your variable. Initialization, though, is more complex. Sometimes you simply use new, and then we can use your new() syntax. But often we have different constructor parameters. Or how about initializing using a factory method, like ExampleClass exampleObject = ExampleBuilder.CreateExample();? Your syntax doesn't save us anything there, whereas the type inference in var will allow us to use var exampleObject = ExampleBuilder.CreateExample(); smoothly.


答:
Yes, it bothers other people.  It's a major motivation for people choosing dynamically typed languages.  What you're talking about in the context of a statically typed language is called type inference, which basically means the compiler can tell what type a variable is by what type it is initialized to.  It has been a full feature in languages like Scala and Haskell from the start, because of the crazy long types that come up regularly in those languages.  C# supports it in a more limited form with var, and C++11 with auto.

However, note that in languages with type inference, it's still recommended to explicitly specify types on public interfaces to your code.  It prevents you from accidentally changing the public interface, say if something is implemented in terms of a concrete type, but you want its public interface to be a more abstract type.  It also makes it easier for consumers of your code to determine how to use it.

Title: Typical instantiation of new object - is there a way to avoid repetitious syntax?

Body:
When learning C# (and OO concepts more generally at the same time) something I found very distracting is exemplified by the following line:

```<code>ExampleClass exampleObject = new ExampleClass();
</code>```

It's the apparent redundant repetition that bothered me. Some light dawned when I grasped the difference between declaring a variable and assigning it a value or reference (and that these processes can be separate). However, the above usage is extremely common.

Obviously, I've learnt to live with it (and am not expecting the C# syntax to change!) but I wondered if there is a better way. Would there be any merit in the following:

```<code>exampleObject = new ExampleClass();
</code>```

Where the variable exampleObject is strongly typed as ExampleClass when it is not specified?

EDIT

[after commenters pointed out ambiguity of above between a declaration of a new, and an assignment, of an existing, variable:]

An alternative hypothetical shortened syntax, which avoids the declaration/assignment ambiguity, is:

```<code>ExampleClass exampleObject = new();
</code>```

...where this would create a new instance of ExampleClass, the type having been specified in the declaration of its referencing variable, exampleObject.

.. but I'm sure this opens up other problems I haven't thought of!

/EDIT

Obviously, if for some reason we wanted exampleObjectto be of type Object, or - a more common requirement - to be of the type of a parent class of ExampleClass, we would specify these types in front of the variable name in the standard way, but is there any drawback to my suggested shorthand in this very common scenario?


问:
Can the DDD repository modify entity in the DB without an entity object?
Say I have an aggregate root Entity with some flags which are represented by an encapsulated object EntityFlags:

```<code>class Entity
{
    /** @var EntityFlags */
    private $flags;
    ...
}
</code>```

I have a repository for this entity.

My goal is to modify flags in the DB. There are two ways I see:

Get entity from the repository, modify flags like $entity->getFlags()->set($name, true) and save it: $repository->save($entity).

Create an additional method in the repository, e.g. modifyFlags(EntityId $id, EntityFlags $flags)

I think the first way is redundant. But it also seems wrong to use repository for partial entity updates like in the 2nd way. Which way is the correct one? Maybe I missed something?

答:
You're placing too much responsibility into the Repository here, drifting away from the original pattern. A Repository is just supposed to be a conceptual set of domain objects, a collection you can query from or add to without minding about the underlying persistent storage.

modifyFlags(EntityId $id, EntityFlags $flags) could typically be the signature of a use case, i.e. a method in one of your Application layer Services, but not a Repository method. A repo isn't supposed to contain object modification logic.

save($entity) may also not fit very well into the repo, because knowing how to flush things to the database is a separate responsibility in itself. The Unit of Work API in most object relational mapping tools typically allows you to do that. It doesn't make much sense to have a Save(object) method on an array or a collection type - likewise on a Repository.


答:
No, the repetitious syntax shouldn't bother anyone.  It's kind of like complaining about the the three statements within a for loop.

```<code>for(int x = 0; x <= 100; x++) {
   /* do work */
}
</code>```

Sure, you could use syntactic sugar for mocking this common pattern as below, but you don't gain a lot by any sensible alternative and, like any usage of sugar, you lose some things that are important.

```<code>for(x = 0 to 100) {
   /* do work */
}
</code>```

While this is useful for the simple iteration, it's shortcomings become clear after a bit of thought:

It's not possible in the shorthand for x to be anything but a locally declared variable.

You can't have a more complex test, such as "skip prime numbers"

You can't implicitly step by more than 1, or increment some external modifier.

Most of these can be overcome, but the syntax doesn't really help beyond some typing.

It's probably worth nothing that your one-line examples actually distort how things really should be done in C#.  If we're initializing a member of a class, you really do want to do something like the following:

```<code>class Test : ITest {
    public IExample example;
    public Test() {
      example = new Example();
    }
}
</code>```

The type of your member is declared by way of an interface, so you can change the concrete class latter without a major code re-write.

The actual initialization is in a constructor, which can be adjusted or over-ridden in a deriving class.

Words like "Object" and "Class" are skipped entirely.  Names are for people, and the java-like capitalization syntax does enough for our purposes.

Conversely, if you're only initalizing a local instance, you would do one of the following:

```<code>IExample example = new Example();
</code>```

or

```<code>var example = new Example();
</code>```

Body:
No, the repetitious syntax shouldn't bother anyone.  It's kind of like complaining about the the three statements within a for loop.

for(int x = 0; x <= 100; x++) {
   /* do work */
}

Sure, you could use syntactic sugar for mocking this common pattern as below, but you don't gain a lot by any sensible alternative and, like any usage of sugar, you lose some things that are important.

for(x = 0 to 100) {
   /* do work */
}

While this is useful for the simple iteration, it's shortcomings become clear after a bit of thought:

It's not possible in the shorthand for x to be anything but a locally declared variable.

You can't have a more complex test, such as "skip prime numbers"

You can't implicitly step by more than 1, or increment some external modifier.

Most of these can be overcome, but the syntax doesn't really help beyond some typing.

It's probably worth nothing that your one-line examples actually distort how things really should be done in C#.  If we're initializing a member of a class, you really do want to do something like the following:

class Test : ITest {
    public IExample example;
    public Test() {
      example = new Example();
    }
}

The type of your member is declared by way of an interface, so you can change the concrete class latter without a major code re-write.

The actual initialization is in a constructor, which can be adjusted or over-ridden in a deriving class.

Words like "Object" and "Class" are skipped entirely.  Names are for people, and the java-like capitalization syntax does enough for our purposes.

Conversely, if you're only initalizing a local instance, you would do one of the following:

IExample example = new Example();

or

var example = new Example();


答:
Both are possible, but the question is why would you want to use one over another. First case allows you to do additional work when setting flags. Maybe you want to modify something else or notify other piece of code. This is especially true for aggregate roots, whose reason for existence is primarily to ensure business rules over multiple entities. But pulling whole entity from database, just to change single property does seem wasteful. Second case removes this waste, but also removes your ability to run any business rules during the change. Also, any performance optimizations should be preceded by profiling, so you don't complicate your code for "percieved" performance gain.

If it was on me, I would use the first option, and if I figure out through profiling this is a performance problem, I would change it to second option.

Title: Can the DDD repository modify entity in the DB without an entity object?

Body:
Say I have an aggregate root Entity with some flags which are represented by an encapsulated object EntityFlags:

```<code>class Entity
{
    /** @var EntityFlags */
    private $flags;
    ...
}
</code>```

I have a repository for this entity.

My goal is to modify flags in the DB. There are two ways I see:

Get entity from the repository, modify flags like $entity->getFlags()->set($name, true) and save it: $repository->save($entity).

Create an additional method in the repository, e.g. modifyFlags(EntityId $id, EntityFlags $flags)

I think the first way is redundant. But it also seems wrong to use repository for partial entity updates like in the 2nd way. Which way is the correct one? Maybe I missed something?


问:
"flexible" functions in SQL Server 2012?
I'm looking for a very exotic thing and have no idea if it exists at all in SQL Server 2012. (Please forgive me - my background is in T-SQL, but not yet the fine details of SQL 'programming'.)
So, whether this 'this' is a UDF or SP or something else - I don't know.

The challenge is to have something so flexible that it could return a table with one or more records and a list of fields that is determined at runtime. I guess something like a virtual table, but 'lighter' and faster. Is that doable (and how)?

As an example, let's say I have two records (IDs being 1 and 2) and their values for field 'name' are 'R1' and 'R2'. Some other logic makes me want to combine these into a record with ID 'virtual1' and two fields names , 'F1' and 'F2' with value 'R1' and 'R2' - very much boiled down, but this what I'd like to achieve....

答:
It can be done (and indeed has been done), but it's not a feature of SQL Server and it's not particularly 'light'.

A relational database management system stores all its data in tables (that's item 0 in Codd's 12 rules). The flexibility you describe comes when you define tables that define 4 things: tables, rows, columns and values.

The 'tables' table lists all your tables (table id, attributes).

The 'columns' table lists columns in all your tables (table id, column id, attributes).

The 'rows' table lists rows in all your tables (table id, row id).

The 'values' table lists values in all your tables (table id, row id, column id, value). if you don't want all strings, you can have multiple 'values' tables.

There might be some other lookup tables for attributes and types, depending on how fancy you want to get.

You access the data by generating some rather fancy SQL that joins the 4 tables into the virtual table you mentioned.

Possibly not what you had in mind, but it can do what you asked.

And yes, this is an inner platform and has some features in common with a God table. As mentioned in these references, some very well known platforms use this technique to a greater or lesser extent, especially when tables, fields and relationships have to be defined on the fly. Microsoft CRM and Oracle Financials come to mind. Just don't do it unless you really need to. Then have no fear.

Obviously a system built like this would be next to impossible to query directly in SQL. As a rule end-users of such systems do not write SQL, but instead use the query and reporting tools provided as part of the system. It is also possible for the system to generate views on the fly to present the internal tables in a standard relational format, on which you can write standard SELECT queries and use SQL-oriented reporting tools.


答:
One of the failings of most bug tracking approaches is they only deal with one side of the equation - the end user's view of the system.  This is a critical bug to fix to this can wait a week (priority), this bug is painful to this is an s in a pluralization glitch (severity).

A blog post describing multidimensional bug tracking looks at addressing this including the developer view: PEF and REV.

The PEF values are the user's view:

Pain - how painful is the bug when it is encountered?

Effort - how much effort does it take to work around?

Frequency - how often does the bug occur?

The REV side is from the developer's view:

Risk - how risky is the fix?

Effort - how much effort will it take to fix?

Verifiability - how easy is it to verify that the bug is fixed?

Each of these is measured on a 1..9 scale with 1 being low/easy and 9 being high/hard.  The numbers are added together to give a score for PEF and REV.

The part that addresses the bits described:

How clear/straightforward it is. E.g. whether it's something that will need a lot of design work or just a simple UI bug fix.

How maintainable the affected area of the code is. Is it a well-designed area or a big ball of mud.

How much of the program I think will be affected by the required change.

These factor into the effort and risk described in in REV.

Yes, it is something that's been fought with before.  I have (in the past) used this model for custom fields in Redmine and it was reasonably successful.

The big advantage of this comes in when you compare the PEF and REV scores.  If you have a PEF of 21 and a REV of 7, thats something that can be a big win.  While a PEF of 7 and REV of 21 is something that should be avoided for awhile because the risk and effort side likely outweigh the benefit fixing it.

One can then look at the REV score and assign things with low Risk to the less experienced developers (low risk, high effort are often ideal for this situation).

Title: Categorize tasks/bugs by risk of changes

Body:
The project I'm currently working on has an issue: bugs and tasks are often assigned to people who are too new or too inexperienced and their work ends up producing more bugs down the road. The problem is that parts of our software are much more "dangerous" to work on than others due to code quality issues. I've been trying to combat this issue by estimating the risk associated with tasks and paying close attention to which developers get assigned which tasks.

We use JIRA so I started labeling issues to keep track of this estimation. I've noticed that I've ended up using several metrics to categorize a bug/task:

How clear/straightforward it is. E.g. whether it's something that will need a lot of design work or just a simple UI bug fix.

How maintainable the affected area of the code is. Is it a well-designed area or a big ball of mud.

How much of the program I think will be affected by the required change.

My labels are kind of messy since I didn't have a clear idea when I started what the possible categories would be and I still don't. I'm thinking about requesting a new field be added (something like "Risk") so that we can require an estimate before assigning the work to someone.

Has anyone dealt with this sort of thing before?


答:
Not sure if this meets your needs, but views can be very dynamic if you know how to use them properly.  The tables should be well-structured and contain the data exactly once, however the views can organize these tables with whatever combinations of columns you can imagine, given you know how to define them in a query.  I think this is a very powerful way to organize a database without having to sacrifice good database structure as well.  However we talking about creating a table from columns from existing tables.

If you wanted to create a table from scratch, then you should probably look into temporary tables (see in section Temporary Tables below).  These tables disappear once you disconnect, making them ideal for holding information for performing various tasks.  Like a normal table, you can make them to hold any type of information you want.  Of course, you still have to take the time to define each field individually, however assuming you were writing a dynamic script, this should be a trivial task.

The alternative being that you stay away from SQL Server altogether and you just use NoSQL type databases.  These are truly dynamic and are meant to be changed on the fly.  If having a dynamic database were important enough, I would consider using NoSQL such as mongodb rather than SQL Server.

Title: "flexible" functions in SQL Server 2012?

Body:
I'm looking for a very exotic thing and have no idea if it exists at all in SQL Server 2012. (Please forgive me - my background is in T-SQL, but not yet the fine details of SQL 'programming'.)
So, whether this 'this' is a UDF or SP or something else - I don't know.

The challenge is to have something so flexible that it could return a table with one or more records and a list of fields that is determined at runtime. I guess something like a virtual table, but 'lighter' and faster. Is that doable (and how)?

As an example, let's say I have two records (IDs being 1 and 2) and their values for field 'name' are 'R1' and 'R2'. Some other logic makes me want to combine these into a record with ID 'virtual1' and two fields names , 'F1' and 'F2' with value 'R1' and 'R2' - very much boiled down, but this what I'd like to achieve....


答:
SQL Server has the ability to host .NET assemblies so, in theory, you could write code to make it do whatever you want.

Failing that, there's always EAV, but I wouldn't wish that on my worst enemy.

What you really need to do is figure out how you can confine your scope.  Instead of building an inner platform, try to figure out the minimum possible additional flexibility that will meet your software requirements, and implement that.  My guess is that you can do it with a custom table and some DDL.


问:
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.

答:
Your approach will work.  A lot of document management systems use this type of approach.

One thing to consider is that you don't need to use both the user uuid and the random item id as part of the string.  You can instead hash the concatination of both.  This will give you a shorter identifier, and possibly some other benefits because the resultant id's will be more evenly distributed (better balanced for indexing, and file storage if you are storing files based on their uuid).

Another option you have is to generate just a temporary uuid for each item.  Then when you do connect and post them to the server, the server generates (guaranteed) uuid's for each item and returns that to you.  You then update your local copy.

OwnerDisplayName: herbrandson


问:
Does this implementation of the state pattern make sense?
I have the task to implement the state pattern in one of my classes. The assignment referenced a suggested implementation, and upon reviewing that implementation I was confused since I believed it to be nonsensical for most applications and frankly simply bad from a design point of view, since it completely dismisses some very basic design principles of software code.

This is the class diagram of the suggested implementation:

I wonder: What is the use of this implementation? It (imo) clearly violates the two main design principles of software engineering: Make things easily maintainable, and easily extensible.

In my eyes, this implementation has zero easy extensibility(you have to change the source of at least two classes, for example, to implement a new state that you forgot about when first implementing it). The coupling between this code and client code seems to be huge. If you remove anything in this pattern, all client code will break. If you want to add anything, you have to change all client code in order to adapt, for example, a new state, because new states can only be entered via the enter() method of the concrete state, or by directing injecting them into the Controller using the changeState() method.

As a bonus, you can only have one garage door in the entire world, since the states are practically singletons. The enter() method in the concrete states was given as this:

```<code>public static State enter(Controller c) {
if(m_instance == null) m_instance = new <<concreteStateName>>(c);
return m_instance;
}
</code>```

Or you can have multiple garage doors, which all open simultaneously if you open one.

Why would you put all methods in the abstract State class? Where's the polymorpy? Why do concrete states have either empty or exception throwing versions of methods that have nothing to do with their state (for example, the resulting interface of Opened will have a "lock()" method, even though you can't directly lock the garage door when it's open. You have to close it first). Why not choose a single method and implement it differently in the concrete States, making the thing easily extensible again?

It is also (again, as far as I can see) not really maintainable without a lot of troubles. What if you, after a couple of months of using the garage, decide that one state is in fact not only obsolete but wrong? You're going to have to take it out, and the according method in State() with it, breaking the entire code base that uses this implementation. This is a garage door with four states. I wouldn't want to work on that thing if it had any more states.

The situation gets more confusing when I look around the internet: The pattern actually seems to be implemented exactly this way a lot of times (for example it is implemented like this way in our national Wikipedia (German)).

The actual question: Am I missing anything or is this simply bad? Since this is so widespread, I'm thinking that I might be missing something obvious here.

答:
Try not to get caught up in the details of the UML. It is extensible if you assume enter(Controller) is some kind of interface implementation, and your concrete methods aren't required to implement all methods of the abstract superclass. The goal of the diagram is to illustrate the essence of the pattern.

The diagram alone fails to convey this, but the payoff is the simple fact that the Controller instance doesn't need to keep track of state to make correct decisions. For example, the controller can call lock() at any time on the abstract m_state object without fear of double-locking the door, or locking the door in an open state, because Closed happens to be the only concrete State object that implements lock() (polymorphy).

This is the reason all the methods defined in the abstract superclass are selectively implemented in the concrete classes.  It saves your controller the trouble of writing validation code for invalid state changes like double-locking a door.

The state switching logic is contained in the concrete state implementations. If the current state is a Locked instance and unlock() is called, the Locked state object would call changeState(Closed) on the Controller object (in addition to other Controller methods that might apply, such as a theoretical controller method setIndicatorLight(Color)).

The key here is that the concrete State implementations are designed to interact with each other. Lets say I create another concrete State implementation like Broken. If none of the other states actually set the Broken state on the controller, then the state might as well not exist. You also logically wouldn't create concrete implementations that didn't lead to other states.


问:
Commenting regular expressions
Are there any common practises for commenting the regular expressions: inline comments referring different part of RegEx or general comment for all expression?</p>

答:
This is somewhat a language specific answer, but no language is stated in the question.

The book "Dive Into Python" suggests implementing comments using Verbose Regular Expressions:

Python allows you to do this with something called verbose regular
  expressions. A verbose regular expression is different from a compact
  regular expression in two ways:

Whitespace is ignored. Spaces, tabs, and carriage returns are not
  matched as spaces, tabs, and carriage returns. They're not matched at
  all. (If you want to match a space in a verbose regular expression,
  you'll need to escape it by putting a backslash in front of it.)

Comments are ignored. A comment in a verbose regular expression is
  just like a comment in Python code: it starts with a # character and
  goes until the end of the line. In this case it's a comment within a
  multi-line string instead of within your source code, but it works the
  same way.

Example:

```<code>>>> pattern = """
^                   # beginning of string
M{0,4}              # thousands - 0 to 4 M's
(CM|CD|D?C{0,3})    # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
                    #            or 500-800 (D, followed by 0 to 3 C's)
(XC|XL|L?X{0,3})    # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
                    #        or 50-80 (L, followed by 0 to 3 X's)
(IX|IV|V?I{0,3})    # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
                    #        or 5-8 (V, followed by 0 to 3 I's)
$                   # end of string
"""
>>> re.search(pattern, 'M', re.VERBOSE)                1
</code>```

Source and further details here

This method has a slight disadvantage that the caller must know that the pattern is written in a verbose format and call it accordingly.

Title: Commenting regular expressions

Body:
This is somewhat a language specific answer, but no language is stated in the question.

The book "Dive Into Python" suggests implementing comments using Verbose Regular Expressions:

Python allows you to do this with something called verbose regular
  expressions. A verbose regular expression is different from a compact
  regular expression in two ways:

Whitespace is ignored. Spaces, tabs, and carriage returns are not
  matched as spaces, tabs, and carriage returns. They're not matched at
  all. (If you want to match a space in a verbose regular expression,
  you'll need to escape it by putting a backslash in front of it.)

Comments are ignored. A comment in a verbose regular expression is
  just like a comment in Python code: it starts with a # character and
  goes until the end of the line. In this case it's a comment within a
  multi-line string instead of within your source code, but it works the
  same way.

Example:

>>> pattern = """
^                   # beginning of string
M{0,4}              # thousands - 0 to 4 M's
(CM|CD|D?C{0,3})    # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
                    #            or 500-800 (D, followed by 0 to 3 C's)
(XC|XL|L?X{0,3})    # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
                    #        or 50-80 (L, followed by 0 to 3 X's)
(IX|IV|V?I{0,3})    # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
                    #        or 5-8 (V, followed by 0 to 3 I's)
$                   # end of string
"""
>>> re.search(pattern, 'M', re.VERBOSE)                1

Source and further details here

This method has a slight disadvantage that the caller must know that the pattern is written in a verbose format and call it accordingly.

ContentLicense: CC BY-SA 4.0


问:
Relative encapsulation design
Let's say I am doing a 2D application with the following design:

There is the Level object that manages the world, and there are world objects which are entities inside the Level object.

A world object has a location and velocity, as well as size and a texture. However, a world object only exposes get properties. The set properties are private (or protected) and are only available to inherited classes.

But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation).

How to tackle this problem? Should I just make everything public?

Currently what I'm doing is having a inner class inside game object that does the set work. So when Level needs to update an objects location it goes something like this:

```<code>void ChangeObject(GameObject targetObject, int newX, int newY){
 // targetObject.SetX and targetObject.SetY cannot be set directly
 var setter = new GameObject.Setter(targetObject);
 setter.SetX(newX);
 setter.SetY(newY);
}
</code>```

This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.

答:
A simple solution would be to make them immutable and produce new world objects for the next world state. This gives the Level complete control over the world's state without allowing objects to interfere with each other directly.

Another benefit of this approach is that it still works even if your world objects stop being pure data and have some internal AI. The objects can "update" their state by returning a copy of itself with modified position/velocity, and the world is still free to take that copy and "alter" it further to resolve collisions or apply global forces (e.g. gravity, wind.) Since the objects are immutable, you can also divvy up the work of calculating the new positions across multiple threads.

Finally, if you ever need to implement some sort of "save state" or "rewind time" mechanic you get it for free, because you're not destroying the old states. You'll need to do this if you want to have deterministic behavior and smooth animation.

Deterministic behavior requires that you to update the world in fixed time increments (as opposed to however long it's been since the last update.) In order to keep the gameplay in sync with real time you'll need to keep track of the excess time as well (e.g. you update in 0.05s intervals, but it's been 0.07 secs - you have an excess of 0.02 you can't throw away.) Eventually that excess time accumulates enough to produce a second world update in the same iteration of the game loop, which causes the animation to stutter periodically. The solution is to keep the previous world state and interpolate the positions between the previous and current state to smooth out the animation again. See Fix Your Timestep! for more info.

Title: Relative encapsulation design


答:
The idea is to restrict what objects can modify another object. There are two broad ways to achieve this.

Forget it and let anyone modify the objects. Just do not call the mutating functions from outside Level and move on.

Use a language feature to achieve this. For example, in C++ you could use the friend keyword to allow Level more access. In Java, you could use package-private visibility and put those objects (and only those objects) that need access in the same package.

Personally I think a clear, clean design is really nice to have. However, the real world pokes it head in sometimes and makes it necessary to pound that square peg into the round hole. While it can be good OO practice to restrict who can mutate or use an object, perhaps option one is the quick and easy way. Maybe option 2 is better.

If this code is not going to be used by others (e.g. plugins) then maybe option one is quicker and easier. If it will be used and extended by others' code, then option two would be better.

Title: Relative encapsulation design

Body:
Let's say I am doing a 2D application with the following design:

There is the Level object that manages the world, and there are world objects which are entities inside the Level object.

A world object has a location and velocity, as well as size and a texture. However, a world object only exposes get properties. The set properties are private (or protected) and are only available to inherited classes.

But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation).

How to tackle this problem? Should I just make everything public?

Currently what I'm doing is having a inner class inside game object that does the set work. So when Level needs to update an objects location it goes something like this:

```<code>void ChangeObject(GameObject targetObject, int newX, int newY){
 // targetObject.SetX and targetObject.SetY cannot be set directly
 var setter = new GameObject.Setter(targetObject);
 setter.SetX(newX);
 setter.SetY(newY);
}
</code>```

This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.


问:
Are there any standards for preparing a user manual of electronic device?
Are there any standards for preparing a user manual of electronic device?

I am trying to prepare a manual for a device. However, I could not find any format. If I find, I will take this as guide for me.

If there is no standard, what should be in the manual or what should not be in?

答:
There's a few different standards:

MIL-STD-498

IEEE 12207-2008

Documentation Standards For Implementation Stage (Hong Kong government standard)

General format:

Front page with any necessary version information and details of the
author & publisher Contents page(s)

General business over view of the system's scope and purpose

General over view of the manual's scope and purpose

General over view of the software including capabilities and it's hardware and software requirements

General user orientated over view of the software

Start up guide, covers: installation, setup, first time use, any default passwords ect

Processing reference, guides user in performing every operation that the system is capable of

For more detail see MIL-STD-498


问:
What hat should a programmer not wear?
In my experience, software developers tend to wear multiple hats and fill multiple roles with different responsibilities.  From not only coding, but sometimes also writing SQL, designing the user-interface, designing the database, graphics manipulation, to even QA testing.

If the primary role is to write software/code, what roles should the developer not take on?  Are there any?

The intention of this question is not because a developer is incapable of filling another role-- but having the additional role actually works against the primary role, or should really be a dedicated role of someone who does not primarily program.

答:
The "designer" or the "creative guy".
You'll go from innocently putting together a mockup of the interface of an application to writing marketing text for the next online ad campaign or endless discussions about the "right" shade of blue before you know it x_x.</p>

ContentLicense: CC BY-SA 2.5

Title: What hat should a programmer not wear?


问:
How to make C++ template stack work with basic data types and compound variables?
Templates are nice for similar algorithms of different data types. Say I make a template stack of a basic data type...

```<code>Stack<int> stck(10);
stck.Push(5);
</code>```

I'd pop it...

```<code>int x = stck.Pop();
</code>```

x would be 5. If I call pop again, there are no items, so I have the method just return 0 for null. It could be something else, but whatever.

But now, if I change the template type to a compound variable (a structure type - say, RECT), and the stack is empty, it can't return 0. It expects a RECT type, but I don't have any left. How do I make this work for basic data types and compound variables? Exceptions?

答:
3 options

make popping en emtpy stack undefined and don't worry about it

throw an exception

return default constructed T() (which happens to be 0 for the numeric types)


问:
Would a "downcast if block" be a reasonable language feature?
Consider the following "if cast":

```<code>class A     { public void f1() { ... } }
class B : A { public void f2() { ... } }

A a = foo(); // might return A or B

if ( a is B ) {
    //  Inside block, implicitly "redeclare" a as type B
    //  It's B, go for it
    a.f2();
    //  Wouldn't compile.
    a = new A();
}
</code>```

We don't enter the block unless a is a B, therefore within the block, the compiler treats a exactly as if it had been declared as type B. You could assign null to it in the block if it's a reference type, but it would be a compile-time error to assign new A() to it, for example (thanks @ThomasEding for bringing up that question).

Anything that could break that assumption that a is B, could just as easily break the following legal C# as well:

```<code>if ( a is B ) {
    B b = a as B;

    b.f2();
}
</code>```

The former looks to me like syntactic sugar for the latter.

Even if this feature makes sense, I'm sure Anders Hjelberg's lads have more useful features to implement. I'm just wondering if it's a worse idea than I think it is.

UPDATE A serious objection would be that the feature as described adds semantics without adding syntax: From one version of the language to the next, the meaning of the above block would change significantly. It would be more tolerable with a new keyword. But then you'd be adding a new keyword.

Update

A more redable version of this feature was implemented in C#7:

```<code>object object2 = new List<Test>();

if (object2 is Dictionary<String, int> foo)
{
    Console.WriteLine(foo.Keys);
}
</code>```

答:
It's not that it's a bad idea, it's just that there's no point in elevating this to the point of language feature, not even syntactic sugar, you can very easily implement this yourself in C#:</p>

```<code>public static class ExtensionMethods
{
    public static void AsIf<T>(this object target, Action<T> todo)
    {
        if (target is T) todo((T)target);
    }
}

a.AsIf(aAsB => {your code});
</code>```

Body:
It's not that it's a bad idea, it's just that there's no point in elevating this to the point of language feature, not even syntactic sugar, you can very easily implement this yourself in C#:

public static class ExtensionMethods
{
    public static void AsIf<T>(this object target, Action<T> todo)
    {
        if (target is T) todo((T)target);
    }
}

a.AsIf(aAsB => {your code});


答:
I like the idea. It's also not dangerous if you take into consideration some cases.

Consider

```<code>if (a is B) {
    a.BMethod(); // OK
    a = new B(); // OK
    a.BMethod(); // OK
    a = null;    // Disallow? (Probably OK)
    a.BMethod(); // Disallow? (Probably OK)
    a = new A(); // Disallow? (Probably bad)
    a.BMethod(); // Disallow?
}
</code>```

It certainly is possible to write your extension to fail to compile in such a case, but one would want clean error messages, need to define more restrictions (such as you could only assign a B to a inside the if-block), throw a runtime exception, or something else.

Consider multi-threaded code using a, and a gets reassigned inside the as-if block. This would be very hard to do properly in a direct C# translation (it's possible, but not very nice *). This feature wants to be done at the byte code level, where it is trivial to implement.

(*): You would need to assign to a temporary, then assign to the original a, then assign to the a_as_b compiler generated variable. Even still, I may be missing some important edge cases.

Title: Would a "downcast if block" be a reasonable language feature?

Body:
Consider the following "if cast":

```<code>class A     { public void f1() { ... } }
class B : A { public void f2() { ... } }

A a = foo(); // might return A or B

if ( a is B ) {
    //  Inside block, implicitly "redeclare" a as type B
    //  It's B, go for it
    a.f2();
    //  Wouldn't compile.
    a = new A();
}
</code>```

We don't enter the block unless a is a B, therefore within the block, the compiler treats a exactly as if it had been declared as type B. You could assign null to it in the block if it's a reference type, but it would be a compile-time error to assign new A() to it, for example (thanks @ThomasEding for bringing up that question).

Anything that could break that assumption that a is B, could just as easily break the following legal C# as well:

```<code>if ( a is B ) {
    B b = a as B;

    b.f2();
}
</code>```

The former looks to me like syntactic sugar for the latter.

Even if this feature makes sense, I'm sure Anders Hjelberg's lads have more useful features to implement. I'm just wondering if it's a worse idea than I think it is.

UPDATE A serious objection would be that the feature as described adds semantics without adding syntax: From one version of the language to the next, the meaning of the above block would change significantly. It would be more tolerable with a new keyword. But then you'd be adding a new keyword.

Update

A more redable version of this feature was implemented in C#7:

```<code>object object2 = new List<Test>();

if (object2 is Dictionary<String, int> foo)
{
    Console.WriteLine(foo.Keys);
}
</code>```

Body:
I like the idea. It's also not dangerous if you take into consideration some cases.

Consider

if (a is B) {
    a.BMethod(); // OK
    a = new B(); // OK
    a.BMethod(); // OK
    a = null;    // Disallow? (Probably OK)
    a.BMethod(); // Disallow? (Probably OK)
    a = new A(); // Disallow? (Probably bad)
    a.BMethod(); // Disallow?
}

It certainly is possible to write your extension to fail to compile in such a case, but one would want clean error messages, need to define more restrictions (such as you could only assign a B to a inside the if-block), throw a runtime exception, or something else.

Consider multi-threaded code using a, and a gets reassigned inside the as-if block. This would be very hard to do properly in a direct C# translation (it's possible, but not very nice *). This feature wants to be done at the byte code level, where it is trivial to implement.

(*): You would need to assign to a temporary, then assign to the original a, then assign to the a_as_b compiler generated variable. Even still, I may be missing some important edge cases.


问:
Should I keep investing into data structures and algorithms?
These days, I'm investing heavily in data structures and algorithms and trying to solve some programming puzzles.

I'm trying to code and solve with Java and Clojure.

Am I wasting my time? should I invest more in technologies and frameworks that I already know in order to gain deeper knowledge (the ins and the outs) and be able to code with them more quickly?

By studying data structures and algorithms, am I going to become a better programmer or those subjects are only important during college years?

答:
I spent a lot of time hacking around in C/C++ with OpenGL. I know the languages and API well enough...and I've become a reasonable developer and programmer because of that experience. That said, the actual algorithmic knowledge required to solve various problems encountered I've only just really been able to grasp.

Speaking from personal experience, focusing on building applications is going to be a waste of your time if you don't know the theory behind the problem domains which pertain to what you're trying to build.

For many different kinds of software, these domains will stem from the fundamentals you learn from studying algorithms, in addition to their own specific niche-based theory (e.g., linear algebra in computer graphics, number/information theory in cryptography, etc.).

You don't necessarily have to become a computational wiz-kid behind everything, but doing what you were doing at the time of this post is a very, very necessary path to go down at least once in one's programming journey - regardless of whether or not they're self-taught.


答:
Let's assume features start with 0 points, rather than with -100 points (due to costs associated with implementation, design, etc.).

This feature strikes me as confusing.  I've already declared that a is an A.  If I want to know the compile-time type of a, I only have to look in one place, at the declaration.  While I acknowledge that the implementation is relatively simple (use the code substitution you describe in your question), this also argues in favor of not implementing the feature; it's easy for coders to do it, too.

The truly horrifying thing is that the type of a variable can magically change immediately after a }.  C# very deliberately prevents this from happening (see Simple names are not so simple).  So, I absolutely hate any version of this feature that fails to introduce a new variable during the cast.

If you find yourself constantly casting your types so as to access members of derived classes, it makes me suspect you are misusing inheritance.  Personally, usually in code where I'm using such a conditional, I'm going to break out of my function if the cast fails.  So, my code would look more like this:

```<code>B myB = myA as B;
if (myB == null) return;
</code>```

Which would, under some variant of your proposal, become this:

```<code>if (!(myA is B)) return;
</code>```

or (introducing a new name)

```<code>if (!(myA to B myB)) return;
</code>```

or, using declarative expressions (this is a variant on Jimmy Hoffa's answer)

```<code>if (!a.To(out B myB)) return;
</code>```

With the exception of the approach using declarative expressions, all of these features require learning new C# syntax for a feature that is not at all painful to deal with.  The declarative expression approach is nice in that it is the general case of a specific feature; i.e. allowing coders to make use of an assignment and conditional using a single expression.

The only cost to the declarative expression approach is that it won't work universally; it only works if your special To method is implemented and visible in your current scope.  However, that's a price I'm willing to pay to avoid adding yet more syntax to the C# language; I won't bother using such an extension method unless I'm dealing with code which constantly requires it (and probably not even then).

In summary: This feature isn't needed quite often enough to justify adding new syntax to the language.  However, the more general feature, declarative expressions, may be worth the cost (which is why Microsoft is probably going to pay it).  It not only handles this case, but also handles the annoying two-statement TryParse case (and, like your proposal, makes for clean scope; the type is only in scope on the inside of the conditional).

Update: Declarative Expressions were cancelled.

Update 2: C# 7.0 is adding "out variables". This might be enough for my final example (if (!a.To(out B myB)) return;).  C# 7.0 is also adding "Is-expressions with patterns", which allows, if (!(o is int i)) return;.  This is basically the feature you asked for.

Body:
Let's assume features start with 0 points, rather than with -100 points (due to costs associated with implementation, design, etc.).

This feature strikes me as confusing.  I've already declared that a is an A.  If I want to know the compile-time type of a, I only have to look in one place, at the declaration.  While I acknowledge that the implementation is relatively simple (use the code substitution you describe in your question), this also argues in favor of not implementing the feature; it's easy for coders to do it, too.

The truly horrifying thing is that the type of a variable can magically change immediately after a }.  C# very deliberately prevents this from happening (see Simple names are not so simple).  So, I absolutely hate any version of this feature that fails to introduce a new variable during the cast.

If you find yourself constantly casting your types so as to access members of derived classes, it makes me suspect you are misusing inheritance.  Personally, usually in code where I'm using such a conditional, I'm going to break out of my function if the cast fails.  So, my code would look more like this:

B myB = myA as B;
if (myB == null) return;

Which would, under some variant of your proposal, become this:

if (!(myA is B)) return;

or (introducing a new name)

if (!(myA to B myB)) return;

or, using declarative expressions (this is a variant on Jimmy Hoffa's answer)

if (!a.To(out B myB)) return;

With the exception of the approach using declarative expressions, all of these features require learning new C# syntax for a feature that is not at all painful to deal with.  The declarative expression approach is nice in that it is the general case of a specific feature; i.e. allowing coders to make use of an assignment and conditional using a single expression.

The only cost to the declarative expression approach is that it won't work universally; it only works if your special To method is implemented and visible in your current scope.  However, that's a price I'm willing to pay to avoid adding yet more syntax to the C# language; I won't bother using such an extension method unless I'm dealing with code which constantly requires it (and probably not even then).

In summary: This feature isn't needed quite often enough to justify adding new syntax to the language.  However, the more general feature, declarative expressions, may be worth the cost (which is why Microsoft is probably going to pay it).  It not only handles this case, but also handles the annoying two-statement TryParse case (and, like your proposal, makes for clean scope; the type is only in scope on the inside of the conditional).

Update: Declarative Expressions were cancelled.

Update 2: C# 7.0 is adding "out variables". This might be enough for my final example (if (!a.To(out B myB)) return;).  C# 7.0 is also adding "Is-expressions with patterns", which allows, if (!(o is int i)) return;.  This is basically the feature you asked for.


问:
Dealing with co-workers who do not have a consistent coding style?
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?

答:
We have a JUnit test that looks for formatting issues. It runs as part of the build. I continually get bit by omitting a space between if, while or for and the opening parenthesis. Our code is consistently formatted, though.

http://code.google.com/p/kawala/wiki/BadCodeSnippetsRunner


答:
I've seen an AsIf extension method implemented as such:

```<code>private static void AsIf<TBase, TChild>(this TBase source, Action<TChild> action) where TChild : TBase
{
    if ((source is TChild) && (action != null))
    {
        action((TChild)source);
    }
}
</code>```

The generic constraints make sure you're attempting to "as-if" something hierarchically allowable.

Body:
I've seen an AsIf extension method implemented as such:

private static void AsIf<TBase, TChild>(this TBase source, Action<TChild> action) where TChild : TBase
{
    if ((source is TChild) && (action != null))
    {
        action((TChild)source);
    }
}

The generic constraints make sure you're attempting to "as-if" something hierarchically allowable.


问:
RESTful API resource path for resource with complex relationship?
In my RESTful API, I have Users, Applications, and Tokens. An application has an owner, which is a user. A token is linked to both an application, and a user.

A user has both public and private representations:

GET /user - Retrieve current authenticated user

GET /users/:user - Retrieve given user

An application has a public representation:

GET /applications/:id - Retrieve given application

A token is associate with both a user, and an application. A token is never public:

GET /user/tokens/:id - Retrieve given user token

Similary, applications of a user can be seen like so:

GET /user/applications - Retrieve collection of the current authenticated users' applications.

What should the resource path be in a situation such as this, for if I wanted to get all of the current users' tokens for a given application? Some things I have considered:

GET /user/tokens/application/:appId - I felt this may be poorly represented. How would it be read? Current users' tokens application? It's really: current users' tokens for application.

GET /user/applications/:id/tokens - I felt this could imply that if you owned an application you would be able to see the tokens of all users using the application, which is of course not the intended functionality, or representation.

GET /applications/:id/tokens - I felt this to be problematic in a manner similar to the above.

答:
Remember you can use the query string to filter or limit the result. Since you're looking for a user's tokens, limited to a particular application, this is pretty natural

GET /user/tokens?application=:id

The resource is a collection of tokens, limited by an application ID. This is consistent with /user/tokens/:id except that you're narrowing the result by application ID instead of a token id.


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
I use Google Chrome + AdBlock Plus, and have JavaScript turned on.

EDIT: I use NotScript now. :)

<s>Chrome ALONE blocks almost all popups (I've only found one site [Chess.com] that broke through once), and AdBlock gets rid of all the ads, so I have no problems with those.

IMO, JavaScript gives you a "better experience" overall, and as long as you visit trustworthy sites (that haven't been hacked...), you're fine. As "computer guys"/developers, I believe we should have a very keen "internet sense", and be able to tell if a site may be malicious.</s>


问:
Encyption for passwords in config file?
I was wondering, if it makes sense to encrypt passwords for external services stored in my config file with an symmetric encryption algorithm?

On the one hand I think, if someone gets access to the config file, he will probably also get access to the code and it will relatively easy to decrypt the passwords... on the other hand I am not comfortable to store the passwords in plain text either.

Whats your opinion on this topic? Are there any "best practices"?

答:
As with all security, you need to consider two things: (1) threats and (2) cost-benefit. For example, storing an encrypted password in a config file using symmetric cryptography relies on the file's access permissions and key management.

This may be possible on a web server. After all, the web server can run in a single, low permission account with either (1) read access to the config file and a key store or (2) access to a component that does. Microsoft, for example, supports the former.

However, a traditional application running on Windows, Mac or Linux is different. The user is likely an administrator or have administrator access (e.g. sudo or UAC), meaning he or she can either access the config file and key store or grant themselves access. Anyone with physical access to the storage can also bypass any access control.

Should you use a different form of encryption like asymmetric cryptography? Asymmetric cryptography gives you two keys, meaning data encrypted with one can only be decrypted with another. Since the application will need access to the decrypted password, it needs access to one of the keys. Asymmetric encryption will only remove the ability to encrypt a new or changed password.

Asymmetric encryption may be useful as part of a digital signature to detect tampering. However, a local administrator will have access to the key store used for the digital signature.

You do not specify the encryption algorithm you use but using a stronger algorithm (e.g. wider key, encrypt iteratively) but this only helps if an attacker gets access to the config file and not the key store then tries to brute force it.

Should you store the password somewhere else? This is an operating system and environment dependent question. You could use dedicated hardware, e.g. Trusted Platform Module (TPM) or Hardware Security Module (HSM) but these are topics unto themselves and are likely to be too expensive and complex for most cases.

A better solution may be to trust a third party authentication provider, e.g. via OpenID. This means the application need not manage passwords and customers need not remember yet another password. The third party provider may also provide a second factor (e.g. one time password) and handle password changes and resets.

However, the application risks a compromise to that third party authentication service. Local administrators can also view or modify which third party provider is trusted.

Without knowing more about what you are doing, I would do as you say, i.e. encrypt the password with symmetric encryption in a config file with appropriate permissions. It covers the 90% case without impacting the customer or your development schedule too much.

Title: Encyption for passwords in config file?


问:
Why convert to assembly language instead of machine code?
When I compile a C program, it is compiled first to assembly code, then assembled into machine code. I'm curious why it doesn't just convert straight to machine code in the first place.</p>

答:
It depends on the compiler and the options you provide to the compiler. These days the most widely used compilers will write out machine language by default, but will generate an assembly listing if you request it. It can be helpful to have the assembly listing because a) sometimes compilers have bugs and you want to check the code it's generated, b) you want to understand how the machine code is affected by the CPU pipeline and cache and most people find it much easier to read assembly than machine code.

These days compilers typically convert your program to a highly abstract representation and allow you to write custom back ends to generate different flavors of machine language or even other high level languages.


问:
Accessing a private array when I have an extension method
I'm trying to make a number of data classes for my C#/XNA game, which would essentially be a wrapper around T[,]:

```<code>public interface IGrid<T>
    where T : struct
{
    Point Size { get; }
    T this[int x, int y] { get; set; }
}
</code>```

For example, I might have a Heightmap object which is essentially an IGrid<float>, or I might have a Level.TileData object which is an IGrid<byte> or IGrid<int>. These could be entirely separate classes with specific helper methods, etc.

I also made a small extension library that operates specifically on any 2-dimensional array:

```<code>public static class Transformations
{
    static T[,] Transpose(this T[,] value);
    static T[,] FlipHorizontal(this T[,] value);
    static T[,] FlipVertical(this T[,] value);
    static T[,] RotateClockwise(this T[,] value);
    static T[,] RotateCounterClockwise(this T[,] value);
}
</code>```

However, when I actually implement IGrid<T>, I encounter a small design issue.

Because the backing array would be private/protected, any client code that actually uses IGrid<T> would be unable to use my extension library.

According to CA1819 and Eric's blog, publicly exposing an array (even via properties!) is a bad idea, as it would be fully mutable. The suggested workaround is to clone the array, then expose it as an immutable type (which means I still don't have an array to use the library on).

Am I overthinking things, or is there an elegant solution here? I really like the idea of using indexers to read/write data on the object, but in some situations I might want to work with the entire array at once.

答:
There is no guarantee that a client implementing IGrid<T> does actually use an 2D array T[,] for the implementation. So without changing something, you cannot expect to make your extension library work "out of the box" on IGrid<T>. IMHO you have the following options:

change (or extend) the interface of your Transformation class to use IGrid<T> as input instead of T[,]. This is probably the cleanest alternative, but I guess if you want to keep and maintain the T[,] variant, too, it will mean some code duplication in your extension library, since T[,] and IGrid<T> don't have a common interface.

to avoid the code duplication, you could write a conversion method from IGrid<T> to T[,], but this will have the drawback of making additional copies of the data. You could use this with my first suggestion to create adapter methods to avoid the code-duplication:

```<code> T[,] Transpose(this IGrid<T> value)
 {
      return ConvertIGridToArray(value).Transpose();
 }
</code>```

extend IGrid<T> to provide access to underlying T[,], with the drawback of loosing immutability (which forces any client to use a T[,] internally)

Currently, I don't see a way to avoid the code duplication and the additional copying and the loss of immutability all three - pick your choice.

Note that for big arrays, immutability maybe not the optimal design for your transformation operations, without immutability they could be implemented in-place, which is sometimes the better alternative, since it is less memory consuming. Note further that if you want your transformation methods work on something like an Heightmap class, they cannot deliver a new Heightmap  object directly, you will have to do some type conversion either. An in-place transformation would not have that problem, it could operate on the internal T[,] of the Heightmap object directly.

Body:
There is no guarantee that a client implementing IGrid<T> does actually use an 2D array T[,] for the implementation. So without changing something, you cannot expect to make your extension library work "out of the box" on IGrid<T>. IMHO you have the following options:

change (or extend) the interface of your Transformation class to use IGrid<T> as input instead of T[,]. This is probably the cleanest alternative, but I guess if you want to keep and maintain the T[,] variant, too, it will mean some code duplication in your extension library, since T[,] and IGrid<T> don't have a common interface.

to avoid the code duplication, you could write a conversion method from IGrid<T> to T[,], but this will have the drawback of making additional copies of the data. You could use this with my first suggestion to create adapter methods to avoid the code-duplication:

 T[,] Transpose(this IGrid<T> value)
 {
      return ConvertIGridToArray(value).Transpose();
 }

extend IGrid<T> to provide access to underlying T[,], with the drawback of loosing immutability (which forces any client to use a T[,] internally)

Currently, I don't see a way to avoid the code duplication and the additional copying and the loss of immutability all three - pick your choice.

Note that for big arrays, immutability maybe not the optimal design for your transformation operations, without immutability they could be implemented in-place, which is sometimes the better alternative, since it is less memory consuming. Note further that if you want your transformation methods work on something like an Heightmap class, they cannot deliver a new Heightmap  object directly, you will have to do some type conversion either. An in-place transformation would not have that problem, it could operate on the internal T[,] of the Heightmap object directly.


答:
tl;dr: Concurrency Issues

When you write A a; you are effectively making the statement "a is a variable that can contain objects representable by the type A". By changing the variable's type to something lower in the food chain, you would potentially introduce concurrency issues.

For example

```<code>namespace AsIf
{
class A { public void FA() {} }
class B : A { public void FB() {} }
class C : A { public void FC() {} }

class Program
{
delegate void ActionOnA(ref A a);
static void AToC(ref A a) { Thread.Sleep(5000); a = new C(); }

void main()
{
A a = new B();

// Wait 5 seconds, change a to new C()
ActionOnA action = AToC;
action.BeginInvoke(ref a, (ar) => { action.EndInvoke(ref a, ar); }, null);

if(a is B)
{
// a is implicitly retyped as B for the rest of this block

// B.FB get called on a (an instance of B)
a.FB();
// Sleep 6 seconds
Thread.Sleep(6000);
// B.FB gets called on a (an instance of C)
a.FB();
// 'Undefined behaviour' most likely causing all kinds of crazy
}
}
}
}
</code>```

This is slightly less likely to happen when you introduce b

```<code>// assume everything else is as before

void main()
{
A a = new B();

// Wait 5 seconds, change a to new C()
ActionOnA action = AToC;
action.BeginInvoke(ref a, (ar) => { action.EndInvoke(ref a, ar); }, null);

if(a is B)
{
// introduce b
B b = (B)a;

// B.FB get called on b (an instance of B)
b.FB();
// Sleep 6 seconds
Thread.Sleep(6000);
// B.FB gets called on b (an instance of B)
b.FB();
// Safe! (for now)
}
}
</code>```

This is because B is an entirely different variable being used to hold the same object.
What the concurrent function is actually doing is assigning to the variable a which is not directly affecting the object a was holding. Because b now holds a reference to the object that was in a, a can get reassigned and nobody would care.

Of course this is an implementation detail. If the compiler were to secretly create a second variable for the asif block rather than just reinterpreting a as being of the type B, the result would be effectively the same as my second example. Whether such behaviour is expected, obvious or desired is a different matter entirely.

It's not an impossible feature, it's just one that's more work than it's worth really.

Body:
tl;dr: Concurrency Issues

When you write A a; you are effectively making the statement "a is a variable that can contain objects representable by the type A". By changing the variable's type to something lower in the food chain, you would potentially introduce concurrency issues.

For example

namespace AsIf
{
class A { public void FA() {} }
class B : A { public void FB() {} }
class C : A { public void FC() {} }

class Program
{
delegate void ActionOnA(ref A a);
static void AToC(ref A a) { Thread.Sleep(5000); a = new C(); }

void main()
{
A a = new B();

// Wait 5 seconds, change a to new C()
ActionOnA action = AToC;
action.BeginInvoke(ref a, (ar) => { action.EndInvoke(ref a, ar); }, null);

if(a is B)
{
// a is implicitly retyped as B for the rest of this block

// B.FB get called on a (an instance of B)
a.FB();
// Sleep 6 seconds
Thread.Sleep(6000);
// B.FB gets called on a (an instance of C)
a.FB();
// 'Undefined behaviour' most likely causing all kinds of crazy
}
}
}
}

This is slightly less likely to happen when you introduce b

// assume everything else is as before

void main()
{
A a = new B();

// Wait 5 seconds, change a to new C()
ActionOnA action = AToC;
action.BeginInvoke(ref a, (ar) => { action.EndInvoke(ref a, ar); }, null);

if(a is B)
{
// introduce b
B b = (B)a;

// B.FB get called on b (an instance of B)
b.FB();
// Sleep 6 seconds
Thread.Sleep(6000);
// B.FB gets called on b (an instance of B)
b.FB();
// Safe! (for now)
}
}

This is because B is an entirely different variable being used to hold the same object.
What the concurrent function is actually doing is assigning to the variable a which is not directly affecting the object a was holding. Because b now holds a reference to the object that was in a, a can get reassigned and nobody would care.

Of course this is an implementation detail. If the compiler were to secretly create a second variable for the asif block rather than just reinterpreting a as being of the type B, the result would be effectively the same as my second example. Whether such behaviour is expected, obvious or desired is a different matter entirely.

It's not an impossible feature, it's just one that's more work than it's worth really.


问:
How to manage memory in C interface for C++ implementation considering c++11?
I have a library implemented in C++ which has a C interface. This C interface is, for all intents and purposes, the only way to use this library. C++11 seems to discourage the use of raw pointers but neither shared_ptr or unique_ptr are suitable in this case. From what I understand, intrusive_ptr is an option, but I am both unsure of how this differs from maintaining my own ref count (I am new to C++) and wary of wading into boost yet (I am new to C++).

How should I handle memory management in C++11 and higher? I only state the spec to make it clear that I am willing to use the features of the latest spec and have no need to maintain compatibility with older specs.

答:
The fact that C++11 offers a range of smart-pointer classes to make life easier with memory management does not mean that you can't or shouldn't use raw pointers where that is appropriate.

The committee that maintains the C++ standard is very reluctant to remove existing features from the language and more so if it is a widely used and useful feature like raw pointers. Keeping the language backwards compatible is one of the corner stones in its evolution.

With that said, if you have to provide a C-compatible interface to your C++ library, you should use only features from the common subset of C and C++ in your interface and that means using raw pointers where they are visible in the interface and effectively letting the user of your library deal with allocation/deallocation (although you can provide functions for that).


答:
As a data point, the Ceylon language allows1 you to do this.

In Ceylon, you would write:

```<code>A a = ...
if (is B a) {
   // refer to 'a' as a 'B'
}
</code>```

or

```<code>if (is B b = some_expression_returning_A ) {
   // refer to 'b' as a 'B'
}
</code>```

There is also a variation of the switch statement that allows you to switch on types, in much the same way.  For example:

```<code>void switchOnEnumTypes(Foo|Bar|Baz var) {
    switch(var)
    case (is Foo) {
        print("FOO");
    }
    case (is Bar) {
        print("BAR");
    }
    case (is Baz) {
        print("BAZ");
    }
}
</code>```

1 - Actually, it requires this, since Ceylon doesn't have an explicit type-cast.  The goal is to avoid core language constructs that can throw exceptions.  They do something similar to design out NPEs.

Body:
As a data point, the Ceylon language allows1 you to do this.

In Ceylon, you would write:

A a = ...
if (is B a) {
   // refer to 'a' as a 'B'
}

or

if (is B b = some_expression_returning_A ) {
   // refer to 'b' as a 'B'
}

There is also a variation of the switch statement that allows you to switch on types, in much the same way.  For example:

void switchOnEnumTypes(Foo|Bar|Baz var) {
    switch(var)
    case (is Foo) {
        print("FOO");
    }
    case (is Bar) {
        print("BAR");
    }
    case (is Baz) {
        print("BAZ");
    }
}

1 - Actually, it requires this, since Ceylon doesn't have an explicit type-cast.  The goal is to avoid core language constructs that can throw exceptions.  They do something similar to design out NPEs.


答:
Analysis.

It has to use some kind of intrusive pointer (specifically user-implemented reference counting), though it could be Boost intrusive_ptr or some other flavor.

My personal opinion.

I have used Microsoft COM pointers in my projects and it works fine. If your code only has to work on Microsoft Windows, this may be the recommended route as the C systems programmer for Windows will probably be familiar with it. For all other considerations, including cross-platform applications, use Boost intrusive_ptr.

I have described my opinions about the minimal usage of Microsoft COM pointers in this answer.

The nature of intrusive_ptr.

It is important to understand the nature of intrusive_ptr. It is a handle class, implemented using C++ template. It is provided so that such objects can be owned by C++ callers.

C code cannot see this handle class from their header includes, let along call its methods. Instead, the C code would be calling some extern "C" methods. This means you will be providing extern "C" methods which in turn call the intrusive_ptr_add_ref and intrusive_ptr_release methods provided by Boost intrusive_ptr.

http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/intrusive_ptr.html

What this means.

Calling C++ methods on this object from C code will require one wrapper function per class method, such as this.

For objects that require add_ref and release management, you will provide extern "C" wrapper functions for those as well.

It is your responsibility to document in an obvious way, or convey to the C programmer, what pointer types in your object are reference-counted. A combination of naming convention, API documentation, API usage sample, and verbal warning is recommended.

Finally, understand the laws (object ownership rules) that needs to be obeyed when using reference counting. See this question and the answer.

Advanced topics - object or interface type cast, interface query, interface segregation

I have only used these techniques with Microsoft COM (via its QueryInterface method), so I cannot comment on whether one could use these techniques on Boost intrusive_ptr when programming via an extern "C" interface.

Title: How to manage memory in C interface for C++ implementation considering c++11?

Body:
I have a library implemented in C++ which has a C interface. This C interface is, for all intents and purposes, the only way to use this library. C++11 seems to discourage the use of raw pointers but neither shared_ptr or unique_ptr are suitable in this case. From what I understand, intrusive_ptr is an option, but I am both unsure of how this differs from maintaining my own ref count (I am new to C++) and wary of wading into boost yet (I am new to C++).

How should I handle memory management in C++11 and higher? I only state the spec to make it clear that I am willing to use the features of the latest spec and have no need to maintain compatibility with older specs.


问:
Relevance of HTML5: Is now the time?
It seems like most of the jobs I'm receiving, and most of the Internet, is still using standard HTML (HTML 4, let's say) + CSS + JS. Does anyone have any vision on where HTML5 is as a standard, particularly regarding acceptance and diffusion? It's easy to find information about inconsistencies between implementations of HTML5 and so forth. What I want to know about is relevance of HTML5.

答:
I have two quibbles about the question you're asking:

• Which HTML5 are you asking about?

Different groups have different agendas/goals, and what any two groups mean when they each say "HTML5" can be drastically different. Sometimes it's a shorthand for both HTML5 and CSS3. Sometimes HTML5, CSS3 and jQuery. Sometimes they mean the W3C's spec. Sometimes they mean the WHATWG's spec (sadly, the last two aren't identical). And so on.

Before you can get a solid answer to your question, you first have to specify what you mean when you say HTML5.

• It's not really black & white

It's entirely possible to implement parts of HTML5 right now without any problems. Some other parts of it, not so much. But it's not a black or white issue; you don't have to junk everything that works in order to add some of what's in HTML5.

An article I think you might find useful is How to use HTML5 on your website today from InfoWorld, written by, well, me.

Title: Relevance of HTML5: Is now the time?


问:
Do compiler-writers actually need to 'understand' machine code?
Might be kind of an odd question.

A guy writing a C++ compiler (or whatever non-VM language): Does he need to be able to read/write raw machine language? How does that work?

EDIT: I am specifically referring to compilers that compile to machine code, not to some other programming language.

答:
No. The key point of your question is that compilation is extremely broad term. Compilation can happen from any language to any language. And assembly/machine code is only one of the many languages for compilation target. For example Java and .NET languages like C#, F# and VB.NET all compile to some kind of intermediate code instead of machine-specific code. It doesn't matter if it then runs on VM, the language is still compiled. There is also option to compile to some other language, like C. C is actually quite popular compilation target and many tools do it. And finally, you could use some tool or library to do the hard work of producing machine code for you. there is for example LLVM which can reduce effort needed to create a standalone compiler.

Also, your edit doesn't make any sense. It is like asking "Does every engineer need to understand how engine works? And I'm asking about engineers working on engines." If you are working on a program or library that emits a machine code, then you have to understand it. The point is, you don't have to do such a thing when writing compiler. Many people did it before you, so you need to have serious reason to do it again.


答:
Classically a compiler has three parts: lexical analysis, parsing, and code generation. Lexical analysis breaks up the text of the program into language keywords, names, and values. Parsing figures how the tokens that come from the lexical analysis are combined in syntactically correct statements for the language. Code generation takes the data structures produced by the parser, and translates them into machine code or some other representation. Nowadays the lexical analysis and parsing may be combined into a single step.

Clearly the person writing the code generator has to understand the target machine code at a very deep level, including instruction sets, processor pipelines and cache behavior. Otherwise the programs produced by the compiler would be slow and inefficient. They very well might be able to read and write machine code as represented by octal or hexadecimal numbers, but they'll generally write functions to generate the machine code, referring internally to tables of machine instructions. Theoretically the folks writing the lexer and the parser might not know anything about the generation of the machine code. In fact, some modern compilers let you plug in your own code generation routines which might emit machine code for some CPU the lexer and parser writers have never heard of.

However, in practice compiler writers at each step know a lot about different processor architectures, and that helps them design the data structures the code generation step will need.

Title: Do compiler-writers actually need to 'understand' machine code?

Body:
Might be kind of an odd question.

A guy writing a C++ compiler (or whatever non-VM language): Does he need to be able to read/write raw machine language? How does that work?

EDIT: I am specifically referring to compilers that compile to machine code, not to some other programming language.


答:
No, not at all. It is perfectly possible (and often even preferrable) for your compiler to emit assembly code instead. The assembler then takes care of creating the actual machine code.

By the way, your distinguishing of non-VM implementation vs. VM implementation is not useful.

For starters, using a VM or precompilation to machine code are just different ways to implement a language; in most cases a language can be implemented using either strategy. I actually had to use an C++ interpreter once.

Also, many VMs like the JVM both have a binary machine code and some assembler, just like an ordinary architecture.

The LLVM (which is used by the Clang compilers) deserves special mention here: It defines a VM for which instructions can be represented as either byte code, textual assembly, or a data structure which makes it very easy to emit from a compiler. So although it would be useful for debugging (and to understand what you are doing), you wouldn't even have to know about the assembly language, only about the LLVM API.

The nice thing about the LLVM is that its VM is just an abstraction, and that the byte code isn't usually interpreted, but transparently JITted instead. So it's entirely possible to write a language that's effectively compiled, without ever having to know about your CPU's instruction set.


答:
A long time ago I wrote a compiler that converted between two different shell scripts.   It went no way near machine code.

A compiler write has to understand their output, but that is often not machine code.

Most programmers will never write a compiler that outputs machine code or assembly code, but custom compilers can be very useful on lots of projects to produce other outputs.

YACC is one such compiler that does not output machine code….