答:
It sounds to me like your changes are underspecified. Say you live somewhere that doesn't have postal codes, so you don't have a postal code column in the address table. Then postal codes are introduced, or you start dealing with customers who live where there are postal codes, and you have to add this column to the table.

If the work item just says "add postal code column to address table" then yes, the export will be broken, or at least won't export postal codes. But what about the input screen that is used to enter postal codes? The report that lists all the customers and their addresses? There are tons of things that need to change when you add this column. The job of remembering those things is an important one - you shouldn't be counting on random code artifacts to "trap" developers into remembering.

When the decision is made to add a meaningful column (that is, not just some cached total or denormalized lookup or other value that doesn't belong in an export or report or on an input screen) the work items created should include ALL the changes needed - adding the column, updating the populate script, updating the tests, updating the export, the reports, the input screens and so on. These may not all be assigned to (or picked up by) the same person, but they must all get done.

Sometimes developers choose to add columns themselves as part of implementing some larger change. For example someone may have written a work item to add something to an input screen and a report, without thinking about how it is implemented. If this happens a lot, you will need to decide whether your work-item-adder needs to know implementation details (so as to be able to add all the right work items) or whether developers need to be aware that the work-item-adder sometimes leaves things out. If it's the latter then you need a culture of "don't just change the schema; stop and think about what else that affects."

If there were a lot of developers and this happened more than once, I would set up a checkin alert for the team lead or other senior person to be alerted on schema changes. That person could then look for related work items to deal with the consequences of them schema change, and if the work items were missing, could not only add them but educate whoever left them out of the plan.

Title: How to draw programmer's attentions in certain conditions?

Body:
Let's start with an example.

Let's say, I have a method called export that depends heavily on the DB schema. And by “depends heavily” I mean I know that adding a new column to a certain table often (very often) leads to the corresponding export method change (usually you should add the new field to the export data as well).

Programmers often forget to change export method since it's not really clear you should even look at this. My goal is to force programmer explicitly make a decision to determine whether he forgot to look at the export method or just don't want to add a field to the export data. And I'm looking for the design solution for this problem.

I have two ideas, but both of them have flaws.

Smart “Read all” wrapper

I can create the smart wrapper that makes sure all data is explicitly read.

Something like this:

```<code>def export():
    checker = AllReadChecker.new(table_row)

    name    = checker.get('name')
    surname = checker.get('surname')
              checker.ignore('age') # explicitly ignore the "age" field

    result = [name, surname] # or whatever

    checker.check_now() # check all is read

    return result
</code>```

So, checker asserts if table_row contains another fields that were not read. But all this thing looks kind of heavy and (maybe) affects perfomance.

“Check that method” unittest

I can just create the unittest that remembers the last table schema and fails every time the table is changed. In that case programmer would see something like “don't forget to check out the export method”. To hide the warning  programmer would (or wouldn't — that's a problem) check out export and manually (that's another problem) fix the test by adding new fields into it.

I have a few other ideas but they are too troublesome to implement or too difficult to understand (and I don't want the project to become a puzzle).

The above problem is just an example of the more wide class of problems I encounter from time to time. I want to bind some pieces of code and/or infrastructure so changing one of them immediately alerts programmer to check another one. Usually you have some simple tools like extracting common logic or writing reliable unittest, but I'm looking for the tool for more complex cases: maybe some design patterns I'm now aware of.


问:
Does class inheritance (in C#) violate the Open/Closed Principle?
I typically make all my methods private unless and until they need to be overriden by a sub-class. At that point I modify the base class to make that particular method protected virtual. Is it accurate to say that this is a violation of the "Closed to Modification" principal? If  so, that would imply that I should choose protected virtual as my default (similar to Java, in which methods are virtual by default). Is that really what the OCP recommends?

Personally, such an interpretation seems a bit daft to me, but I want to know if I am missing something.

答:
I typically make all my methods private unless and until they need to be overriden by a sub-class. At that point I modify the base class to make that particular method protected virtual

That is seldom a good tactics. When you create a class initially, you should make all methods not be exposed private. Fullstop. Those methods won't become protected later - they are typically not proper designed to be overridden later on, because when you created the method, their intended purpose was not to be an extension point. Making all of them protected virtual by default won't change that - just the fact you can technically override a method does not mean this will make any sense. Classes, which are intended to be instantiated on its own are seldom good candidates for the becoming base classes of other classes, and trying to switch their private methods to "protected" is not just a violation of the OCP, it leads most probably to bad or wrong usage of inheritance.

On the other hand, if you design an abstract class A in "top down" manner for which you know it will become a base class for classes B, C and D, because A is some kind of generalization of B, C and D, you will typically know right from the start which methods in A must be protected to be overridden by B, C, and D, so these methods are protected or public right from the start, and they are designed to be overridden.

You can create such a design also "bottom up": you start with a class B, then create a second class C, you see the commonalities in both and refactor the common methods to a common base class or common interface A  (instead of trying to make C an derivation of B, in a wrong attempt to follow the OCP). Now the methods in A which need to be overwritten in B and C are all public or protected right from the start. B and C have to be modified, of course, but B and C are not the classes which are extended - so asking for the OCP is pointless here. However, ideally A does not have to be modified later when another class D inherits from A. If that's the case, you A confirms to the OCP.

So the bottom line is: classes which follow the OCP are not created out of existing classes just by making any method "protected" - the "extension points" have to be chosen deliberately and designed for that purpose.

ContentLicense: CC BY-SA 3.0


问:
Which programming language is used to write a BIOS program?
As I understand, the BIOS code/bitstream that is held in the ROM should be generic (work alongside with multiple CPU types or ISAs). In addition, I saw mentioned on the web that it is possible to dump its code (and to "disassemble" it).

So, in which language, instruction set or machine code is it written? Doesn't it need any kind of processor to perform its operations? If so, I guess that it will use the external CPU, then how does it know the specific instruction set of the employed one?

Maybe it has an internal processor?

答:
BIOSes used to be written exclusively in assembly language, but the transition was made a long time ago to write the majority of the code in some higher level language, and leave written in assembly as few portions of it as possible, preferably only the bootstrapper, (the very first few hundreds of instructions that the CPU jumps to after a start / reset,) and whatever routines deal with specific quirks of the underlying architecture.

BIOSes were already being written primarily in C as early as the early nineties.  (I wrote a BIOS in 90% C, 10% assembly in the early nineties.)

What has also helped greatly in this direction is:

C libraries that target a specific architecture and include functions for dealing with peculiarities of that architecture, for example, functions for reading/writing bytes to/from I/O ports of the x86 architecture.  Microsoft C has always offered library functions for that kind of stuff.

C compilers that not only target a specific CPU architecture but even offer extensions to the C language that you can use in order to write code which makes use of special CPU features.  For example, the x86 architecture supports things known as interrupts, which invoke routines known as interrupt handlers, and it requires them to have special entry/exit instruction sequences.  From the very early days, Microsoft C supported special keywords that you could use to mark a function as an interrupt handler, so it could be invoked directly by a CPU interrupt, so you did not have to write any assembly for it.

Nowadays I would assume that most of the BIOS is written in C++, if not in any higher level language.

The vast majority of the code that makes up a BIOS is specific to the underlying hardware, so it does not really need to be portable: it is guaranteed that it will always run on the same type of CPU.  The CPU may evolve, but as long as it maintains backwards compatibility with previous versions, it can still run the BIOS unmodified. Plus, you can always recompile the parts of the BIOS written in C to run natively on any new CPU that comes up, if the need arises.

The reason why we write BIOSes in languages of a higher level than assembly is because it is easier to write them this way, not because they really need to be portable.

ContentLicense: CC BY-SA 4.0


问:
Motivating yourself to actually write the code after you've designed something
Does it happen only to me or is this familiar to you too?

It's like this: You have to create something; a module, a feature, an entire application... whatever. It is something interesting that you have never done before, it is challenging.

So you start to think how you are going to do it. You draw some sketches. You write some prototypes to test your ideas. You are putting different pieces together to get the complete view.

You finally end up with a design that you like, something that is simple, clear to everybody, easy maintainable... you name it. You covered every base, you thought of everything. You know that you are going to have this class and that file and that database schema. Configure this here, adapt this other thingy there etc.

But now, after everything is settled, you have to sit down and actually write the code for it. And is not challenging anymore.... Been there, done that! Writing the code now is just "formalities" and makes it look like re-iterating what you've just finished.

At my previous job I sometimes got away with it because someone else did the coding based on my specifications, but at my new gig I'm in charge of the entire process so I have to do this too ('cause I get payed to do it).

But I have a pet project I'm working on at home, after work and there is just me and no one is paying me to do it. I do the creative work and then when time comes to write it down I just don't feel like it (lets browse the web a little, see what's new on P.SE, on SO etc).

I just want to move to the next challenging thing, and then to the next, and the next...

Does this happen to you too? How do you deal with it?

How do you convince yourself to go in and write the freaking code?

I'll take any answer.

答:
If the challenge for you is in designing and not implementing, maybe you need a different motivating factor:

If it's a pet project (not for work), I actually look forward to seeing it come alive, so designing it isn't enough for me.  When you come up with your own pet projects, what's the goal?  Is it for something you need to use?  If so, you can use that as the motivation for implementing it.  To see it work.  To provide the functionality you were looking to get out of it.

Are you planning on making it available for others?  A motivating factor could be seeing them benefit from the final product.  They're not going to get the utility out of it if it's just in design mode.  And if you plan on marketing it, use the fact that nobody is going to pay for your pet project while it's stuck in design mode, as a motivating factor.

When I work on my own thing, I take a more iterative approach than I could at work -- I don't worry about all the details before generating something.  It may take longer, but 1) since it's only for me (or for someone who doesn't even know it exists in any form yet), then I have the flexibility to experiment and take my time.  2) I spend a bunch of cycles refactoring and learning better ways of doing things.  On my own dime, figuratively speaking.

Ultimately, though, isn't the real satisfaction in seeing something come to life out of thin air?  That's what does it for me.  If that doesn't do it for you, unless your motivation is the final product, then I'm not sure I understand why you want to work on the pet project at all.  If designing is what juices you, and you do that at work, you seem to already get the satisfaction you're looking for.

ContentLicense: CC BY-SA 2.5


问:
Is there a specific reason for the poor readability of regular expression syntax design?
Programmers all seem to agree that readability of code is far more important than short-syntaxed one-liners which work, but require a senior developer to interpret with any degree of accuracy - but that seems to be exactly the way regular expressions were designed. Was there a reason for this?

We all agree that selfDocumentingMethodName() is far better than e(). Why should that not apply to regular expressions as well?

It seems to me that rather than designing a syntax of one-line logic with no structural organization:

```<code>var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})(0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
</code>```

And this isn't even strict parsing of a URL!

Instead, we could make a some pipeline structure organized and readable, for a basic example:

```<code>string.regex
   .isRange('A-Z' || 'a-z')
   .followedBy('/r');
</code>```

What advantage does the extremely terse syntax of a regular expression offer other than the shortest possible operation and logic syntax? Ultimately, is there a specific technical reason for the poor readability of regular expression syntax design?

答:
I believe regular-expressions were designed to be as 'general' and simple as possible, so they can be used (roughly) the same way anywhere.

You're example of regex.isRange(..).followedBy(..) is coupled to both a specific programming language's syntax and perhaps object-oriented style (method chaining).

How would this exact 'regex' look in C for example? The code would have to be changed.

The most 'general' approach would be to define a simple concise language which can then be easily embedded in any other language without change. And that's (almost) what regex are.


问:
When is optimization not premature and therefore not evil?
"Premature optimization is root of all evil" is something almost all of us have heard/read. What I am curious what kind of optimization not premature, i.e. at every stage of software development (high level design, detailed design, high level implementation, detailed implementation etc) what is extent of optimization we can consider without it crossing over to dark side.</p>

答:
I only know of one way to answer this question, and that is to get experience in performance tuning. That means - write programs, and after they are written, find speedups in them, and do it iteratively. Here's one example.

Here's the mistake most people make: They try to optimize the program before actually running it. If they have taken a course in programming (from a professor who doesn't actually have much practical experience) they will have big-O colored glasses, and they will think that's what it's all about.
It's all the same problem, prior optimization.**

Somebody said: First make it right, Then make it fast.
They were right.

But now for the kicker: If you have done this a few times, you recognize the silly things you earlier did that cause speed problems, so you instinctively avoid them.
(Things like making your class structure too heavy, getting swamped with notifications, confusing size of function calls with their time cost, the list goes on and on ...)
You instinctively avoid these, but guess what it looks like to the less-experienced: premature optimization!

So these silly debates go on and on :)

** Another thing they say is you don't have to worry about it any more, because compilers are so good, and machines are so fast nowadays.
(KIWI - Kill It With Iron.)
There are no exponential hardware or system speedups (done by very smart hard-working engineers) that can possibly compensate for exponential software slowdowns (done by programmers who think this way).


问:
Who is responsible for setting color in MVVM?
I have an iOS app where after exceeding a certain limit, part of the user interface changes a color to alert the user. I'm using MVVM to accomplish this and division of labor looks like this:

Model - fetch limit value and from the storage

View Model - compare limit with current value and pass bool (over/under limit flag)

View - pick a color based on the limit flag and set it on required views (this work is done in a controller).

I started to wonder if selecting color for the views isn't a view model's job. If you divide MVVM to M(VC)VM, maybe it can be fitted into a UIView's subclass instead of UIViewController's. Where is the place for selecting an actual color? And why?

答:
The View is the place which has intimate knowledge of your graphical runtime environment, of how color is expressed in it, and even of the fact that you are actually running within a graphical runtime environment and not as part of some unit test. (Assuming that you unit-test your Model, and your View Model, but not your View.)

So, I would think that the View is the best place for converting the "over the limit" flag to a color, so that your unit tests only need to ensure that under the right conditions, the "over-the-limit" flag is raised in your View Model.

On the other hand, if you want to give the user the ability to choose the color to display in case of an "over the limit" situation, then the color becomes part of your Model.

However, even in that case, the color chosen by the user in the event of an "over-the-limit" situation can be presented by the View Model as a completely separate entity from the "over-the-limit" flag itself, and in a completely abstracted fashion, (say, a string containing a color name,) rather than as the actual RGBA value which your runtime environment requires.

Let the View read from the View Model the "over-the-limit" flag, and if it is set, then let it also read the abstracted color which is to be displayed in this situation, and let it worry about converting the abstracted color to an RGBA value.


问:
Handling and managing error codes
I'm looking for examples of creating, handling and managing error numbers/codes.

To understand what I'm takling about, let's take example scenario:
(EU - end user, IT - it helpdesk)

```<code>EU: - (calls IT) something's wrong
IT: - what happened?
EU: - it says "cannot create xyz"
IT: - what have you done?
EU: - ummm....
(conversation continues for another gazillion years)
</code>```

... and exception that produces message cannot create xyz is being thrown in dozen places in whole system, so IT guy doesn't know where to look for.

Another approach (which I really like and would like to use) is for example:

Now, when EU calls IT, whole conversation looks like this:

```<code>EU: - I have error 1004
IT: - ok, thanks, we'll take a look
</code>```

Having error code, IT guy instantly knows where to look for error. He doesn't need to ask EU to provide loads of misleading details, he just can sit down and work or if he knows why, explain that this is intentional error because EU did something wrong.

Sounds like flowers and donuts, doesn't it?

But what are best practices to achieve this behaviour?

Let's assume that this is Java and we're building app from scratch.
What I know so far is that I cannot get error codes from database, because if Exception is being thrown, I cannot rely on external sources.

This leads to problems with teamwork. Let's say that John, Paul and Adam assumed that they will use error codes while writing their app, and they will generate errors incrementaly. I see possible collision, when John wants to mark exception message in code using number #256, but Paul doesn't know about that and creates his own exception, also with #256 related it, and uses this exception in few dozens of places in app. At the end of the day noone knows what error #256 really means.

So maybe there's another approach - use small but handy one-table web app that will handle generating error numbers, so John, Paul and Adam just can click "generate" when they want new unique error number?

Above elaborate also leads to another question - what are best practices to set error codes? In exceptions themself, like this:

```<code>public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super("Error #256 - xyz is forbidden"); }
  public FooException(String message, Throwable cause) { super("Error #256 - xyz is forbidden", cause); }
  public FooException(Throwable cause) { super(cause); }
}
</code>```

or:

```<code>try{
    (some stuff)
} catch (FooException ex){
    System.out.println("Error #256 - you cannot do xyz in here");
}
</code>```

I suspect second option is better, because it indicates unique, specific place in code in whole project, but this looks harder to manage.

Any thoughts? Any practices? Advices? Thanks.

答:
Go ahead and use error numbers if you want to use a reference table, but I'd recommend a different approach.

In your message tell the user:

What error occurred.  If it's an intentional thrown error due to user input, tell them what they did wrong in the message.

The program name, class name and method name where the error occurred so a programmer or support person can find the code.

If possible, suggest actions the user can take to correct the problem.

Just using error codes is too cryptic for a user friendly program and not as easy for a support person to decode as you might think.  Inevitably, the error will occur when the support rep is away from his/her desk (on call at home) or they will have misplaced the error code list.

Which message would you rather troubleshoot?

"Program failure! Error 0x80020018"

or
"MyProgramName error 0X80020018 occurred in module SendMail, the email address is not valid.   Please check that the email address you entered is valid and try again."

Title: Handling and managing error codes


问:
What is the bug workflow on your agile/Scrum team?
What is the bug workflow on your agile/Scrum team?

Here is ours:
- If the bug is related to a story in the current sprint, we fix it.
- If the bug is not related to a story in the current sprint and it is not critical, it is sent to the product owner for prioritization.
- If the bug is not related to a story in the sprint and it is critical, we fix it.

答:
I think the best way to approach this is to determine what you actually want to consider a Bug first.

A lot of developers will not consider something that isn't working as intended that they are currently working on as not a bug, because it is honestly not a bug. If you are currently working on something and it still has defects then the specific bug isn't actually complete so there isn't an actual defect. The inverse applies to completed work, if you have determined that something is complete and ready for testing/release/production and you later find a defect in the code or use then you definitely have a bug.

My company uses the following methodology to determine when a bug should be corrected:

If the bug is critical then it is added to the current sprint related to that product, at the appropriate priority. Typically we plan in approximately 10% extra time to allow for this into a sprint, as well as having the extra things that we don't actually plan on completing but if we have no bugs or something was completed faster than we expected we can then complete.

If a bug isn't critical then we simply add it to the backlog and normally complete it in the next sprint.

why this is the ideal flow there is some obvious leak to it, and sometimes things that aren't 'critical' from a programming perspective may need to be completed immediately if management decides that it needs to be completed earlier than we think it should be completed.

In an aside I think that the best thing to do is to pick a structure and then stick with it. Some of the biggest losses to productivity start occurring when you start doing things without structure. Once you start degrading your structure it is very easy for it to go all downhill.

That may have overly answered your question, but those are just my thoughts on how these things should be handled.


答:
What I've noticed is that there is a huge disconnect between what is needed for diagnosing a problem and what you display to the user. Error codes and exceptions are simply start points that give you a suggestion of what might have gone wrong.

For example: an error saying a file upload failed could be because the network was down, disconnected, rejected, data corrupted, the directory on the server could not be created, the file already existed, the file existed and was readonly, the directory was secured against the user writing to it, the filename being uploaded was too long, or even that the fancy customer SAN array thing took 40 seconds to respond and the network upload timed out! (damn you EMC and the customer that mis-configured your storage array!)

The problem here is that while you want to tell the user "failed to upload", you do not really want to create exceptions or error code for all the possibly permutations of what might have gone wrong - particularly in the last case where the file appears to have been written correctly when you go to look. I've always found that a decent logging mechanism is worth its weight, when an error occurs that cannot simply be retried by the user, the logs are going to be viewed to see what went on. The logs will often not tell you the exact error but should give you enough tracing information (including error codes written in them) for you to diagnose the problems with the data or environment that led to the error condition.

As for exceptions v error codes, I prefer the latter, even if they are thrown as exceptions! If you do use error codes you will need to provide a mechanism to convert them to text descriptions, a set of error codes per module (or class) makes sense to avoid the need to grab a new unique code, and keeps error codes from a module sequential.

Title: Handling and managing error codes

Body:
I'm looking for examples of creating, handling and managing error numbers/codes.

To understand what I'm takling about, let's take example scenario:
(EU - end user, IT - it helpdesk)

```<code>EU: - (calls IT) something's wrong
IT: - what happened?
EU: - it says "cannot create xyz"
IT: - what have you done?
EU: - ummm....
(conversation continues for another gazillion years)
</code>```

... and exception that produces message cannot create xyz is being thrown in dozen places in whole system, so IT guy doesn't know where to look for.

Another approach (which I really like and would like to use) is for example:

Now, when EU calls IT, whole conversation looks like this:

```<code>EU: - I have error 1004
IT: - ok, thanks, we'll take a look
</code>```

Having error code, IT guy instantly knows where to look for error. He doesn't need to ask EU to provide loads of misleading details, he just can sit down and work or if he knows why, explain that this is intentional error because EU did something wrong.

Sounds like flowers and donuts, doesn't it?

But what are best practices to achieve this behaviour?

Let's assume that this is Java and we're building app from scratch.
What I know so far is that I cannot get error codes from database, because if Exception is being thrown, I cannot rely on external sources.

This leads to problems with teamwork. Let's say that John, Paul and Adam assumed that they will use error codes while writing their app, and they will generate errors incrementaly. I see possible collision, when John wants to mark exception message in code using number #256, but Paul doesn't know about that and creates his own exception, also with #256 related it, and uses this exception in few dozens of places in app. At the end of the day noone knows what error #256 really means.

So maybe there's another approach - use small but handy one-table web app that will handle generating error numbers, so John, Paul and Adam just can click "generate" when they want new unique error number?

Above elaborate also leads to another question - what are best practices to set error codes? In exceptions themself, like this:

```<code>public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super("Error #256 - xyz is forbidden"); }
  public FooException(String message, Throwable cause) { super("Error #256 - xyz is forbidden", cause); }
  public FooException(Throwable cause) { super(cause); }
}
</code>```

or:

```<code>try{
    (some stuff)
} catch (FooException ex){
    System.out.println("Error #256 - you cannot do xyz in here");
}
</code>```

I suspect second option is better, because it indicates unique, specific place in code in whole project, but this looks harder to manage.

Any thoughts? Any practices? Advices? Thanks.


问:
Database constraints for a recursive folders structure
In an application, I have a recursive folder structure (like folders in OS X or Windows file system).

Each folder can contain three kind of things:

Other folders (hence the recursive structure)

Employees

Tasks

Here are the simplified models for those elements:

```<code>class Folder:
    parent_folder: Folder

class Employee:
    folder: Folder
    task: Task

class Task:
    folder: Folder
    name: StringField()
</code>```

As you may understand from the models above, each Employee can be attributed a single Task.

The pain point is that an employee can only have a task which is located in this employee’s tree of folders (aka be part of its path). Let me illustrate this with some examples:

```<code>Valid:
    Employee in /MyFolder/OtherFolder
    Task in /MyFolder

Valid:
    Employee in /MyFolder/OtherFolder
    Task in /MyFolder/OtherFolder

Invalid:
    Employee in /MyFolder
    Task in /MyFolder/OtherFolder # not in Employee’s path

Invalid:
    Employee in /MyFolder
    Task in /RandomFolder # not in Employee’s path
</code>```

Desired behaviour

If an Employee or a Task is moved so that an Employee's Task becomes unaccessible to said Employee, I’d like to have the relation between the two nullified, so that the Employee becomes task-free.

If, at any time, in the database, an Employee has a Task for which he doesn’t have access (is not in its path), the database should be considered corrupted.

Questions

Is it possible to implement this behaviour at the database level, so that it would work like Foreign Key constraints with nullifying cascading rules, for example?

If it's not possible at the database level, can you think of a way to implement this at the application level and keeping the database integrity at any time?

Subsidiary question: should we reconsider our data structure and implement one which would be more suitable for this particular problem?

What we tried so far (and the reasons why it didn’t work):

Implement this behaviour at the application level - doesn’t work because we can’t guarantee the integrity of the database in this case

Use Views or Common Table Expressions (CTE) - doesn’t work because Foreign Keys can’t be used within Views or CTE

Use a separate table for the relations - doesn’t work because of the recursive aspect of the structure which prevents us to use FK constraints for this goal

A note on the stack: PostgreSQL - SQLAlchemy

To keep this question (relatively) short, I simplified the problem and omitted a certain number of elements - please ask if you need more details

Edit: I should have mentioned that retrieving an object's folder from pure SQL is actually much less trivial than in my example

答:
If the database is under control of the application (not modified by anything else), do it at the application level, not the database level.

In theory you could do it with triggers, but I don't think you should.
Checking the validity of such a structure requires computationally complex queries, and there is significant danger that this will have a negative impact on performance and scalability.  It is a possibility, but this isn't a good design to choose without a clear need for it (and I don't see one given the information in the question).

I don't understand the concern "we can't guarantee the integrity of the database".  Why not?  If the database can only be modified via the application, and you ensure (and thoroughly test) that every action the application performs is done correctly and doesn't result in an invalid state, then you should not have a problem with database integrity.  And this sort of testing is what you need anyway to ensure that your program is robust.

If you need additional assurance for some reason (most likely because the database can be modified outside the application), you might consider triggers.  However, if that is not performant, you could create some custom code that performs an integrity check on demand. Or you might consider providing an API for others who need to modify the database, rather than allowing the database to be modified directly


答:
This is perfectly possible with triggers, and if you must ensure integrity at an application-independent level, this is possibly your best shot. From this example you can see that recursion is possible in POSTGRESQL stored procedures, so traversing the tree should not be too hard to be implemented.

Of course, you may have to implement "AFTER INSERT", "AFTER UPDATE" and "AFTER DELETE" triggers for tables Employee and Task, and to make this bullet proof without significant performance hit you have to be careful, but to my experience, these are solvable problems.

Title: Database constraints for a recursive folders structure

Body:
In an application, I have a recursive folder structure (like folders in OS X or Windows file system).

Each folder can contain three kind of things:

Other folders (hence the recursive structure)

Employees

Tasks

Here are the simplified models for those elements:

```<code>class Folder:
    parent_folder: Folder

class Employee:
    folder: Folder
    task: Task

class Task:
    folder: Folder
    name: StringField()
</code>```

As you may understand from the models above, each Employee can be attributed a single Task.

The pain point is that an employee can only have a task which is located in this employee’s tree of folders (aka be part of its path). Let me illustrate this with some examples:

```<code>Valid:
    Employee in /MyFolder/OtherFolder
    Task in /MyFolder

Valid:
    Employee in /MyFolder/OtherFolder
    Task in /MyFolder/OtherFolder

Invalid:
    Employee in /MyFolder
    Task in /MyFolder/OtherFolder # not in Employee’s path

Invalid:
    Employee in /MyFolder
    Task in /RandomFolder # not in Employee’s path
</code>```

Desired behaviour

If an Employee or a Task is moved so that an Employee's Task becomes unaccessible to said Employee, I’d like to have the relation between the two nullified, so that the Employee becomes task-free.

If, at any time, in the database, an Employee has a Task for which he doesn’t have access (is not in its path), the database should be considered corrupted.

Questions

Is it possible to implement this behaviour at the database level, so that it would work like Foreign Key constraints with nullifying cascading rules, for example?

If it's not possible at the database level, can you think of a way to implement this at the application level and keeping the database integrity at any time?

Subsidiary question: should we reconsider our data structure and implement one which would be more suitable for this particular problem?

What we tried so far (and the reasons why it didn’t work):

Implement this behaviour at the application level - doesn’t work because we can’t guarantee the integrity of the database in this case

Use Views or Common Table Expressions (CTE) - doesn’t work because Foreign Keys can’t be used within Views or CTE

Use a separate table for the relations - doesn’t work because of the recursive aspect of the structure which prevents us to use FK constraints for this goal

A note on the stack: PostgreSQL - SQLAlchemy

To keep this question (relatively) short, I simplified the problem and omitted a certain number of elements - please ask if you need more details

Edit: I should have mentioned that retrieving an object's folder from pure SQL is actually much less trivial than in my example


答:
From the point of view of the problem that you are facing, a message like "Cannot create xyz" is absolutely no different from "Run-time error '1004'". If the "Cannot create xyz" exception is being thrown in a dozen places all over your system, so can error "Run-time error '1004'" be issued in a dozen places all over your system. Replacing one with the other does not help you in any way.

And generally, exceptions are always in a far better position to help than error codes ever will.

You have a number of options.

If by any chance it is very easy for you to collect the log files from the field, then you can generate a new unique error number each time an error occurs, and store it in the log together with the exception, so that you know where to look in the log file.  This way, you present your user with a message like "ERROR 2624501; Please contact technical support" but the error number is always different, even if the type of error is the same.

If collecting log files is not easy, then you need to have a means of uniquely identifying every single place which may throw an exception.  The way this is traditionally done is by means of release number, source file name, and line number.

Every exception that you throw contains a stack trace, and the topmost entry of the stack trace should contain the file name and line number, so you can report those.  (Of course, the exception may have been caused by another exception, so you may first have to traverse the cause chain of exceptions first.)

The release version is necessary because you are likely to be making a release to the users and then continuing to work on your source code, so the code changes, so a particular line which throws an exception on the end-user's release may not be throwing any exception on the code that you have in front of you, so you may need to look for a specific version of the source file in your Version Control System.

If you do not want to be divulging to your end users highly technical information such as source file names, then you may need to obfuscate them by associating each source file name to yet another number, and only showing your end user numbers.

You could even automate the validation of this procedure, so as to ensure that no two classes have the same number.  You can have each class which may throw an exception register with a "central obfuscating authority" object, which makes sure that the unique number of each class is really unique, so if it is not, then it will break during a test run and not in the field.

Unfortunately, reporting just the place where the error occurred is not very useful, because for example you may have one central function which opens all your files, so an exception thrown by that function does not tell you much.  Which subsystem tried to open that file?  For what purpose?  What was the filename?  That's why complete exception stack traces are useful.

The method that I would recommend is a bit involved, but it is the best.

Take your entire exception stack trace in a string, including all exception messages and all causal exceptions, and apply ZIP compression to it to make it small.  Then, apply base-64 encoding to it to get a string which can be copied and pasted into an email.  Add a "more info" box to your error dialogs, which presents this weird long sequence of characters to your end users, asking them to email it to you.  This way, you can reverse the encoding procedure, (base-64 decode, then unZIP,) and you can have all of the pertinent information in your hands.

Title: Handling and managing error codes


问:
Get license information for all used NuGet packages
To keep our house in order, I want to automatically assemble licenses for project dependencies in our documentation, rather than having to add them manually.

Does anybody know a simple way to traverse programmatically a set of CSPROJ files and extract the license information for the referenced packages as a link or string?

答:
I managed to get the licence information using the following command:</p>

```<code>@( @(Get-Project -All | ForEach-Object { Get-Package -ProjectName $_.ProjectName }) | Select Id -Unique ) | ForEach-Object { $pkg = $_ ;$pkgId = $_.Id ; if ($pkgId -notlike  'microsoft*'){ $url = Open-PackagePage $pkgId -License -WhatIf -PassThru; Write-Host "$pkgId $url"}}
</code>```

Body:
I managed to get the licence information using the following command:

@( @(Get-Project -All | ForEach-Object { Get-Package -ProjectName $_.ProjectName }) | Select Id -Unique ) | ForEach-Object { $pkg = $_ ;$pkgId = $_.Id ; if ($pkgId -notlike  'microsoft*'){ $url = Open-PackagePage $pkgId -License -WhatIf -PassThru; Write-Host "$pkgId $url"}}


问:
Should the View not perform validation?
I was reading "In MVC should a model handle validation?" because I was curious about where validation logic should go in an MVC website. One line in the top answer goes like this: "controllers should handle validation, models should handle verification."

I liked that, but it left me wondering why we wouldn't do data validation in the View, for several reasons:

Views typically have robust validation support (JS libraries, HTML5 tags)

Views can validate locally, reducing network IO

UI is already designed with data-type in mind (calendars for dates, spinners for numbers), making it one small step from validation

Validating in more than one place is contrary to MVC's concept of isolating responsibilities, so "do it in both" seems inappropriate. Is doing data validation only in the controller truly the dominant approach?

答:
I don't think there is a single place where you can say all the validation should go. This is because we have a few different competing programming strategies working together in a standard asp.net mvc website.

Firstly we have the idea of separating the domain logic into models, the 'action' logic into controllers and the display into a View. This is based on the idea the all the logic will take place on the server with the browser simply providing a render of the view.

Then, we extend the View by using client side javascript. This is so advanced these days that the 'one page website' idea with Jquery/knockout/angular is common practice.

This practice can be equivalent to writing a whole client side application which itself implements a MVC or MVVM pattern. We denigrate the View to a Data Transfer Object and the Controller to a service endpoint. Moving all business and UI logic into the client.

This can give a better user experience, but you are having to trust an essentially untrustworthy client. So you still need to carry out validation logic on the server, regardless of how well your client pre-validates its requests.

Also, we often have validation requirements which cant be carried out by the client. eg. 'is my new Id unique?'

Any application you create with the goal of giving the best experience/performance will necessarily borrow for multiple programming paradigms and make compromises on them to achieve its goal.

Title: Should the View not perform validation?


问:
What is the best design principle to add behavior in future to your API?
I'm designing an API. And, this API will be used by client.

Currently I've two behaviors in a class definition. To illustrate the scenario, sample implementation looks like the following-

```<code>public class Session {

    // instance field declaration goes here

    void connect() {
        // method definition goes here
    }

    void submitJob() {
        // method definition goes here
    }
}
</code>```

I want to add more behaviors to this class definition in future to offer more functionality. And, I don't want the client code to change (i.e. My client will keep instantiating this single class and invoke behaviors as per their need.) But, I don't want to modify this class definition. Is there any design pattern and/or principle that can be followed to add behaviors to achieve the goal?

Note: I do not intend to add behaviors at runtime.

Appreciate any explanation and/or guides.

答: Just follow the SOLID design principles given by Uncle Bob along with OOP fundamental e.g. low coupling between module, high cohesion etc. </p>


问:
Big O Nested For Loop Breakdown
I understand how to get a general picture of the big O of a nested loop, but what would be the operations for each loop in a nested for loop?

If we have:

```<code>for(int i=0; i<n; i++)
{
    for(int j=i+1; j<1000; j++)
    {
        do something of constant time;
    }
}
</code>```

How exactly would we get T(N)? The outer for loop would be n operations, the inner would be 1000(n-1) and the inside would just be c is that right?

So T(n)=cn(1000(n-1)) is that right?

答: It is O(1), not linear, because the inner loop will only be executed when n is less than 1000, so for big n (ex: 1,001 and 100,000,000) it will be the same. Like you said, it might be linear till 1000, but it is constant after that....</p>

Title: Big O Nested For Loop Breakdown


答:
Validating in more than one place is contrary to MVC's concept of isolating responsibilities, so "do it in both" seems inappropriate.

Could there be multiple validation responsibilities to consider here?  As you said in your #3:

UI is already designed with data-type in mind (calendars for dates, spinners for numbers), making it one small step from validation

So maybe it's:

View: Validate input type, format, requirement...basic user input validation that has nothing to do with the business logic.  Catch all this fluffy stuff before we generate network traffic by making a request of the server.

Model: Validate the business concerns of the data.  Is that be a legal value according to the business rules?  Yes, it's a numeric value (we ensured that in the view), but does it make sense?

Just a thought.

Title: Should the View not perform validation?

Body:
I was reading "In MVC should a model handle validation?" because I was curious about where validation logic should go in an MVC website. One line in the top answer goes like this: "controllers should handle validation, models should handle verification."

I liked that, but it left me wondering why we wouldn't do data validation in the View, for several reasons:

Views typically have robust validation support (JS libraries, HTML5 tags)

Views can validate locally, reducing network IO

UI is already designed with data-type in mind (calendars for dates, spinners for numbers), making it one small step from validation

Validating in more than one place is contrary to MVC's concept of isolating responsibilities, so "do it in both" seems inappropriate. Is doing data validation only in the controller truly the dominant approach?


答:
The actual BIOS for a computer would be written in some language (probably C or assembly) that is compiled to architecture dependent binary code; this code can't run on any other architecture (and arguably doesn't really need to, as it is already very specific to the machine with which it is shipped).

But are you possibly thinking about Option ROMs (which are sometimes called BIOSes, as in "Video BIOS" for a GPU option ROM)?

For actual, legacy BIOS compatible option ROMs, they would probably be ISA dependent executable code (again generated by any language that can be compiled to target the desired architecture); PCI also allows including code for multiple ISAs and allows the host to select the appropriate binary image during the boot process.

For UEFI compatible option ROMs, there is also an architecture-independent byte code format that can be run on different architectures, but ISA-dependent code can also still be used.

Title: Which programming language is used to write a BIOS program?

Body:
As I understand, the BIOS code/bitstream that is held in the ROM should be generic (work alongside with multiple CPU types or ISAs). In addition, I saw mentioned on the web that it is possible to dump its code (and to "disassemble" it).

So, in which language, instruction set or machine code is it written? Doesn't it need any kind of processor to perform its operations? If so, I guess that it will use the external CPU, then how does it know the specific instruction set of the employed one?

Maybe it has an internal processor?


答:
I am going to assume you need validation for persistence.

Not only View, but Model should not handle validation either. During my days in IT I realized DDD is one of the ways to ensure you are actually doing things correctly, ie. classes are actually responsible for what they should be.

When following Domain-Driven design, your models include your business logic, and that is it. But they do not include validation, why not?

Let's assume you are already as far that you are using Data Mapper instead of Active Record to persist your domain layer. But still, you want models to be validated, so you add the validation to your Model.

```<code>interface Validation
{
    public function validate();
}

class ConcreteModel extends MyModel implements Validation
{
    public function validate() { // the validation logic goes here }
}
</code>```

The validation logic ensures, you can correctly insert the model into your MySQL database... A few months go by and you decide, you wanna store your Models in noSQL databases as well, databases, which require different validation rules than MySQL.

But you have a problem, you have only 1 validation method, but need to validate a Model in 2 different ways.

The models should do what they are responsible to do, they should take care of your business logic and do it well. Validation is tied to persistence, not business logic, hence validation does not belong to a model.

You should create Validators instead, which will take a model to validate in their constructor as a parameter, implement the Validation interface and use these Validators to validate your objects.

```<code>interface Validation
{
    public function validate();
}

class MySQLConcreteModelValidator implements Validation
{
    public function __construct(ConcreteModel $model) { }

    public function validate()
    {
        // you validate your model here
    }
}

class RedisConcreteModelValidator implements Validation
{
    public function __construct(ConcreteModel $model) { }

    public function validate()
    {
        // you validate your model with different set of rules here
    }
}
</code>```

If at any time in the future decide you want to add another validation method for another persistence layer (because you decided Redis and MySQL are not the way to go anymore), you will just create another Validator and use your IoC container to get the right instance based on your config.

Title: Should the View not perform validation?

Body:
I am going to assume you need validation for persistence.

Not only View, but Model should not handle validation either. During my days in IT I realized DDD is one of the ways to ensure you are actually doing things correctly, ie. classes are actually responsible for what they should be.

When following Domain-Driven design, your models include your business logic, and that is it. But they do not include validation, why not?

Let's assume you are already as far that you are using Data Mapper instead of Active Record to persist your domain layer. But still, you want models to be validated, so you add the validation to your Model.

interface Validation
{
    public function validate();
}

class ConcreteModel extends MyModel implements Validation
{
    public function validate() { // the validation logic goes here }
}

The validation logic ensures, you can correctly insert the model into your MySQL database... A few months go by and you decide, you wanna store your Models in noSQL databases as well, databases, which require different validation rules than MySQL.

But you have a problem, you have only 1 validation method, but need to validate a Model in 2 different ways.

The models should do what they are responsible to do, they should take care of your business logic and do it well. Validation is tied to persistence, not business logic, hence validation does not belong to a model.

You should create Validators instead, which will take a model to validate in their constructor as a parameter, implement the Validation interface and use these Validators to validate your objects.

interface Validation
{
    public function validate();
}

class MySQLConcreteModelValidator implements Validation
{
    public function __construct(ConcreteModel $model) { }

    public function validate()
    {
        // you validate your model here
    }
}

class RedisConcreteModelValidator implements Validation
{
    public function __construct(ConcreteModel $model) { }

    public function validate()
    {
        // you validate your model with different set of rules here
    }
}

If at any time in the future decide you want to add another validation method for another persistence layer (because you decided Redis and MySQL are not the way to go anymore), you will just create another Validator and use your IoC container to get the right instance based on your config.


问:
Is TCP still considered siginificant overhead compared to UDP?
I'm working on a distributed application for a graduate class I'm taking. There has been much discussion around implementing a way to maintain peer connection health statuses. Think Gossip. One of the primary themes for this project has been how we should rely on UDP communication to overcome the "excessive" bandwidth usage of TCP (wrt maintaining these lists of connection status between peers).

I don't know that I agree with this stance though. To me, the primary advantage of TCP isn't the reliability of the connection, but instead the congestion control it offers. It seems more likely that TCP connections between hosts is actually lighterweight than UDP because you get reliability, congestion control, and built-in connection failure notifications.

One potential scenario that could make adequate use of UDP packets is a backup mechanism for detecting link failures (which is what I've started to implement, though I'm not positive this is the right approach). The idea being that our primary connection to peers is via a TCP socket, whith built-in failure detection, but if we were to miss the disconnect message from this link, we could fall back on a gossipy-stle peer list we received via UDP from other hosts.

Am I looking at this all wrong? Keep in mind that this question is specific to handling peer connections and failures in a distributed application, across multiple nodes.

答:
Once upon a time, there was a great war being waged between two mighty armies, the CISCites and the RISCites.  The men of RISC believed that their forces were mightier, for their instruction sets were simpler.  The lumbering CISCs, they said, had to have a heavy translation layer in between the instruction set and the actual execution, in which instructions were reduced from CISC form to a much simpler RISC-like form anyway, so simply going with RISC to begin with would eliminate this overhead and result in a much more performant system.

The CISCites countered that their system was simpler to use, because their instructions were semantically more powerful.

Both of these claims were objectively true.  But in the end, something interesting happened: the world kept turning, and so did Moore's Law.  The cost of the CISC-translation overhead was a fixed cost, which became smaller and smaller with each iteration of faster hardware.  Meanwhile, RISC did not become any easier to use.  Today, CISC has essentially taken over the world.

A wise man should be able to see how a parallel to the UDP/TCP situation quite easily presents itself...


问:
Await state async
For speed we sometimes return response to consumer before state is saved in DB. Sometimes (Mostly for our automated consumers) this can break because the want to make actions on the saved data before it is saved. I wrote this little helper

```<code>public async Task<TEntity> GetWithRetry<TEntity>(Expression<Func<TEntity, bool>> predicate, string errorOnTimeout) where TEntity : class
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    do
    {
        var entity = await _context.DbSet<TEntity>().FirstOrDefaultAsync(predicate);
        if(entity == null)
            await Task.Delay(100);
        else
            return entity;
    } while(stopwatch.Elapsed < TimeSpan.FromSeconds(1000));

    throw new Exception(errorOnTimeout);
}
</code>```

Used like

```<code>var existingBooking = await GetWithRetry<Booking>(b => b.BookingKey == confirmCommand.BookingKey, "Booking key not found");
</code>```

Any pitfalls? Task.Delay should scale well since it returns the thread to the pool, and if the data exists in DB the first time around it should not give much more overhead than an extra wrapped task?

This is the current version of the code:

```<code>public async Task<TEntity> FirstAsync<TEntity>(Expression<Func<TEntity, bool>> predicate, string errorOnTimeout, TimeSpan? timeout = null) where TEntity : class
{
    var entity = await FirstAsyncOrDefault(predicate, timeout);
    if(entity != null) return entity;

    throw new Exception(errorOnTimeout);
}

public async Task<TEntity> FirstOrDefaultAsync<TEntity>(Expression<Func<TEntity, bool>> predicate, TimeSpan? timeout = null) where TEntity : class
{
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    if(timeout == null)
        timeout = TimeSpan.FromSeconds(1);

    do
    {
        var entity = await DbSet<TEntity>().FirstOrDefaultAsync(predicate);
        if(entity != null) return entity;

        await Task.Delay(100);

    } while(stopwatch.Elapsed < timeout);

    return null;
}
</code>```

答:
If you just want retries with timeout, you can use a for loop instead of Stopwatch.

```<code>const int MaxWaitTime = 1000; //ms
const int SleepTime = 100; //ms

public async Task<TEntity> GetWithRetry<TEntity>(Expression<Func<TEntity, bool>> predicate)
    where TEntity : class
{
    TEntity entity = null;
    // run while under wait time and entity is null
    for (var i = 0; i < MaxWaitTime && entity == null; i += SleepTime)
    {
        // only delay after first attempt
        if (i != 0) await Task.Delay(SleepTime);

        entity = await _context.DbSet<TEntity>().FirstOrDefaultAsync(predicate);
    }
    // I'd let the caller decide whether to throw on null here
    return entity;
}
</code>```

But

Seems like a better solution would be to add a call for your customers that only completes when the data is written. Understanding that blocking for IO is a performance problem, don't! Try returning a Task, perhaps with TaskCompletionSource<T>. Then you can run the operation asynchronously without blocking and have the server wake back up to complete the call when the Task completes.

Example batching scenario:

```<code>// api method
public async Task DoSomethingAsync(...)
{
    // using bool as dummy type, not really returning result
    var notifySource = new TaskCompletionSource<bool>();

    // pass into your data infrastructure
    // returns without performing save
    MyDatabase.AddToWriteBatch(..., notifySource);

    // wait for the task to complete
    await notifySource.Task;
}
</code>```

When your data infrastructure gets around to saving the data, it notifies the caller(s) of completion:

```<code>public void Process(Batch batch) {
    ...
    // call to database
    Database.BatchWrite(batch.DataCollection);
    foreach (var taskSource in batch.TaskSources)
        taskSource.SetResult(true); // this will trigger Task completion
}
</code>```

This way, you still are not blocking for IO on the API call. But you can offer the customer a way to be sure their write is committed before performing other operations.

Or

You could use the TaskCompletionSource<TEntity> for reads, and place the reads in the same queue with writes, so that the reads are guaranteed to occur after writes.

Title: Await state async

Body:
If you just want retries with timeout, you can use a for loop instead of Stopwatch.

const int MaxWaitTime = 1000; //ms
const int SleepTime = 100; //ms

public async Task<TEntity> GetWithRetry<TEntity>(Expression<Func<TEntity, bool>> predicate)
    where TEntity : class
{
    TEntity entity = null;
    // run while under wait time and entity is null
    for (var i = 0; i < MaxWaitTime && entity == null; i += SleepTime)
    {
        // only delay after first attempt
        if (i != 0) await Task.Delay(SleepTime);

        entity = await _context.DbSet<TEntity>().FirstOrDefaultAsync(predicate);
    }
    // I'd let the caller decide whether to throw on null here
    return entity;
}

But

Seems like a better solution would be to add a call for your customers that only completes when the data is written. Understanding that blocking for IO is a performance problem, don't! Try returning a Task, perhaps with TaskCompletionSource<T>. Then you can run the operation asynchronously without blocking and have the server wake back up to complete the call when the Task completes.

Example batching scenario:

// api method
public async Task DoSomethingAsync(...)
{
    // using bool as dummy type, not really returning result
    var notifySource = new TaskCompletionSource<bool>();

    // pass into your data infrastructure
    // returns without performing save
    MyDatabase.AddToWriteBatch(..., notifySource);

    // wait for the task to complete
    await notifySource.Task;
}

When your data infrastructure gets around to saving the data, it notifies the caller(s) of completion:

public void Process(Batch batch) {
    ...
    // call to database
    Database.BatchWrite(batch.DataCollection);
    foreach (var taskSource in batch.TaskSources)
        taskSource.SetResult(true); // this will trigger Task completion
}

This way, you still are not blocking for IO on the API call. But you can offer the customer a way to be sure their write is committed before performing other operations.

Or

You could use the TaskCompletionSource<TEntity> for reads, and place the reads in the same queue with writes, so that the reads are guaranteed to occur after writes.


问:
Should I stop using the term C/C++?
I understand C and C++ are different languages but when I was learning C++ I was always told that C is a subset of C++ or C++ is C with classes. And that was quite true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general). In fact (especially when working on embedded systems) it's very likely to find code written in C++ but with a lot of parts written entirely in pure C language. Here I have several questions:

Should I stop using the term C/C++?

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern c++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)

Is there right now any collaboration between the people who makes the standards of C/C++ to keep the compatibility

If #4 is yes, such collaboration could end up in the near future with the appearance of the modern c++ (11/14/17)

I know that there already similar questions, but I'm sure that a lot of people share these questions so I'm very interested to get good answers especially for the points that have to do with the C++ tendency in the near future.

答:
I was always told that C is a subset of C++ or C++ is C with classes. And that was quiet true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general).

C has never been a subset of C++. For example C89 is not a subset of C++98.

A few examples:

the C89 identifier-list form for function parameter declaration is not supported in C++

C89 and C++98 have different types for the characters constants

C89 and C++98 have different types for string literals

logical operators yield different types in C89 and C++98 (int vs bool)

Should I stop using the term C/C++?

Yes.

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

A program is either C or C++ (if even some very basic program can compiled with either a C or a C++ compiler). What compiler are you using to compile it? It should answer your question. Harbison & Steele coined the term Clean C to designate a common subset of C and C++ but I think it was a bad idea.

EDIT: However I admit that technically you can link C and C++ objects files in a single program but OTH there are many languages that are allowed to be mixed in a single program for example Java and C++. I think using the term C/C++ program only adds to the confusion that it is written in a single language called C/C++.

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern c++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)

There are many features (example: variable length array, flexible array member, _Generic, ...) of C99 or C11 that are not supported by any C++ version.

OwnerDisplayName: redobot

Title: Should I stop using the term C/C++?

OwnerDisplayName: ouah


答:
C was never a subset of C++. The most obvious example of this is int new;.  This has been true since C89 and C++98, and the languages have only grown further from each other as new standards have come out.

Should I stop using the term C/C++

Yes

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

A source file is written in one language or the other.  A program can consist of code from multiple languages working together, or an executable produced by linking different compiled objects.  You would say the program was written in C and C++, "C/C++" is not a language.

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language

They never did. char *a = malloc(10);. C and C++ have never been fully compatible for at least as long as they've had ISO standards (I don't know all the details about the pre-standardized days).  click the links or see below for a file that is fine with C89 and up, but isn't valid under any C++ standard.

afaik no, but I don't know much about the C working group.

/* A bunch of code that compiles and runs under C89 but fails under any C++ */

/* type aliases and struct names occupy separate namespaces in C, not in C++ */
struct S { int i; };
typedef int S;

struct Outer { struct Inner { int i; } in; };
/* struct Inner will be Outer::Inner in C++ due to name scope */
struct Inner inner;

/* default return type of int in C, C++ functions need explicit return types */
g() {
    return 0;
}

/* C sees this as two declarations of the same integer,
 * C++ sees it as redefinition */
int n;
int n;

/* K&R style argument type declarations */
void h(i) int i; { }

/* struct type declaration in return type */
struct S2{int a;} j(void) { struct S2 s = {1}; return s; }

/* struct type declaration in argument, stupid and useless, but valid */
/*void dumb(struct S3{int a;} s) { } */

/* enum/int assignment */
enum E{A, B};
enum E e = 1;

void k() {
    goto label; /* C allows jumping past an initialization */
    {
        int x = 0;
label:
        x = 1;
    }
}

/* () in declaration means unspecified number of arguments in C, the definition
 * can take any number of arguments,
 * but means the same as (void) in C++  (definition below main) */
void f();

int main(void) {
    f(1); /* doesn't match declaration in C++ */
    {
        /* new is a keyword in C++ */
        int new = 0;
    }

    /* no stdio.h include results in implicit definiton in C.  However,
     * as long as a matching function is found at link-time, it's fine.
     * C++ requires a declaration for all called functions */
    puts("C is not C++");
    {
        int *ip;
        void *vp = 0;
        ip = vp; /* cast required in C++, not in C */
    }
    return 0;
}

/* matches declaration in C, not in C++ */
void f(int i) { }
```

I always feel it's worth mentioning that C is a subset of Objective-C.

Title: Should I stop using the term C/C++?

Body:
I understand C and C++ are different languages but when I was learning C++ I was always told that C is a subset of C++ or C++ is C with classes. And that was quite true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general). In fact (especially when working on embedded systems) it's very likely to find code written in C++ but with a lot of parts written entirely in pure C language. Here I have several questions:

Should I stop using the term C/C++?

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern c++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)

Is there right now any collaboration between the people who makes the standards of C/C++ to keep the compatibility

If #4 is yes, such collaboration could end up in the near future with the appearance of the modern c++ (11/14/17)

I know that there already similar questions, but I'm sure that a lot of people share these questions so I'm very interested to get good answers especially for the points that have to do with the C++ tendency in the near future.

Body:
C was never a subset of C++. The most obvious example of this is int new;.  This has been true since C89 and C++98, and the languages have only grown further from each other as new standards have come out.

Should I stop using the term C/C++

Yes

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

A source file is written in one language or the other.  A program can consist of code from multiple languages working together, or an executable produced by linking different compiled objects.  You would say the program was written in C and C++, "C/C++" is not a language.

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language

They never did. char *a = malloc(10);. C and C++ have never been fully compatible for at least as long as they've had ISO standards (I don't know all the details about the pre-standardized days).  click the links or see below for a file that is fine with C89 and up, but isn't valid under any C++ standard.

afaik no, but I don't know much about the C working group.

/* A bunch of code that compiles and runs under C89 but fails under any C++ */

/* type aliases and struct names occupy separate namespaces in C, not in C++ */
struct S { int i; };
typedef int S;

struct Outer { struct Inner { int i; } in; };
/* struct Inner will be Outer::Inner in C++ due to name scope */
struct Inner inner;

/* default return type of int in C, C++ functions need explicit return types */
g() {
    return 0;
}

/* C sees this as two declarations of the same integer,
 * C++ sees it as redefinition */
int n;
int n;

/* K&R style argument type declarations */
void h(i) int i; { }

/* struct type declaration in return type */
struct S2{int a;} j(void) { struct S2 s = {1}; return s; }

/* struct type declaration in argument, stupid and useless, but valid */
/*void dumb(struct S3{int a;} s) { } */

/* enum/int assignment */
enum E{A, B};
enum E e = 1;

void k() {
    goto label; /* C allows jumping past an initialization */
    {
        int x = 0;
label:
        x = 1;
    }
}

/* () in declaration means unspecified number of arguments in C, the definition
 * can take any number of arguments,
 * but means the same as (void) in C++  (definition below main) */
void f();

int main(void) {
    f(1); /* doesn't match declaration in C++ */
    {
        /* new is a keyword in C++ */
        int new = 0;
    }

    /* no stdio.h include results in implicit definiton in C.  However,
     * as long as a matching function is found at link-time, it's fine.
     * C++ requires a declaration for all called functions */
    puts("C is not C++");
    {
        int *ip;
        void *vp = 0;
        ip = vp; /* cast required in C++, not in C */
    }
    return 0;
}

/* matches declaration in C, not in C++ */
void f(int i) { }

I always feel it's worth mentioning that C is a subset of Objective-C.

OwnerDisplayName: xhainingx


答:
In general the SO users ask the person who is asking the question to choose a language: C or C++. Why?

There are many subtle differences between C and C++. For example, in C++, a const variable at global scope has internal linkage unless declared extern, but in C it has external linkage unless declared static. By saying "C/C++", the OP is asserting knowledge that the answer to their question is the same in both C and C++, when it very well might not be. This needlessly makes things harder for would-be answerers.

Sometimes we can spot that the code isn't valid in one language or the other (for example, implicit conversions from void* to pointer to object are not valid in C++). This is annoying. Why are you saying "C/C++" when you have a piece of code that's valid in C but not C++? Did you intend C, or is this just an error in code intended to be C++?

Sometimes the answer will be different depending on the language (for example, variable-length arrays exist in C99 but not in C++). If we don't know what language you're talking about, either we have to guess, or write an answer for both when only one will actually be useful, because you know which language you're actually using; you're just not telling us!

Sometimes the answer really is the same for both languages, but it's hard to be sure. For example, I think C and C++ have the same integer conversion rules, but in order to be really, really sure, I have to read both standards carefully. Again, this makes me do twice as much work as necessary when you probably only care about one of the languages.

Anyway, to answer your other questions:

Yes.

If you are linking together C and C++ code, it is acceptable to use both tags, but please specify which language each file is in.

There are breaking changes sometimes, but they're rare and typically limited in impact (otherwise they don't get approved). For example, auto in C++11.

I don't think they directly collaborate, but they pay attention to developments in the other language and try to avoid introducing changes that would make compatibility more difficult.

And if you really do want to know about both languages, that's fine, and you can say that in your question. When you say "C/C++", I'm really not sure what you mean, and it really looks like you're making an assumption about the two languages.

Title: Should I stop using the term C/C++?

OwnerDisplayName: Brian


答:
The most simple answer to this question is that you should never have used that term. It is a term that should not exist. It has no meaning. Every program is either C, or C++.

And that was quiet true until the appearance of C++x0, C++11 (or the
  modern C++ 11/14/17 in general).

C++98 and 03 aren't even remotely C with Classes either. Whoever taught you this doesn't know shit and you can forget them. This was never correct.

Title: Should I stop using the term C/C++?


问:
Is MVC now the only way to write PHP?
Hey... its XMAS Eve and something is bugging me... yes, I have work on my mind even when I am on holiday. The vast amount of frameworks available for PHP now use MVC. Even ASP.net has its own MVC module.

I can see the attraction of MVC, I really can and I use it frequently. The only downside that I can see is that you have to fire up the whole system to execute a page request. Depending on your task this can be a little wasteful.

So the question. In a professional environment is this the only way to use PHP nowadays or are their other design methods which have alternative benefits?

答: The thing to think about is not whether using an MVC framework is justified, it's maintainability. Sure, it may be small now, but will it always be?

Title: Is MVC now the only way to write PHP?


答:
There has to be a reason why these terms come together so often. While you should not tell your C teacher that his language is a subset of C++, there is some truth here. Others already have exposed your teacher's point of view. This is very nice (and illustrated with examples, etc.). But we don't live in an ivory tower, or a book.

Your big boss could not care less about the exact language you used. If he knows a bit about programming, just tell him you used C/C++ and it will sound like "I used a language that needs to be compiled to machine code, with DLLs and all the complicated stuff". This is the "external communication" part.

If you create a library that can be interfaced by both C and C++, you definitely want to call it a C/C++ library. Of course, someone will raise a hand and ask why you don't call this a C library that happens to have a C++ wrapper, and anyway C++ can link to C libraries so you don't need to mention it at all. Just answer: "Yes, you are right, this is a C/C++ library". This is the "internal communication" part.

If you create a lexical analyzer for C++, you'd be surprised how well it works with C. You might even not need to modify it all. This is the "if it looks like a duck, etc." part.

Etc.

The majority of C programs I have ever seen compile (and work) without modification as C++ code. Don't let a few exceptions or dogmatic (however influential) programmers fool your intuition. C and C++ are so close, and so often compatible, and so often mixed and matched together, that the term C/C++ is used. It is used because it is useful to describe these kinds of situations where it does not really matter whether you are considering C or C++, as long as it's not Java or PHP. We know it's "wrong", but we don't care, it's more useful than wrong.

It may be abused, it may be stupid, but still, I'm not sure what benefit you will get by being more pedantic than needed and refuse to communicate in terms that others understand. If you feel uneasy in some specific situation, then simply don't use the generic term C/C++, but the one relevant to the case (either C or C++).

Don't be afraid of the future. Our operating systems are written in C. Quite a lot of the C/C++ current software production happens in C++. This couple is here to stay for quite a while. Nobody has interest in one being made more incompatible with the other (quite the other way around, actually).

To be specific about your points:

1) It depends. Yes when it could lead to a confusion, when you feel uneasy, or when it's simply wrong or out of context. No when you think it's adequate.

2) N/A

3) I think no, but I have no crystal ball.

4) no idea

5) I don't think so as nothing pushes in this direction

Title: Should I stop using the term C/C++?


问:
Can one determine the creation date of an email account?
Is it possible to determine the creation date of the mail account for the address supplied within the authentication process flow; Or at least determine that the mail account was/was not created the same day as signup (or specifically after confirmation)?

A use case is to flag such accounts for closer scrutiny as part of a risk management system.

What general considerations do you think come into play in approaching this problem?

I imagine that solutions might be specific to different email providers but if I could determine this information for the major ones it's a good place to be.

Would love specific answers in any language or pseudocode assuming this is solvable within ethical principles.

Disclaimer: I have asked this question on Stack Overflow. Some nice person said that email providers would not allow it for privacy reasons. Completely acceptable, but IMHO I think that the age of an email account has little to do with personal privacy. Also there are too many smart people using the stack* forums for me to just lie down and die.

答: To 100% be sure when an account was created? No, it can't reliably be done. However, I do use a verification service for ecommerce that incorporates this. They use Rapleaf as the provided, who seem to have the largest network for this type of data. They can only tell you when a user in their network first queried that email, but I'd say they're able to find results about 70% of the time. Combined with other factors about the transaction we find that it makes for an excellent anti-fraud measure. Payment is per query, not subscription based.</p>


答:
Should I stop using the term C/C++?

Absolutely.  It is not clear what this construct is intended to express except, perhaps, confusion about what C and C++ are on behalf of the person who uses the term.

Since this confusion is such a common source of frustration, many people have become quite emotional about it and appearance of that term alone will be reason enough for them to become negative about your contribution.  This might seem silly but it appears to be what we have.

I recommend that instead of talking about “C/C++” you use a term that actually makes clear what you mean.

If you are talking about something in C that might or might not also be true for C++, simply say C.

Example: How should the main function be declared in C?

At first, it might seem that the answer for C++ is the same: int main() or int main(int, char**).  But as the discussion goes on, it might be relevant to point out that in C++, the function has to be declared at global scope, which doesn't make sense in C, because it has no namespaces.  On the other hand, C allows calling main recursively while C++ doesn't.  In C++, there is an implicit return 0; if you “fall off” main but in C the return statement is required on any path.  The list goes on and it makes the discussion much simpler if you make it clear up front what the language to be discussed is.

If you are talking about something in C++ that might or might not also be true for C, simply say C++.

Example: Will a malloc()ed array of ints initially be all-zeros in C++?

The short answer for C happens to be the same: no.  But as the answer goes on, it might be worthwhile to point out that in C, calloc would be a good alternative while in C++, using a std::vector<int> might have been a better choice in the first place.

If you want to point out a similarity between C and C++, say C and C++.

Example: In C and C++, the sizeof an int is implementation defined and may vary between compilers and architectures.

Here, we want to point out that C and C++ behave the same way.  We are explicitly talking about both languages.

I actually recommend that you be even more specific and not only talk about “C” or “C++” but the precise version.  Both languages are evolving and a blunt statement such as

C++ supports /* … */ and // … comments while C only supports the /* … */ style.

is neither right nor wrong.

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

Since the languages have overlap, every C program will contain parts that might look like C++ and vice versa.  Nevertheless, the authors will probably have settled onto using either a C or a C++ compiler.  So say “the program is written in C” if it is compiled with a C compiler and “the program is written in C++” if they use a C++ compiler, even if they might refuse to use any modern C++ features.  Some people refer to such C++ code as C-style C++.  Absence of overloading, exceptions, polymorphism, templates and I/O streams a common characteristics of such code.

If, instead, some files are written in C and compiled with a C compiler and some other files are written in C++ and compiled with a C++ compiler, and then the object files linked together, I would say that “the program is written in a mix of C and C++” as, in fact, you already did.

However, if, instead, the authors took great care to write each and every file in such a way that it can be compiled with a C or a C++ compiler and the resulting program would do the same thing, you could say that “the program is written in a common subset of C and C++”.

The latter is often the case for header files that should be shared between C and C++ code.  Writing such code is not easy, by the way.  If you want to further emphasize that only such constructs were used that are valid in C and C++ and are widely supported by different compiler vendors, the term a portable common subset of C and C++ may be used to emphasize this.

Given that both of them are “different” languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern C++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)?

I'm not sure I understand this question.  Since C and C++ are different languages, you cannot expect a compiler for one of them accept a program written for the other.  However, compilers are often designed in a modular way and if a compiler has a C++ front-end, chances are good it will also have a C front-end.  (You would then select which of them you want via a command line switch or similar means.)  As long as both languages will be in widespread use, it seems very unlikely that this is going to change.  Your point about “modern C++” I think is basically a matter of good coding standards and the standard library.  From the compiler's point of view, the evolution of both languages is rather converging than diverging.

Is there right now any collaboration between the people who make the standards of C/C++ to keep the compatibility?

Yes.  The memory model and the atomic operations library introduced in C++11 and C11 is a good example.  It seems that the designers of both languages realize that compatibility is important and are working towards improving it.  Personally, I'd wish that the collaboration were more intense and the two ISO working groups perhaps even joined but my wishes are not important.

Bjarne Stroustrup talks about the differences and commonalities between the various versions of C and C++ in § 44.3 of the 4th edition of The C++ Programming Language which, ironically, is titled “C/C++ Compatibility”.  Use of the term might actually be appropriate in this case as it is clear what is meant.

If #4 is yes, such collaboration could end up in the near future with the appearance of the modern C++ (11/14/17)

As discussed above, it happened in C++11 and is expected / hoped / needed to happen again.

Title: Should I stop using the term C/C++?


问:
Do you throw an argumentexception or argumentnullexception from private methods?
I was just reviewing some code I wrote a while back, and can see that I have a couple of private methods that throw argumentnullexceptions and/or argumentexceptions if there are issues with the methods parameters.

I guess my rationale is that helps future proof the application if someone attempts to "misuse" the method in future. However, given it is a private method and the people who are likely to call this method can see the associated comments and code, it is just unnecessary to throw this. It certainly doesn't hurt to have them, although it does add clutter.

My feeling is that these exceptions are generally more useful on something like a API that is going to be exposed publically.

答:
I realize that while the question has no language tag, it is probably implicitly talking about “coffee languages”.  But just for the sake of completeness, I'd like to mention the somewhat diverging apparent consensus in the C++ world.

There are three things C++ programmers will typically be interested in:

Will it have zero-overhead in optimized builds?  (That is, can it be “compiled out”?)

Can I use it to trap into a debugger right at the point where the error was detected?

Can I use it to report problems from functions declared noexcept?

In the past, I have approached the first problem by writing code like this

int
factorial(const int n)
{
  if (CHECK_ARGS)
    {
      if (n < 0)
        throw std::invalid_argument {"n < 0"};
    }
  int fac = 1;
  for (int i = 2; i <= n; ++i)
    fac *= i;
  return fac;
}
```

where CHECK_ARGS is #defined to a compile-time constant so the compiler may completely eliminate all the argument checking code in optimized builds.  (I'm not saying that compiling the checks out is a good thing in general but I do believe that a user should have the option to compile them out.)

I still like about this solution that the argument checking code is clearly visible grouped together into the if.  However, the second and third issue are not solved by this.  Therefore, I'm now leaning again more towards using an assert macro for argument checking.

The Boost coding standards agree with this:

What About Programmer Errors?

As a developer, if I have violated a precondition of a library I'm using, I don't want stack unwinding. What I want is a core dump or the equivalent - a way to inspect the state of the program at the exact point where the problem was detected. That usually means assert() or something like it.

There was a very interesting talk given by John Lakos at CppCon'14 titled Defensive Programming Done Right (part 1, part 2).  In the first part of his talk, he discusses the theory of contracts and undefined behavior.  In the second part, he presents what I consider a very good proposal for systematic argument checking.  In essence, he proposes assertion macros that allow the user to select how much of a budget (in terms of CPU utilization) she is willing to donate to the library for argument checking and has the library make wise use of that budget.  As an addition, the user can also install a global error handling function that will be called in case a broken contract is detected.

Regarding the aspect that a function is private, I don't think that this means we should never have it check its arguments.  We might trust our own code more to not violate an internal function's contract but we also know that we aren't perfect either.  Argument checking in internal functions is just as helpful in detecting our own bugs as it is in public functions for detecting bugs in client code.

Body:
I realize that while the question has no language tag, it is probably implicitly talking about “coffee languages”.  But just for the sake of completeness, I'd like to mention the somewhat diverging apparent consensus in the C++ world.

There are three things C++ programmers will typically be interested in:

Will it have zero-overhead in optimized builds?  (That is, can it be “compiled out”?)

Can I use it to trap into a debugger right at the point where the error was detected?

Can I use it to report problems from functions declared noexcept?

In the past, I have approached the first problem by writing code like this

int
factorial(const int n)
{
  if (CHECK_ARGS)
    {
      if (n < 0)
        throw std::invalid_argument {"n < 0"};
    }
  int fac = 1;
  for (int i = 2; i <= n; ++i)
    fac *= i;
  return fac;
}

where CHECK_ARGS is #defined to a compile-time constant so the compiler may completely eliminate all the argument checking code in optimized builds.  (I'm not saying that compiling the checks out is a good thing in general but I do believe that a user should have the option to compile them out.)

I still like about this solution that the argument checking code is clearly visible grouped together into the if.  However, the second and third issue are not solved by this.  Therefore, I'm now leaning again more towards using an assert macro for argument checking.

The Boost coding standards agree with this:

What About Programmer Errors?

As a developer, if I have violated a precondition of a library I'm using, I don't want stack unwinding. What I want is a core dump or the equivalent - a way to inspect the state of the program at the exact point where the problem was detected. That usually means assert() or something like it.

There was a very interesting talk given by John Lakos at CppCon'14 titled Defensive Programming Done Right (part 1, part 2).  In the first part of his talk, he discusses the theory of contracts and undefined behavior.  In the second part, he presents what I consider a very good proposal for systematic argument checking.  In essence, he proposes assertion macros that allow the user to select how much of a budget (in terms of CPU utilization) she is willing to donate to the library for argument checking and has the library make wise use of that budget.  As an addition, the user can also install a global error handling function that will be called in case a broken contract is detected.

Regarding the aspect that a function is private, I don't think that this means we should never have it check its arguments.  We might trust our own code more to not violate an internal function's contract but we also know that we aren't perfect either.  Argument checking in internal functions is just as helpful in detecting our own bugs as it is in public functions for detecting bugs in client code.


问:
Why is universal newlines mode deprecated in Python?
I just noticed that the universal newline feature of file operations seems to be on its way out.

The documentation for Python 3.5 open's mode parameter indicates that it's deprecated:

'U'     universal newlines mode (deprecated)

At least as far back as Python 3.2, open contains a similar "backwards compatibility only" warning when documenting the usage of the mode argument:

'U'     universal newlines mode (for backwards compatibility; should not be used in new code)

Even in Python 2.7, a similar warning is placed in the documentation of io.open.

What's the reason for this?

答:
The open() function in the Python 3 library  has a newline argument.  Setting it to None enables universal newlines.  This is the accepted way to do it, rendering the mode='U' argument redundant.

Use newline=None to enable universal newlines mode (this is the default).


答:
Views should perform validations for ff purposes:

) A front end validation can reduce data traffic in your server.

) it handles invalid data before it can travel in your server.

) if you want a higher security, a combination of front  end and back end Validation is better.

Title: Should the View not perform validation?


问:
Motivating yourself to actually write the code after you've designed something
Does it happen only to me or is this familiar to you too?

It's like this: You have to create something; a module, a feature, an entire application... whatever. It is something interesting that you have never done before, it is challenging.

So you start to think how you are going to do it. You draw some sketches. You write some prototypes to test your ideas. You are putting different pieces together to get the complete view.

You finally end up with a design that you like, something that is simple, clear to everybody, easy maintainable... you name it. You covered every base, you thought of everything. You know that you are going to have this class and that file and that database schema. Configure this here, adapt this other thingy there etc.

But now, after everything is settled, you have to sit down and actually write the code for it. And is not challenging anymore.... Been there, done that! Writing the code now is just "formalities" and makes it look like re-iterating what you've just finished.

At my previous job I sometimes got away with it because someone else did the coding based on my specifications, but at my new gig I'm in charge of the entire process so I have to do this too ('cause I get payed to do it).

But I have a pet project I'm working on at home, after work and there is just me and no one is paying me to do it. I do the creative work and then when time comes to write it down I just don't feel like it (lets browse the web a little, see what's new on P.SE, on SO etc).

I just want to move to the next challenging thing, and then to the next, and the next...

Does this happen to you too? How do you deal with it?

How do you convince yourself to go in and write the freaking code?

I'll take any answer.

答:
I think problem is in incorrect goal. It look like that you set goal "design system". And then you do it well, and goal is reached. So one suggestion is to set another goal "implement system", but then it is more related to motivation and how you do it.

There is one other way that worked for me well: set initial goal as "deliver system to specific users" instead of "design system" or "make system". In this way, you won't be satisfied, until users get something valuable. And you do it well from beginning (including testing and other modern fancy stuff).