答:
If you need to compromise your tests, you could try to identify the bits where incorrect results are less important. But you should strive to have as much code as you can tested, before it gets committed to your version-control mainline.

You can, of course, sacrifice testing and tackle the problems this may cause further down the line. You could do some prototyping of new code outside version control, as long as that NEVER hits production, to figure out what the right direction is.

Title: Should I use TDD and BDD if my project is changing fast?

Body:
I have my own little project I am creating using RoR, I plan it to have small-medium load.

With no doubt I started with BDD and TDD (Cucumber and RSpec to be exact, but I am also experienced with TestUnit), I like it but since it's my own project and it's a somewhat startup - I am changing many things in it, many requirements, many ideas how things should work and look. So it becomes too much time-consuming to always code it using BDD and TDD, even if I cover only common cases.

What should I do? Should I sacrifice BDD and TDD for productivity till I get to some point when I have a solid basis and it's time for production, and than I write tests?

Should I write them right now but as minimal as possible? Should I only write RSpec and forget about Cucumber for now? Or maybe just TestUnit to test model for now since it's the most important and everything else can change?

Thanks in advance!

Update:

I know all the pros of TDD and BDD, by no means it makes it easier to scale and bugfix application in future and save time, but maybe it's more reasonable in my situation to wait few weeks till I have at least some skeleton architecture of my app and than once I am sure with it I can cover it with tests to have a solid base? And than continue with TDD and do all the tests with TDD.


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答:
Read Neal Ford's excellent book The Productive Programmer.

It's full of lots of useful tips.

Edit:

And, as mentioned elsewhere, read the docs for your tools. I'm always learning new things for Vim by reading Vim wikis. Similarly, just reading through the man page for bash or zsh always gives new tricks to use.

OwnerDisplayName: Nick Gotch

ContentLicense: CC BY-SA 2.5

Title: How to become a "faster" programmer?

OwnerDisplayName: Rob Wells


问:
Avoid copy and paste programming, what pattern to use?
I have a small software that generates some Word documents. It reads a template, runs a few SqL procedures to get the data, generates the documents and then sends them via e-mail. It's quite simple.

Right now I want to apply that logic to generate another type of report, the base word template will change and it will run different queries. I can do this (wrongly) by copy pasting the code, but I want to extend the current app to generate both reports.

What I can't figure out is what software pattern I need to apply to solve this situation.

答:
To add to what @Robert says, I think of this as seeking a parameterization technique that allows the common code to be written once (so it can be maintained in one place) and then reused instead of pasting.

However, you have to determine the kind of parameterization that will let you factor the common part to be written just once.

Often function parameters suffice, but that's not the only approach.

There are also classes and methods as @Robert says.  Sometimes we use overrides and/or interfaces: I think of overrides and interfaces as a form of parameterization:  The use of base class or interface serves to express a bundle of formal parameters and the concrete subclass or interface implementation serves binding of the bundle of actual parameters.

Don't forget that in many (esp. functional) languages we can have higher-order functions, meaning functions can take parameters that refer to functions, which enables other use cases.  Abstract and interface methods act a lot like function parameters, perhaps with a bit more structure.

Another tool that some languages provide is generic types.  Sometimes common code cannot be expressed with normal parameters: what differs between scenarios is the types being operated over, even if the code is the same in any case.  In those situations generics help.

You can discuss some design pattern in terms of parameterization, such as a Observer and Visitor pattern, which abstracts specific data structure or its traversal from an action to be performed.  These can be implemented by OOP techniques (using overrides or interfaces) and also by higher-order functions.

And still, other techniques (monads) allow other kinds of common code to be collected so as to be written only once.  There is ongoing research in other kinds of parameterization.

In general, though, I think one can make a mental link of many of the  techniques to reduce copied (pasted) code to variations on parameterization.

ContentLicense: CC BY-SA 3.0


问:
Design of simple disassembler
I am writing a simple x86 disassembler in c++ and I would like to hear an input on class which will handle disassembly. I thought to make a class which would receive a pointer to the table which will contain instruction description. In that way I would have logic implemented in a class which could disassemble code for any platform by just receiving different input table. Do you think that's a good way to solve a problem, or should I put the table definition inside a class and then have special classes for x86 disassembler, arm disassembler and so on. I'm a student and I didn't worry before about code elegance but I'm trying to write more elegant code now so any advice about design is welcomed.</p>

答:
If you are planning to write a Recursive Descent Parser (Wikipedia) then a general-purpose description of the machine code to be disassembled might be feasible, but even that is debatable, and you are certainly going to be getting into some very deep waters by just trying that.

If you are not going to be writing a recursive descent parser, then there is probably no point at all in trying to make it so general-purpose.

I would recommend that you first get your disassembler to work in a hard-coded way for a single CPU, and afterwards worry about making it general-purpose.  Try to be focused to a single, simple goal, or else you will never get anything done.

Most chances are, YAGNI.  (Ya Ain't Gonna Need It.)

Title: Design of simple disassembler


答: I read something a long time ago about optimization that really stuck with me.  I don't remember the source or the exact words, but the gist of it was, "The only way to make a program run faster is to make it do less.  Any other plan is just that."  The same goes for humans.  The army also has a saying, "Haste makes waste."  Doing the same things we do now, but faster, will only create problems.  There are many different plans for becoming more productive out there, and I'm not saying they aren't effective, but they won't be tailored to your needs.  You're better off looking at what you do and finding the things you do that aren't productive, and cutting those out.  Any other plan is just a watered-down version of that.</p>

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

OwnerDisplayName: Imagist


问:
Testing procedural code
TL;DR. Writing procedural code within a DB transaction. How can I improve design of the code so it's better testable?

In my application I have a service object that perform multiple things within the same transaction. See code in Ruby below:

```<code>class CreateRefundService
  def create(customer_id)
    ActiveRecord::Base.transaction do
      refund = create_refund(customer_id)
      credit = add_credits_to_customer(customer_id)

      send_email(refund)
      add_note(refund, credit)
    end
  end

  private

  # ... implementation of all 4 methods above
end
</code>```

I'm trying to write 4 tests that would check that all four things happen during transaction, but it starts to feel uncomfortable, since for every method under test I need to stub other 3 methods. This gives me a warrant that there's probably a problem about this design.

I'm under constraints that multiple things need to happen during the same transaction.

答:
The four methods seem to do things which make sense each on its own. So I would not see them as "implementation details which must kept private", I would see them as individual, reusable units, each unit worth to be tested on its own. So you can make them public and write a unit test directly for each.

What remains is to decide if you need some kind of automated integration test for the create method, or if you rely other tests on a different layer or level for this method.

Title: Testing procedural code


答: Are you slower than your colleagues, or are your estimates more overoptimistic?</p>

Title: How to become a "faster" programmer?


问:
How to write highly changeable, highly complex software?
I know questions like this has been asked before. But none of them truly answered me.

How to keep a big and complex software product maintainable over the years?

How do you organize highly customized software?

...

We're working on a software that has a lot of rules and conditions. Also, those rules change frequently.

So far we've used many designs and techniques to cope with the requirements and implement them. To be more specific, let us focus on the following examples:

Using configurable options, so that values can be changed easily by business people, like the amount of debt a customer can undergo.

Problem: Soon there are like hundreds of configurable options, and even naming them becomes a nightmare, let alone managing them, changing them, tracking them in code, etc.

Using small satellite project files as additives to the main engine (something like extensible workflow), so that new rules can be added hot, and also unwanted rules can be removed from the process pipelines.

Problem: Soon the number of project files become so huge that the file-system management of the projects becomes a pain in the ass. What if for a short period of time business team needs a special customization that only lasts for two months, and then it should be removed from the system. Something like prepaid registration to track user-behavior for making the real decisions. Or a rule as simple as banning customers with suspicious activity that should be launched really soon.

It seems that our team is going the wrong path altogether. So how a team can handle creating highly-complex, highly-changeable software when it encounters the specific problems mentioned? What points should that team consider? Are there specific architectures or designs that will help us creating such software?

答:
I will focus on the two core problems described in your question:

Soon there are like hundreds of configurable options, and even naming them becomes a nightmare, let alone managing them, changing them, tracking them in code

The naming problem can be solved by organizing them in hierarchies. For example, look at the thousands of options you will find in the about:config page of the Firefox web browser - they are well-structured and organized in groups of multiple levels.

Tracking in code should follow the same principle: create a hierarchy of objects or data structures (actually, naming and code hierarchies should match, and one should be generated from the other). Of course, that alone is not enough, for hundreds of options you will need to maintain some formal documentation in a disciplined manner (again, check how the Firefox community solves this). You need to establish some quality gates like reviews, and you should to clean up things from time to time. In the end, this is a purely organizational problem, but it is in fact in no way different from managing something like a large database schema.

Using small satellite project files as additives ... Soon the number of project files become so huge that the file-system management of the projects becomes a pain in the ass

That is actually not different from the first case: hierarchies, formal documentation, quality assurance and some discipline will help you here, too. Moreover, assumed your additives are code, there should be no real difference to code which is not "hot-pluggable" - the latter makes only a difference for the user of the system, but not for the maintenance by developers. So you have to care for the same things you always have when writing bigger software: dependencies, clean architecture, SOLID code etc.

As you mentioned "a business team": another option to keep "additives" more manageable is to provide an extension mechanism like a script or query language, so your business team can write such additives on their own. That delegates the burden of managing the extensions away from the development team to the users of the system on the "business side". Though that sounds just like shifting the problem around, it can actually help you, because you create a strict boundary between your core system and those extensions, with in total more people involved for doing the management tasks that give you a headache.

And maybe the people "inventing" all these new requirements will be thinking twice what they do, if they have to write these scripts on their own.

One final thing to add: I heavily recommend to keep new options as "orthogonal as possible". In other words: each new option should have as few dependencies as possible to other existing options, ideally none. That typically implies to split up new requirements for "one option" into several smaller options, but I can tell you from experience, that really a key factor to keep such a system manageable.


答:
To produce software faster, I've found the best thing to do is to learn your runtime API as best as possible. Don't type out list logic when a LINQ extension will do; don't build a bunch of event listeners when binding will work, etc.

As far as estimation, that comes with experience. You can make use of estimation software out there to help you figure out better estimates.

Personally, I found with junior level developers, take whatever their initial estimate is and multiply it by 2, then double it. This will account for all of the learning, meetings, wasted time, etc. The more senior level developers tend to work at a factor of 2 over their estimates.

Often times, the question is not if your estimate was wrong. It's did your estimate account for all the right things? Are you giving your estimates and timelines in terms of coding effort or in terms of calendar time? Think about all the time in your day and how much of it is actual, productive coding vs. meetings, learning, debugging, etc.

Title: How to become a "faster" programmer?

OwnerDisplayName: James Schek


问:
How to DRY decorator pattern and other delegation in java
I was refactoring some java to use decorators.  All of the decorators inherited from a class ThingDecorator, let's say.  This consisted entirely of:

```<code>SomeType methodName(OtherType otherThing) {
    return decoratedObject.methodName(otherThing);
}
</code>```

For maybe 20 methods of that form.  This is like writing "this thing is a decorator" over and over again, which just drives me nuts as a DRY enthusiast.  Every addition to the activities of this class needs an addition to the class[es] that form the basic un-decorated behavior and the decorator, but it's always just "this thing is still a decorator!" all over again.  Is there any way to express once that an object is to delegate all non-overridden methods to some member field?

答:
No, unfortunately, there isn't any way to accomplish this.

Unless you use some magic, like this: michael.gr - Intertwine: Normalizing Interface Invocations (which though I have implemented for C#, not for Java yet.)


答:
Two things that might be implied, but I haven't seen among the answers here yet that increases productivity are:

Use some sort of build and deployment scripts. Compiling, deploying, restarting app-server and such musn't suck up either time or focus, it should be a one-click kind of thing.

Have some sort of version control. Having to code without being able to roll back a change is like trying to walk on eggs

Title: How to become a "faster" programmer?

OwnerDisplayName: Buhb


答:
It's always the same sole decision, fast development vs. quality, readability, extensibility.
Drag and drop of controls and infinite code-behind files (quick and dirty) or modularity, patterns and practices (long term investment)?

In my honest opinion, everyone must invest in the long term way of coding. As time passes, the fast development is going to be of great quality as well.

However in case I didn't understand your inquiry, and you are seeking answers in terms of practical aspects of fast development, like tooling, code generators and other stuff, my opinion is to start using Resharper and learn as much you can about your IDE :)

Title: How to become a "faster" programmer?

OwnerDisplayName: Aggelos Mpimpoudis


问:
How are individual lines of code and functions stored in a Concrete Syntax Tree?
I'm trying to write a simple compiler for learning purposes. I've been reading the Dragon Book and Modern Compiler Design and one part I don't understand is how the Concrete Syntax Tree is actually created and stored.

I understand that by looping through the Tokens produced by the Lexer it's a simple matter to collect all the pieces of an assignment operator; for example:

```<code>int i = 0;
</code>```

is pretty straight-forward to collect the type, identifier and that we're assigning a value of const_number zero. And I understand how this concrete syntax tree looks like.

And if it's assigned like an expressions like:

```<code>int i = a * b;
</code>```

I also understand what this concrete syntax tree would look like.

But then let's say I have:

```<code>int i = functionCall();
</code>```

What does this look like in a concrete syntax tree?

And further, considering a language like C that's a bunch of functions, with one of them, the main function being denoted as the entry point; how does this all fit into a concrete syntax tree?

Does each one have its own tree?

The creation of a heirarchy of Node types for my tree, each with the specific components it needs makes sense to me; but not how this factors in function calls; unless every single function was inlined.

Additional Info from Comments

So, say I have some code that looks like:

```<code>int AddProc(int i, int j)
{
    return i + j;
}

void main()
{
    int x = 8;
    int y = 0;
    int z = x + y;
    x = AddProc(y,z);
}
</code>```

The Token stream starts from the top to the bottom; simple; each token tells the Parser if it's a TYPE or ID or CONST or ADD_OP whatever. The first stage of the parser is to produce a Concrete Syntax Tree, that's then turned into an Abstract Syntax Tree.

My question is what does the Concrete Syntax Tree look like for the above; and further, the AST as well?

答:
If your code contains a line like

```<code>x = AddProc(y,z);
</code>```

then the syntax tree for that expression would look similar to this:

```<code>       assignment
      /          \
    ID(x)  FunctionCall(AddProc)
                /      \
              ID(y)   ID(z)
</code>```

One important thing to note is that the implementation of AddProc is not part of this syntax tree. Instead, the systax tree for the complete program will have a separate syntax sub-tree for the definition of AddProc.

In languages like C, where programs can be spread over multiple files and contain multiple functions, the compiler will create a separate syntax tree for each file, which in turn contains separate sub-trees for each declaration and definition that is found at file level.

For the creation of syntax trees, the main function is not considered to be special. This function only gets some special treatment when checking the program for errors and when generating code.

Body:
If your code contains a line like

x = AddProc(y,z);

then the syntax tree for that expression would look similar to this:

       assignment
      /          \
    ID(x)  FunctionCall(AddProc)
                /      \
              ID(y)   ID(z)

One important thing to note is that the implementation of AddProc is not part of this syntax tree. Instead, the systax tree for the complete program will have a separate syntax sub-tree for the definition of AddProc.

In languages like C, where programs can be spread over multiple files and contain multiple functions, the compiler will create a separate syntax tree for each file, which in turn contains separate sub-trees for each declaration and definition that is found at file level.

For the creation of syntax trees, the main function is not considered to be special. This function only gets some special treatment when checking the program for errors and when generating code.


答:
A couple of ideas come to mind:

Get other opinions on your estimates - Are there other developers that you could ask something like "Hey, do you think you can get this kind of feature done in this timeframe?"  The idea being that other people's input may help with accuracy in some cases as someone may note a bunch of things you missed in making the estimate.

Hone your estimation skill - Start tracking how off you are on the estimates and why you are off:  Are other work items causing deadlines to not be met?  Are you consistently underestimating how complicated something is?  Are you giving an entire timeline when it isn't practical,e.g. what is asked is vague enough that merely getting a prototype up will take weeks and then there should be a re-evaluation of what else is to be done?  Doing this may help the most in building that skill so that if you say something will take x hours, you can have confidence in that because you have done it over and over and over again.  An alternative way to state this is merely practice, practice, practice.

Granted you probably already considered these, but I just thought it worthwhile to state this for those others out there that may not have considered these ideas.

Title: How to become a "faster" programmer?

OwnerDisplayName: JB King


问:
Template method pattern - abstract classes vs interface delegation
Template method pattern is commonly implemented with abstract classes.

```<code>interface Algorithm
{
    void perform();
}

abstract class AlgorithmBase implements Algorithm
{
    abstract void step1();
    abstract void step2();

    private void finalStep()
    {
        // common implementation
    }

    // Template method
    public final void perform()
    {
        step1();
        step2();
        finalStep();
    }
}

public class AlgorithmA extends AlgorithmBase
{
    void step1()
    {
        // step 1 implementation
    }

    void step2()
    {
        // step 2 implementation
    }
}
</code>```

using

```<code>  Algorithm a = new AlgorithmA();
  a.perform();
</code>```

But some languages (like Swift) don't support abstract classes. Implementation of template method pattern is done through interface delegation.

```<code>protocol Algorithm
{
    func perform()
}

protocol AlgorithmSteps
{
    func step1()
    func step2()
}

class AlgorithmBase: Algorithm
{
    var delegate: AlgorithmSteps

    init(delegate: AlgorithmSteps)
    {
        self.delegate = delegate
    }

    private func finalStep()
    {
        // common implementation
    }

    // Template method
    final func perform()
    {
        delegate.step1()
        delegate.step2()
        finalStep()
    }
}

class AlgorithmA : AlgorithmSteps
{
    func step1()
    {
        // step 1 implementation
    }

    func step2()
    {
        // step 2 implementation
    }
}

let a : Algorithm = AlgorithmBase(delegate: AlgorithmA())
a.perform()
</code>```

Obviously if language does not support abstract classes the only way to go is using interface delegation, but what if it does? Then template method pattern can be implemented either way.

Does second implementation has any advantages in terms of good OOP practices vs first one?

答:
Neither one is better than the other.  It depends entirely on your point of view.  In the first case, you should think of it as extending the logic of AlgorithmBase.  Suppose you have a class called DatabaseEntity with class  PersonEntity deriving from it.  Both of which save to the database, on the latter may want to override the validation logic prior to saving to ensure that firstName and lastName values are filled.  DatabaseEntity is still in charge of when these methods get called, but PersonEntity redefines what it means to validate that instance.

In the second case, it is more about passing responsibility to another class.  You probably wouldn't want to pass responsibility to another class in the case above.  A PersonEntity instance is perfectly suited to perform validation of itself.  Rather take the example of a VehicleFactory.  Any class deriving from VehicleFactory would have to return a Vehicle instance, but suppose you want to generate also a person that drives the vehicle.  It would be wrong to expect a derived class of VehicleFactory to worry about that.  Instead, it should have a PersonFactory instance and delegate the job of creating a Person instance to PersonFactory.  It is still a step in the process of creating a Vehicle, but in contrast to the first example, some of the steps shouldn't be performed by that class or its derived classes.

TL;DR - It depends on what you need to have done, and whether or not steps 1 and 2 should be performed by a derived class.


问:
Confusion about data types, compilers, hardware data representation and static vs dynamic typing
I am trying to understand static vs dynamic typing, but am really struggling to see how everything fits together.

It all starts with data types. As far as I understand, data types are quite abstract notions, which exist 'in' compilers in order to categorise data so that the operations on various types of data can be validated (i.e. in an attempt to stop you adding a string to an integer), and in order to generate the right machine code for the hardware interpretation of the value. I.e. say we have the following:

```<code>int myInt = 5;
char myChar = '5';

Console.WriteLine(myInt);
Console.WriteLine(myChar);
</code>```

Both would ultimately write a five to the console window, but, since the representations in memory of integers and characters are different, the machine code which interprets the value in the memory location bound to the variable myInt, which takes that value and displays it on the console window, would be different to the machine code for myChar. Even though Console.WriteLine() 'does the same job', the different representations of five require different low level code.

So my question is this: if data types 'exist only in the compiler' - i.e. once the program has been compiled into machine code there is no knowledge of what type of data the value in a particular memory cell is (everything is just 1s and 0s) - then how can any type-checking be done at runtime? Surely there is no concept of data types at run time? So surely dynamic typing can't be anything to do with type-checking occurring at run time?

Where is my understanding going wrong, and could somebody please explain static and dynamic typing with respect to the argument given above? What is the big picture of what is going on?

I am trying to understand this for an essay, so references to books or online sources would be useful :) Thank you.

答:
It depends entirely on the runtime.  Java does it one way, .NET does it another, Python does it a third way, C++ does it a limited way, and C doesn't do it at all.

Such runtime type info might come either as metadata (or a pointer to thereof) attached to an object, or instead be static type info disguised as dynamic type info (e.g. C++'s typeid operator).  But, again, it depends on the runtime.


答:
Your assertion that "datatypes exist only in the compiler" is not true for dynamic languages (and not a few static ones).

Once that doesn't hold, it becomes a simple runtime check.

Title: Confusion about data types, compilers, hardware data representation and static vs dynamic typing

Body:
I am trying to understand static vs dynamic typing, but am really struggling to see how everything fits together.

It all starts with data types. As far as I understand, data types are quite abstract notions, which exist 'in' compilers in order to categorise data so that the operations on various types of data can be validated (i.e. in an attempt to stop you adding a string to an integer), and in order to generate the right machine code for the hardware interpretation of the value. I.e. say we have the following:

```<code>int myInt = 5;
char myChar = '5';

Console.WriteLine(myInt);
Console.WriteLine(myChar);
</code>```

Both would ultimately write a five to the console window, but, since the representations in memory of integers and characters are different, the machine code which interprets the value in the memory location bound to the variable myInt, which takes that value and displays it on the console window, would be different to the machine code for myChar. Even though Console.WriteLine() 'does the same job', the different representations of five require different low level code.

So my question is this: if data types 'exist only in the compiler' - i.e. once the program has been compiled into machine code there is no knowledge of what type of data the value in a particular memory cell is (everything is just 1s and 0s) - then how can any type-checking be done at runtime? Surely there is no concept of data types at run time? So surely dynamic typing can't be anything to do with type-checking occurring at run time?

Where is my understanding going wrong, and could somebody please explain static and dynamic typing with respect to the argument given above? What is the big picture of what is going on?

I am trying to understand this for an essay, so references to books or online sources would be useful :) Thank you.


答:
How can any type-checking be done at runtime? Surely there is no concept of data types at run time?

Sometimes there are data types at runtime. Other times, the type checking can be done entirely at compile-time. In principle, it's up to the implementation whether it chooses to implement a type check at compile time or at runtime, and they have a lot of options.

In languages like C++ and Java, there is a distinction between primitive types (typically integers, characters, etc) and structured or complex types (typically structs and classes). In these languages it's common for only the structured types to retain some metadata about their type at runtime (though that usually includes the types of their primitive members/fields). For example, in C++, the typeid function is typically evaluated at compile time, and works even on primitive types, while a dynamic_cast is executed at runtime and only works on classes.

In more dynamic languages like Python and Javascript, any variable can have any type, so a straightforward interpreter will most likely have to implement all variables as a "variant type", i.e. a class that literally carries its own type around with it. A more sophisticated interpretation may use optimizing AOT or JIT compilers that are run on sections of code where all typing issues can be proven at compile time, so it's safe to replace the variant types and their runtime checking with highly optimized code. This is why you see articles about the V8 Javascript engine's "inner classes" that tell you to avoid dynamically changing the structure of your objects or the types stored in your arrays, because that sort of thing prevents V8 from optimizing it down to "just 1s and 0s" that don't know their own types.

Hopefully those examples are sufficient to clear up your confusion.


问:
What are the practical uses of Windows Services?
I am new to working with Windows Services. Although I have learnt to create  Windows Services in VS2010  I would like to know some practical ways in which windows services could be used?

I tried Googling with the current context in mind only to find more tutorials on how to create Windows Services.

EDIT on Bounty Offer:

All the answers are great but I was looking for more practical examples on windows services and their implications? This will help developers know when it is appropriate to use them with the case study.

答:
The most useful service I've written, from the end-user perspective:

* User printed UGLY invoices on a dot-matrix printer with RAW print-driver.

* User wanted a PRETTY invoice with logo, smooth-line graphics.

* No access to legacy code.

The service would:

* Monitor (multiple) printer folders for print jobs.

* Create a PDF of the invoice.

* PDF would "underlay" a nice blank invoice image

* Overlay the raw text

* Look up meta data, based on folder being used (IE: printer being used)

Then the metadata would:

* Generate PDF

* and/or print PDF

* and/or file the PDF to a final destination folder

* and/or delete the PDF

* and/or email the PDF invoice to customer

In this case, it handles ghost-script, PLC and PDF engines.
It's been running very cleanly for years.  Include log files!!!


答: Learn to touch-type as quickly as possible.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: AJ Johnson


答:
You may think that

```<code>Console.WriteLine(myInt);
Console.WriteLine(myChar);
</code>```

get compiled in the same way. But most likely the get compiled to something like

```<code>Console.WriteInteger(myInt);
Console.WriteEndOfLine();
Console.WriteChar(myChar);
Console.WriteEndOfLine();
</code>```

On the other hand, some languages are very flexible. For example, Swift has the data type Any which can literally hold any value. An Any object is quite large, because it contains not only the value, but a complete description of the value. If you write

```<code>var myInt:Any = 5
var myChar:Any = '5'
</code>```

then you have two objects of type Any, one containing the description of the "Int" type and an integer value, one containing the description of the "Char" type and a char value.

Body:
You may think that

Console.WriteLine(myInt);
Console.WriteLine(myChar);

get compiled in the same way. But most likely the get compiled to something like

Console.WriteInteger(myInt);
Console.WriteEndOfLine();
Console.WriteChar(myChar);
Console.WriteEndOfLine();

On the other hand, some languages are very flexible. For example, Swift has the data type Any which can literally hold any value. An Any object is quite large, because it contains not only the value, but a complete description of the value. If you write

var myInt:Any = 5
var myChar:Any = '5'

then you have two objects of type Any, one containing the description of the "Int" type and an integer value, one containing the description of the "Char" type and a char value.


答:
Concrete syntax trees follow directly from the grammatical production rules of the language (i.e. its grammar).  They are complex, wordy and offer little benefit for the next phases of the compiler (analysis and code generation).

I don't think that most compilers represent or store concrete syntax (let alone concrete syntax trees), concrete syntax is at best manifest within the parsing algorithm itself (for example, sometimes using recursion); generally on successfully parsing something the parser generates some intermediate data structure, and if that is a tree, it is likely more reflective of an abstract syntax tree.

Look at the diagram for the "Parse Tree" in this answer and https://stackoverflow.com/a/10176731/471129 , and compare with the AST further on in @Guy's answer.

http://eli.thegreenplace.net/2009/02/16/abstract-vs-concrete-syntax-trees/

Title: How are individual lines of code and functions stored in a Concrete Syntax Tree?

Body:
I'm trying to write a simple compiler for learning purposes. I've been reading the Dragon Book and Modern Compiler Design and one part I don't understand is how the Concrete Syntax Tree is actually created and stored.

I understand that by looping through the Tokens produced by the Lexer it's a simple matter to collect all the pieces of an assignment operator; for example:

```<code>int i = 0;
</code>```

is pretty straight-forward to collect the type, identifier and that we're assigning a value of const_number zero. And I understand how this concrete syntax tree looks like.

And if it's assigned like an expressions like:

```<code>int i = a * b;
</code>```

I also understand what this concrete syntax tree would look like.

But then let's say I have:

```<code>int i = functionCall();
</code>```

What does this look like in a concrete syntax tree?

And further, considering a language like C that's a bunch of functions, with one of them, the main function being denoted as the entry point; how does this all fit into a concrete syntax tree?

Does each one have its own tree?

The creation of a heirarchy of Node types for my tree, each with the specific components it needs makes sense to me; but not how this factors in function calls; unless every single function was inlined.

Additional Info from Comments

So, say I have some code that looks like:

```<code>int AddProc(int i, int j)
{
    return i + j;
}

void main()
{
    int x = 8;
    int y = 0;
    int z = x + y;
    x = AddProc(y,z);
}
</code>```

The Token stream starts from the top to the bottom; simple; each token tells the Parser if it's a TYPE or ID or CONST or ADD_OP whatever. The first stage of the parser is to produce a Concrete Syntax Tree, that's then turned into an Abstract Syntax Tree.

My question is what does the Concrete Syntax Tree look like for the above; and further, the AST as well?


答:
It depends on the language. In C, types exist only at compile time. In Java and C#, types exists both at compile time and runtime. In dynamic languages (like Python, JavaScript etc.) they exist only at runtime.

Your code example would therefore work quite different depending on the language. In Java/C# the two calls to Console.WriteLine() actually calls two different methods. This is called method overloading - multiple methods can have the same name, as long as they have different types of parameters, so the compiler can select the correct method implementation at compile time depending on the types of the arguments. The two different methods just happen to produce the same output in this specific case.

A dynamic language on the other hand would not have method overloading, but might have a single method which behaved differently depending on the runtime type of the argument.


问:
Do you have to use an in-memory db for integration testing?
I'm currently setting up integration testing for my company. I haven't done it before. We are developing a Java web application which uses MySQL as datasource.

I know it is very common to use an in-memory database like H2 or HyperSQL for development.

My question is, is it best practice to use a separate in-memory DB or can i just choose MySQL.

答:
Do you have to use an in-memory database?

No, you don't have to. But depending on what kind of application you are developing, and depending on what kind of tests you are going to implement, it can have some benefits.

Pros:

tests may probably run faster than on a MySQL server

administrative overhead may be smaller, because you want each dev to have his isolated database instance, and managing a MySQL server for each dev will probably mean more effort than a zero-administration DB

you will be forced to develop your application in a database-independent manner (which may improve the design of the app)

Cons

you cannot make use of any MySQL feature which is not also available at the in-memory system

you will be forced to develop your application in a database-independent manner (which may impose some restrictions and overhead to your app)


答:
What happens when all the code is right, but the database is down?

What happens when all the code is right, but the data in the database (or the time) has changed (select count(1) from table where date > sysdate - 1)?

What happens when two unit tests run at once?

What happens when one test terminates early and doesn't clean up?

All of these things make the actual database much harder to use for unit testing and you would find yourself spending a significant amount of time trying to account for them. For automated tests, the can create false negatives - where the test fails but everything is working correctly.  "The build broke, time to check if the database was up last night at 2am..." and all the joys of going through that to try to figure out what went wrong.

The key to automated testing is being able to reproduce it. No matter when it runs, or what the situation of the rest of the network, the automated test shouldn't fail if the code is correct.  And if you are going to have databases that might be up or down, or data that might have changed - the additional effort to try to make it work using an external database becomes excessive.

So, spin up a database in memory.  Load it up with exactly the right data. Have it only be for that instance of the tests (and if another build fires off while its running, it gets its own instance).  This makes it easier to rerun the test at any time.

The big danger of automated tests failing because of something beyond the control of the programmer is that those false negatives will be a "oh, the test failed, might be the database - I'll check it later" and that starts leading to ignored failing tests and a longer time frame between the failing test and the bug fix (when there is a problem with the code).

There are libraries for making testing against a database easier - that you fire up a new database schema just for your test. Though this has the additional cost of maintenance on the database (and if the database is down, it still fails) and only partially mitigates the bullet points at the start.

Title: Do you have to use an in-memory db for integration testing?

Body:
I'm currently setting up integration testing for my company. I haven't done it before. We are developing a Java web application which uses MySQL as datasource.

I know it is very common to use an in-memory database like H2 or HyperSQL for development.

My question is, is it best practice to use a separate in-memory DB or can i just choose MySQL.


答:
In practice, compilers keep some abstract syntax tree (perhaps several sorts of them, e.g. both typed and untyped ASTs) with additional meta-information (e.g. source position as a filename + line, etc...). That meta-information could be kept inside trees or outside them. And most compilers also maintain some symbol table.

So your "concrete syntax tree" is often some initial form of the AST decored with some initial meta-data.

Did you look into the implementation of concrete compilers like Ocaml, GCC, Clang, etc...? Did you consider compiling to C, to LLVM, to GCCJIT, etc...? The devil is in the details !

For GCC, my documentation page of GCC MELT contains links to a lot of other sites and hundreds of slides explaining more details. Read also the GCC internals documentation, notably chapters on GENERIC trees and on GIMPLE.

Notice also that most compilers have numerous passes (GCC has several hundreds of them) and a pass is transforming some internal representation (often such a decorated AST) into some other one (often, but not always, the source and target IR has similar types; Ocaml has both typeless trees and typed trees after the type inference pass).

(there is no a single universal answer to your question(s); it is a matter of opinion, of source language, of target language, of objectives -ease of error recovery during compilation-, etc...; you might care about debug info, e.g. in DWARF!)

If you are fluent in Lisp or Scheme, consider reading C.Queinnec's book Lisp In Small Pieces (which gives several implementations of Lisp and the theory behind them). Read also Scott's Programming Languages Pragmatics

Often, a compiler would canonicalize or simplify some AST, e.g. into A-normal form or CPS form (or transforming a for loop in C into something simpler with while or if & goto)

Of course, you'll learn a lot by studying the source code of several free software compilers and interpreters, and by coding your own compiler (perhaps targeting C, or Javascript, or LLVM, or GCCJIT, or libjit...); the structure of the target language and the source language may dictate the transformations and the internal representations of your compiler.

Read about semantics (operational semantics, denotational semantics, types & programming languages ....) & about undefined behavior (notably, what every C programmer should know about UB)


问:
Is MVC just the SEO of PHP programming?
There's around a zillion "PHP frameworks". And most of them bill themselves as following the MVC pattern. While it's welcome to overcome osCommerce coding style (processing logic heavily intermixed with SQL and HTML), there are certainly simpler and easier to follow approaches to get a maintainable application design.

The original MVC concept was targetted at GUI applications. And for Gtk/Python it seems feasible to follow it accordingly. But PHP web apps don't operate on live Views (GUI elements) and a persistent Controller runtime. It's quite certainly a misnomer if it just describes the used code + directory grouping or class naming.

"MVC" seems to be used like a buzzword for PHP frameworks. And I've actually seen one or two mature PHP frameworks admit it, but redefining the phrase anyway to match interna.

So is it generally snake oil? Why isn't better terminology used, and a more sensible concept for maintainable PHP propagated?

Some elaborative reasoning

Why I suspect that PHP implementations don't follow the real MVC pattern:

Models: in theory, Models should be fat and contain business logic, and controllers should be thin handlers (input->output). In reality the PHP frameworks advocate shallow Models. CI and Symfony for example equate Model == ORM. Even HTTP input is handled by the controller, isn't treated as model.

Views: workarounds with AJAX discounted, there can't be Views on web pages. PHP frameworks still pump out pages. The interface still effectively follows the ordinary HTTP model, there's no advantage over non-MVC applications. (And lastly, none of the widespread php frameworks can factually output to GUI Views instead of HTML. I've seen a PHP library that can operate Gtk/Console/Web, but the frameworks don't.)

Controller: I'm unsure. Controllers probably don't need to be long-running and persistently active in the MVC model. In PHP framework context, they're however mostly request handlers. Not really something to get argumentative about, but it just feels slightly buzzwordish.

Would there be better descriptors? I've seen acronyms like PMVC or HMVC thrown around. Though descriptions get more ambigous there, maybe these would describe the current web frameworks less hokey?

答:
As I'm unaware of the PHP frameworks this is seen from a low-level language view.

Models:

in theory, Models should be fat and contain business logic

That's completely up to do, I don't see what PHP has to do with this...

Models are data classes in PHP which could probably communicate with the database,

then you could also send the same model or a partial model in JSON format to the client.

I wouldn't say business logic, it's more like data logic (validation, database interaction, import/export, ...).

and controllers should be thin handlers (input->output)

Your Controller classes interact with the Model classes, they are indeed thin.

Based on the output, do some things with the Models... And return a ModelView to the client...

In reality the PHP frameworks advocate shallow Models. CI and Symfony for example equate Model == ORM. Even HTTP input is handled by the controller, isn't treated as model.

I'm not really aware of those PHP frameworks...

But HTTP input should be handled before it reaches the controller,

you can easily create a class that turns GET and POST data into good routing and parameters.

This is exactly what happens in ASP.NET MVC 2 and there is nothing wrong with it,

I don't know how this would happen with PHP but I guess it would be closely related.

You could even easily turn the GET and POST data into a model,
the model maybe could contain constructor logic for that. Or some separate classes could be added for that purpose.

Views:

workarounds with AJAX discounted, there can't be Views on web pages. PHP frameworks still pump out pages.

I don't see why it couldn't, the only difference is the protocol and PHP can return JSON, etc...

A page is your view and it can request and update through AJAX + JSON.

Again, I'm not really aware of those PHP frameworks but in ASP.NET MVC 2 it works that way.

The interface still effectively follows the ordinary HTTP model, there's no advantage over non-MVC applications. (And lastly, none of the widespread php frameworks can factually output to GUI Views instead of HTML. I've seen a PHP library that can operate Gtk/Console/Web, but the frameworks don't.)

The only advantage you get (and that's the same with normal applications) is the separation into Model (Data) + View (GUI) + Controller (Logic). Similar, you won't see a C++ framework that can factually output to HTML or JSON instead of GUI Views.

Controller:

I'm unsure. Controllers probably don't need to be long-running and persistently active in the MVC model. In PHP framework context, they're however mostly request handlers. Not really something to get argumentative about, but it just feels slightly buzzwordish.

MVC is a software architecture/pattern, where the Controller runs and for how long doesn't mather.

Title: Is MVC just the SEO of PHP programming?


答:
Download all your languages/libraries documentation locally to your computer, then unplug your network cable/turn off Wi-Fi.

Not trying to be funny here. This really helps me!

Title: How to become a "faster" programmer?

OwnerDisplayName: mcjabberz


问:
Evaluating data set with a string formula in php
I was tasked to update some conditions in an application.
I have a data set to be evaluated, and it has been hard-coded in the application following way:

```<code>$arr = array(
'a' => 'apple',
'b' => 'orange',
'c' => 1,
'd' => 2,
'e' => 5,
'f' => 'green',
'g' => 'red',
'h' => 'yellow',
)

$res1 = ($arr['a'] == 'apple') ? TRUE : FALSE;
$res2 = (($arr['b'] == $arr['f']) && ($arr['c'] < $arr['d']) ? TRUE : FALSE;
$res3 = (($arr['e'] == '5') && $res2) ?TRUE : FALSE;
</code>```

and so on...

It is a nightmare to maintain in many places.

What I am essentially looking for is to make some way to pass in query string to evaluate data.
For start a simple formula could be defined as an array

```<code>$formula = ['a', '=', 'apple'];

function query($formula, $arr) {
    switch ($formula[1]) {
        case '=':
            return ($arr[$formula[0]] == $formula[2]);
        case '!=':
            return ($arr[$formula[0]]!= $formula[2]);
        case '>':
            return ($arr[$formula[0]] > $formula[2]);
        case '<':
            return ($arr[$formula[0]] == $formula[2]);
    }
}
</code>```

This then could be extended and called recursively

```<code>$formula = [['a','=','apple'], 'AND', ['e','<','10']]
</code>```

but what I am essentially looking for is to store formulas a a string, like:

```<code>"((([a]="orange") OR ([c]<"4")) AND ([g]="red"))"
</code>```

where [ ] would identify array keys

or maybe something like in Excel

```<code>"AND(OR(IF('a'='orange'),IF('c'<4)),IF('g'='red'))"
</code>```

Is there any clean solution to do this? I have an idea how to build whole library for it, maybe in the future.

I don't want to add new conditions to the code every time. They are already all over the application.
It would be better to store it in configuration and extend or modify in one place.

Any help much appreciated.

答:
So this is only quick solution, but works for me right now.

```<code>$arr = array('a' => 'red','b' => 'blue');

$formula = ['[a]', '=', 'red'];
</code>```

If there is [a] in formula it will be treated as array key.

```<code>function query($formula, $arr) {

    $query_operator=$formula[1];

    if (is_array($formula[0])) {
        //recursive call
        $query_left = query($formula[0], $arr);
    } else {
        //extracting string between brackets
        preg_match("/\[([^\]]*)\]/", $formula[0], $match);
        $query_left = $match ? $arr[($match[1])] : $formula[0];
    }

    if (is_array($formula[2])) {
        //recursive call
        $query_right = query($formula[2], $arr);
    } else {
        //extracting string between brackets
        preg_match("/\[([^\]]*)\]/", $formula[2], $match);
        $query_right = $match ? $arr[($match[1])] : $formula[2];
    }

    switch ($query_operator) {
        case '=':
            return ($query_left == $query_right);
        case '!=':
            return ($query_left != $query_right);
        case '>':
            return ($query_left > $query_right);
        case '<':
            return ($query_left == $query_right);
        case 'AND':
            return ($query_left && $query_right);
        case 'OR':
            return ($query_left || $query_right);
    }
}
</code>```

In this solution it will work with formula like:

```<code>$formula = [['[a]', '=', 'red'], 'AND', ['[b]', '=', 'blue']];
</code>```

It is not exactly what I wanted, but does the job, and is not so terrible (I hope). It needs some input checking and error handling, but this is just an example.

OwnerDisplayName: Pawel Jankowski

Body:
So this is only quick solution, but works for me right now.

$arr = array('a' => 'red','b' => 'blue');

$formula = ['[a]', '=', 'red'];

If there is [a] in formula it will be treated as array key.

function query($formula, $arr) {

    $query_operator=$formula[1];

    if (is_array($formula[0])) {
        //recursive call
        $query_left = query($formula[0], $arr);
    } else {
        //extracting string between brackets
        preg_match("/\[([^\]]*)\]/", $formula[0], $match);
        $query_left = $match ? $arr[($match[1])] : $formula[0];
    }

    if (is_array($formula[2])) {
        //recursive call
        $query_right = query($formula[2], $arr);
    } else {
        //extracting string between brackets
        preg_match("/\[([^\]]*)\]/", $formula[2], $match);
        $query_right = $match ? $arr[($match[1])] : $formula[2];
    }

    switch ($query_operator) {
        case '=':
            return ($query_left == $query_right);
        case '!=':
            return ($query_left != $query_right);
        case '>':
            return ($query_left > $query_right);
        case '<':
            return ($query_left == $query_right);
        case 'AND':
            return ($query_left && $query_right);
        case 'OR':
            return ($query_left || $query_right);
    }
}

In this solution it will work with formula like:

$formula = [['[a]', '=', 'red'], 'AND', ['[b]', '=', 'blue']];

It is not exactly what I wanted, but does the job, and is not so terrible (I hope). It needs some input checking and error handling, but this is just an example.


答:
The concrete syntax tree is an early step in the compilation process, and it only contains the information from the lexical level. The node for a function call does not "know" anything about the function that is called or even if it exists at all. </p>

<p>At later stages it will be verified if the identifier is the name of a function declared somewhere else in the program, that the types of the parameters matches the argument at the call site and so on. But these semantic checks happens at a later stage, and is not present in the syntax tree. </p>

Body:
The concrete syntax tree is an early step in the compilation process, and it only contains the information from the lexical level. The node for a function call does not "know" anything about the function that is called or even if it exists at all.

At later stages it will be verified if the identifier is the name of a function declared somewhere else in the program, that the types of the parameters matches the argument at the call site and so on. But these semantic checks happens at a later stage, and is not present in the syntax tree.


问:
Patterns for passing context through a method chain
This is a design decision that appears to come up quite a lot: how to pass context through a method that doesn't need it to a method that does. Is there a right answer or does it depend on the context.

Sample code that requires a solution

```<code>// needs the dependency
function baz(session) {
  session('baz');
}

// doesn't care about the dependency
function bar() {
  baz();
}

// needs the dependency
function foo(session) {
   session('foo')
   bar();
}

// creates the dependency
function start() {
  let session = new Session();
  foo(session);
}
</code>```

Possible solutions

threadlocal

global

context object

pass the dependency through

curry baz and pass it into bar with the dependency set as the first arg

dependency injection

Examples of where is comes up

HTTP request processing

Context objects in the form of request attributes are often used: see expressjs, Java Servlets or .net's owin.

Logging

For Java logging folk often use globals / singletons. See the typical log4j / commons logging / java logging patterns.

Transactions

Thread locals are often used to keep a transaction or session associated with a chain of method calls to avoid needing to pass them as parameters to all the methods that don't need them.

答:
Philosophically Speaking

I agree with David Arno's concern.

I'm reading the OP as looking for implementation solutions. However, the answer is change the design. "Patterns"? OO design is, one could say, all about context. It's a vast, blank sheet of paper pregnant with possibilities.

Dealing with existing code is a different, well, context.

I'm working on 'zactly the same problem right now. Well, I'm fixing the hundreds of lines of code copy-n-paste that was done just so a value can be injected.

Modularize the code

I threw away 600 lines of duplicate code then refactored so instead of "A calls B calls C calls D ..." I have "Call A, return, Call B, return, Call C ...".  Now we only need to inject the value into one of those methods, let's say method E.

Add a default parameter to the constructor. Existing callers do not change - "optional" is the operative word here. If an argument is not passed the default value is used. Then only 1 line change to pass the variable into the refactored, modular structure; and a small change in method E to use it.

Closures

A Programmers thread - "Why would a program use a closure?"

Essentially, you are injecting values into a method which returns a method customized with the values. That customized method is subsequently executed.

This technique would allow you to modify an existing method without changing its signature.


问:
Strategies to increasing the maintainability of assertions in code

Background

I am writing a compiler for a custom language for a school project and it is going really well for me.

If I where to start all over from scratch I would have done many software architecture things different, but right now I do not have time or motivation for a complete rewrite so I will focus on just finishing this project instead.

There is one thing in my code that I want to refactor right now and it is how I organize my assertions.

I am writing this compiler in the C using flex and bison to generate my lexer and parser. The code in this project is not very clean and quite messy but I am not ashamed of it (compilers are quite complex and this is my first try). But I have added assertions in the code to make bugs get spotted in time and easier to track down.

The problem

The problem I am having with assert in this project is that there is simply too much to check for.

Here is an example from a function that adds the function parameters to the symbol table when compiling a function definition:

```<code>static void add_function_params_to_symbols(struct context *con,
        const struct ast_op *function_def) {
    struct ast *child = function_def->childs[0];
    assert(child);
    assert(child->type == SYN_DECLARATOR);
    assert(child->val_type == AST_OP);
    child = child->val.op.childs[1];
    assert(child);
    assert(child->type == SYN_FUNCTION);
    assert(child->val_type == AST_OP);
    child = child->val.op.childs[1];
    assert(child);
    assert(child->type == SYN_PARAMETER_LIST);
    assert(child->val_type == AST_OP);
    parameter_list_to_symbols(con, &child->val.op);
}
</code>```

This function has three times as many assertions as code statements!

This is quite an extreme example because this function has to go down three levels to the bottom of the tree in order to find the PARAMETER_LIST which it then passes to parameter_list_to_symbols which adds the parameters to the symbol table.

The parse tree for a function definition in my compiler looks somewhat like this:

```<code>FUNCTION_DEF
 DECLARATOR
  IDENTIFIER [function_name]
  FUNCTION
   [return type]
   PARAMETER_LIST
    [declarators containing type and name for each parameter]
    [...]
 FUNCTION_BODY
  [statements in function body]
  [...]
</code>```

There are four things for me to test for each node that I use throughout the program.

assert(node) to check that the node is not NULL

assert(node->type == SYN_FOOBAR) to check that the node is of the expected type (like SYN_EXPRESSION or SYN_VARIABLE).

assert(child->val_type == AST_OP) to check that the node has the right kind of union value. Nodes can also contain other values. For example in nodes that store a string value child->val_type would be equal to AST_STRING. AST_OP means that the node is an operator node which is a node that has children.

I should probably also assert that each node has the right number of children with assert(child->val.op.n_childs == XXX) but I have not done that in this code example because it is already so full of assertions and asserting this too does not seem to add much value.

I have probably written hundreds of assertions like this in my code and it feels like this is getting quite hard to maintain but I am not sure how I should reorganize it.

The question

Am I "over asserting" stuff in my code? What things should I assert and what things can I assume are OK?

How should I structure my assertions to make them easier to maintain?

If you have more tips on using assertions and similar tests in code please mention them in your answer.

答:
Am I "over asserting" stuff in my code?

No.  You have even admitted that you know of at least one little thing that you could have asserted but you haven't, so you are not asserting enough.

What things should I assert and what things can I assume are OK?

Assert everything.  Assume nothing.

How should I structure my assertions to make them easier to maintain?

One technique that I use is that I have special assertion functions which are meant to be invoked from within assertions, to perform many assertions together. They always begin with the prefix 'assert', and they always return true, so that if none of the contained assertions fails, then the calling assertion will succeed.  So, for example:

```<code>boolean assertNodeOfTypeXYZIsOkay( Node* pNode )
{
    assert( pNode != NULL );
    assert( pNode->something_irrelevant_to_node_type );
    assert( pNode->type == NODE_TYPE_XYZ );
    assert( pNode->one_thing_relevant_to_node_type );
    assert( pNode->another_thing_relevant_to_node_type );
    ...
    return true;
}
</code>```

Which is invoked as follows:

```<code>assert( assertNodeOfTypeXYZIsOkay( pNode ) );
</code>```

This allows me to get many assertions out of the way, while at the same time enjoying the benefit of conditional compilation: if assertions are disabled, assertNodeIsOkay() will not only be empty, but it will not even be invoked.

If you have more tips on using assertions and similar tests in code please mention it in your answer.

Having more assertions than actual code is kind of rare, but it is not unheard of. It really depends on what you are doing, and it appears that your particular kind of project calls for this situation to happen.  That's fine.

Once your compiler matures and becomes stable, it will stop failing every once in a while due to oddly formulated input text. When that happens, you will be able to have a release build of your compiler on which assertions are disabled, for maximum performance. With that in mind, you should be applying assertions as liberally as you can, because they practically cost nothing.

Assertions are an excellent documentation tool, since a) comments are not enforceable by the compiler, and b) no comment ever was, or will ever be, as unambiguous as a piece of code stipulating the same thing.

Assertions reduce the complexity of your code, in contrast to virtually any other statement that you can use, which in fact increases the complexity of your code.

Assertions help build systems that, in the event of an error, can tell you what is wrong with themselves.  That, right there, is priceless.

Assertions are the best thing since sliced bread.

The question you should always be asking is not "should I assert this?" but "is there anything I forgot to assert?"

Body:
Am I "over asserting" stuff in my code?

No.  You have even admitted that you know of at least one little thing that you could have asserted but you haven't, so you are not asserting enough.

What things should I assert and what things can I assume are OK?

Assert everything.  Assume nothing.

How should I structure my assertions to make them easier to maintain?

One technique that I use is that I have special assertion functions which are meant to be invoked from within assertions, to perform many assertions together. They always begin with the prefix 'assert', and they always return true, so that if none of the contained assertions fails, then the calling assertion will succeed.  So, for example:

boolean assertNodeOfTypeXYZIsOkay( Node* pNode )
{
    assert( pNode != NULL );
    assert( pNode->something_irrelevant_to_node_type );
    assert( pNode->type == NODE_TYPE_XYZ );
    assert( pNode->one_thing_relevant_to_node_type );
    assert( pNode->another_thing_relevant_to_node_type );
    ...
    return true;
}

Which is invoked as follows:

assert( assertNodeOfTypeXYZIsOkay( pNode ) );

This allows me to get many assertions out of the way, while at the same time enjoying the benefit of conditional compilation: if assertions are disabled, assertNodeIsOkay() will not only be empty, but it will not even be invoked.

If you have more tips on using assertions and similar tests in code please mention it in your answer.

Having more assertions than actual code is kind of rare, but it is not unheard of. It really depends on what you are doing, and it appears that your particular kind of project calls for this situation to happen.  That's fine.

Once your compiler matures and becomes stable, it will stop failing every once in a while due to oddly formulated input text. When that happens, you will be able to have a release build of your compiler on which assertions are disabled, for maximum performance. With that in mind, you should be applying assertions as liberally as you can, because they practically cost nothing.

Assertions are an excellent documentation tool, since a) comments are not enforceable by the compiler, and b) no comment ever was, or will ever be, as unambiguous as a piece of code stipulating the same thing.

Assertions reduce the complexity of your code, in contrast to virtually any other statement that you can use, which in fact increases the complexity of your code.

Assertions help build systems that, in the event of an error, can tell you what is wrong with themselves.  That, right there, is priceless.

Assertions are the best thing since sliced bread.

The question you should always be asking is not "should I assert this?" but "is there anything I forgot to assert?"


答:
Know the technology inside and out.

Stop! Think! Go!

Architect for whatever may arise, but implement only what is really asked for.

KISS - Keep It Simple Stupid

If it is getting too complex, probably, it is not well thought. (Go back to 2 and 4)

Don't get stuck in 5. It often pays to start from scratch (Go back to 2 and 4)

Go back to 1.

Title: How to become a "faster" programmer?

OwnerDisplayName: Rui Craveiro


问:
Minimizing lock time (multithreaded app)
I have a web application written in C# which uses external dll written in C++. Communication between clients (web browsers) and a web application is done using SignalR. For communication between web application and the dll I am using a class and I create an instance of this class for every connected client. Instance of this class is stored in static list - it is shared between requests.

When a request is issued I fetch a connector (class to communicate with dll) from a list and then call a method which can take any time between 0.1 seconds and 3 seconds.

Beside that I have a job which is triggered every minute (using Hangfire) which loops through the list and disposes connectors which are inactive for certain time. Disposing connector can also take around 1 or 2 seconds.

Because application is multithreaded I am using a shared lock between the connector class and the job which disposes connector. Using the lock I avoid that connector is disposed between fetching the connector and calling the method.

In "pseudo-code" this would look like:

```<code>object globalLock = new object();

-- signalr hub method
public void HubMethod(string sessionId, string param) {
  lock (globalLock) {
    DllConnector connector = GetConnector(sessionId);
    connector.CallMethod(param);
  }
}

-- hangfire job
public void KillInactive() {
  lock (globalLock) {
    foreach (DllConnector connector in listOfConnectors) {
      if (connector.IsInactive()) {
         listOfConnectors.Remove(connector);
         connector.Dispose();
      }
    }
  }
}
</code>```

Question:

Because I am expecting "large" number of concurrent clients (requests) I am afraid that this won't scale - requests and the job will became unresponsive. How can I avoid this - to minimize waiting for the lock and to avoid disposed connectors between fetching and calling the method. Are there any patterns?

答:
The way these things are normally done is with threadpools.  See System.Threading.ThreadPool and read MSDN: How to: Use a Thread Pool

Also, the modern approach to sharing data in multithreaded environments is to avoid using locks and to use message-passing instead. This results in systems that are testable, and that once they are known to work, they tend to keep working without nasty surprises due to rare timing issues.

Note: invoking listOfConnectors.Remove( x ); within a foreach( var x in listOfConnectors ) will throw a 'collection was modified' exception.


问:
Handle Field Level Access on MVC Form
I came across and programming issue in my MVC app where I need to provide field-level security for some of my forms.  So I need to display or hide fields on the form, based on the user's permissions.  Additionally, I need to validate on post to see if the user can edit a field or add a new record.

The only solution I could come up with, was creating a HTML helper for the form and some code to walk over the fields posted to see if the user has permissions, but it doesn't seem right.  How would you handle something like this?  Maybe I am asking the wrong question, but there doesn't seem to be any real examples out there to look at.

How might you go about solving something like this?

答:
Do not render fields for which the user doesn't have permission.  The easiest way I can think of to do this is to use a partial view for those fields that require special permissions.

Remember, if you are accepting form data from the user, you still have to validate that data on the server, even for those fields that you aren't rendering, since it's still possible to inject those fields into the page before posting.

Further Reading

MVC4 Model Field Custom Authorization

Don’t Do Role-Based Authorization Checks; Do Activity-Based Checks

Disable some fields based on a user's permissions

Title: Handle Field Level Access on MVC Form


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答:
Avoid switching tasks too often. Distractions and task switching can kill a day, even if you use tools like Mylyn to manage your tasks.

Figure out a granularity (e.g., 30 minutes) and only work on things related to the task at hand. Anything else (new bug reports, emails about other issues, procedural matters that are unrelated) is delayed at least until the "next checkpoint". Make sure to disable popping up email notifications so you won't get sucked in.

It's especially effective if you have a buddy on your team who will let you know if things really melt down and require your immediate attention.

Title: How to become a "faster" programmer?

OwnerDisplayName: Uri


答:
Re-negotiate the estimates and timescales. Make sure you are the one who says how long something will take, and don't succumb to any "well, we need it done sooner" or "how about a stretch-target" suggestions.

Read Joel Spolsky's article on estimates, which basically advocates breaking the piece of work into small chunks, and estimate each one. If any of them are counted in days, break them down further until you have everything estimated in hours.

Title: How to become a "faster" programmer?

OwnerDisplayName: harriyott


答:
People who work in software product lines frequently wrestle with the same problems - how to write software that can vary depending on the deployment environment. There are several methods that have been identified to manage variability - build-time configuration, plug-in architecture models, run-time configuration of properties, configuration files, extending or modifying the source code for each variant. However, like you've found, there's no perfect solution. There are just trade-offs between the options.

To answer your question - yes, there are processes and methods, tools, architectures, and built software systems that achieve what you're trying to achieve. However, without a much deeper understanding of your software system and your organization, it's not possible to provide you with guidance on what, exactly to do.

The field of software product lines is very big. It ranges from requirements development through software maintenance and includes organizational structure, project and program management, and more. The books Software Product Lines: Practices and Patterns and Software Product Lines in Action: The Best Industrial Practice in Product Line Engineering can give you a good introduction to product line engineering, which addresses variability and reuse. More focused on software reuse is Software Reuse: Architecture, Process and Organization for Business Success.

Title: How to write highly changeable, highly complex software?

Body:
I know questions like this has been asked before. But none of them truly answered me.

How to keep a big and complex software product maintainable over the years?

How do you organize highly customized software?

...

We're working on a software that has a lot of rules and conditions. Also, those rules change frequently.

So far we've used many designs and techniques to cope with the requirements and implement them. To be more specific, let us focus on the following examples:

Using configurable options, so that values can be changed easily by business people, like the amount of debt a customer can undergo.

Problem: Soon there are like hundreds of configurable options, and even naming them becomes a nightmare, let alone managing them, changing them, tracking them in code, etc.

Using small satellite project files as additives to the main engine (something like extensible workflow), so that new rules can be added hot, and also unwanted rules can be removed from the process pipelines.

Problem: Soon the number of project files become so huge that the file-system management of the projects becomes a pain in the ass. What if for a short period of time business team needs a special customization that only lasts for two months, and then it should be removed from the system. Something like prepaid registration to track user-behavior for making the real decisions. Or a rule as simple as banning customers with suspicious activity that should be launched really soon.

It seems that our team is going the wrong path altogether. So how a team can handle creating highly-complex, highly-changeable software when it encounters the specific problems mentioned? What points should that team consider? Are there specific architectures or designs that will help us creating such software?


问:
Is it ok to use service locator for ubiquitously used dependencies?
We strictly adhere to inversion of control in our codebase, but that creates hellish constructors (yes, I know that means our classes aren't cohesive enough, this is a work in progress).
The thing is, that sometimes those dependencies are quite silly like a DateTime wrapper to enable date mocking, or the logger, or a TaskFactory wrapper which are not directly related to the business of the class and I do not think they require explicit introduction.

Could we ease the load on our ctors by using a service locator for those items which are passed all over the system? What would be the disadvantages?

答:
The question is, do you really need the dependencies at that level?

Things like a datetime wrapper can be used in two ways: either you need to get a date to assign to something (the order was placed 'now'), or you need some notion of time to perform an action (get me all the outstanding orders that were placed seven days before 'now'). In the first case, your dependency on the wrapper is absolute because the class needs it. In the second case, you can rework your method so that it takes any datetime and the logic of 'seven days before now' is pushed up, reducing the dependencies in your class.

As for logging, it again depends on your application. If you are logging exceptions you should probably only have the dependency on your logging classes in some top-level code. If you are doing logging as part of an auditing feature, you could have an implementation where events are raised from objects but only logged in one place, again reducing the dependency on the logging.

The main reason to avoid service locators is because they hide away the dependencies of your class. This makes it harder for you to design good classes (SOLID), makes testing them harder and turns what are compile-time errors for constructor-based dependencies into runtime errors for service locator-based classes.


问:
Making major version step in software development in separate repository
Currently we are planning to switch from our software version 5.x.x to 6.x.x. Such major releases contains in our case a lot of refactoring work and changing the software architecture. Instead of creating a new branch for version 6 (git), I thought to create a custom repository for this. In general, developing the new version bases on the old version, so it would be a copy.

My problem is that developing version 5 will not stop, because bug fixes and a few minor changes will be done. But now I have two versions I am working on, in two separate repositories. What is the best way to make changes in both, without copy code, or do the work twice? Is there some effective way?

Maybe some one else has the same issue before.

答:
One common way to handle this scenario is to use a trunk/branch concept.  What you do is have the single repository and branch the 5.x.x version for maintenance reasons.  Then you put all of the your new 6.x.x changes into the trunk.  That way you maintain all of the version history of your code.  This also allows you to check out the old version and make a targeted fix there without impacting the trunk.

Here is what this would look like:

```<code>                                                |------branch (5.x.x)
                                                |
----------------------------------------------------------------------Trunk (6.x.x)
</code>```

Then later if you ever need to have a  version 7.x.x you could do the same again:

```<code>             |------branch (5.x.x)
             |                             |---branch (6.x.x)
             |                             |
---------------------------------------------------------Trunk (7.x.x)
</code>```

Body:
One common way to handle this scenario is to use a trunk/branch concept.  What you do is have the single repository and branch the 5.x.x version for maintenance reasons.  Then you put all of the your new 6.x.x changes into the trunk.  That way you maintain all of the version history of your code.  This also allows you to check out the old version and make a targeted fix there without impacting the trunk.

Here is what this would look like:

                                                |------branch (5.x.x)
                                                |
----------------------------------------------------------------------Trunk (6.x.x)

Then later if you ever need to have a  version 7.x.x you could do the same again:

             |------branch (5.x.x)
             |                             |---branch (6.x.x)
             |                             |
---------------------------------------------------------Trunk (7.x.x)


答:
Several solutions are together with git. I have get good experiences with git-worktree for such situations. Excerpt from the manual pages:

```<code>Manage multiple working trees attached to the same repository.

A git repository can support multiple working trees, allowing you
to check out more than one branch at a time. With git worktree add
a new working tree is associated with the repository. This new working
tree is called a "linked working tree" as opposed to the "main working
tree" prepared by "git init" or "git clone". A repository has one main
working tree (if it’s not a bare repository) and zero or more linked
working trees.
</code>```

A complete copy here: https://git-scm.com/docs/git-worktree

Title: Making major version step in software development in separate repository

Body:
Currently we are planning to switch from our software version 5.x.x to 6.x.x. Such major releases contains in our case a lot of refactoring work and changing the software architecture. Instead of creating a new branch for version 6 (git), I thought to create a custom repository for this. In general, developing the new version bases on the old version, so it would be a copy.

My problem is that developing version 5 will not stop, because bug fixes and a few minor changes will be done. But now I have two versions I am working on, in two separate repositories. What is the best way to make changes in both, without copy code, or do the work twice? Is there some effective way?

Maybe some one else has the same issue before.

Body:
Several solutions are together with git. I have get good experiences with git-worktree for such situations. Excerpt from the manual pages:

Manage multiple working trees attached to the same repository.

A git repository can support multiple working trees, allowing you
to check out more than one branch at a time. With git worktree add
a new working tree is associated with the repository. This new working
tree is called a "linked working tree" as opposed to the "main working
tree" prepared by "git init" or "git clone". A repository has one main
working tree (if it’s not a bare repository) and zero or more linked
working trees.

A complete copy here: https://git-scm.com/docs/git-worktree


答:
Learn about The Zone, learn how to get yourself into it, and learn how to recognize when you aren't in it.

Once I am "in the zone" I am extremely
  productive and code just flows out of
  me, often I can get 2 or 3 days coding
  done in 1 day. But I find that often
  its hard to get to that place, I find
  myself procrastinating, getting
  distracted by other things (Stack Overflow for
  example).

Quote from what-tricks-do-you-use-to-get-yourself-in-the-zone

Title: How to become a "faster" programmer?

OwnerDisplayName: Dustin Getz


答:
Your desire to be a "faster" programmer by itself is laudable. However, not delivering on time does not mean you are slow, it means the project was planned poorly. Being a "faster" programmer will not help; it just means you'll whoosh past the deadline faster.

You (and your team) are doing one of the following mistakes (or all of them):

underestimating the work that needs to be done;

missing a big requirement or architecture piece during planning;

confusing work estimates with calendar estimates and not accounting for things like meetings/phone/other overhead;

There are multiple ways you can address any of the three above. But before you can improve on any of them, you need to know why things are going the way they are. Do a postmortem on the last two or three projects estimates vs. actual time taken and figure out where the extra time went.

I'll repeat it again - being slow at writing code won't cause missing the deadline, if you've planned it properly to account for that fact.

Title: How to become a "faster" programmer?

OwnerDisplayName: Franci Penov


问:
How can a computer round the last digit in a floating point representation?
I'm confused by how a computer rounds off the last digit in the floating point representation. For example, I'm told that x=1.24327789 is stored in a computer with a 6-digit capacity then it;s floating point representation would be x=0.124328x101, where clearly the last digit has been rounded.

My confusion refers to how the computer can have the capacity to round this last digit, if it hasn't a 7-digit capacity in order to know the 'last' digit.

I probably have a half-assed way of understanding this representation, but I really have no background in CompSci.

答:
If your computer uses IEEE 754 single precision floating point numbers (as most computers do), then it uses a representation where a number x is represented by a sign (+1 or -1), a mantissa which is an integer ≥ 2^23 and ≤ 2^24 - 1, and a binary exponent b; the number represented is sign * mantissa * 2^b. (There are some details not mentioned). </p>

<p>A number from 1 to 2 has an exponent b = -23, so that mantissa * 2^b is between 1 and 2. The mantissa is an integer, so the number is a multiple of 2^-23. You can calculate that 2^-23 is a bit over 0.000 000 119. </p>

Body:
If your computer uses IEEE 754 single precision floating point numbers (as most computers do), then it uses a representation where a number x is represented by a sign (+1 or -1), a mantissa which is an integer ≥ 2^23 and ≤ 2^24 - 1, and a binary exponent b; the number represented is sign * mantissa * 2^b. (There are some details not mentioned).

A number from 1 to 2 has an exponent b = -23, so that mantissa * 2^b is between 1 and 2. The mantissa is an integer, so the number is a multiple of 2^-23. You can calculate that 2^-23 is a bit over 0.000 000 119.


问:
Putting a password in a REST API call
Suppose I have a REST API that is also used to set/reset passwords. Let's also suppose that this works over a HTTPS connections. Is there any good reason not to put that password in the call path, let's also say I will encode it in BASE64?

An example would be to reset a password like this:

```<code>http://www.example.com/user/joe/resetpassword/OLDPASSWD/NEWPASSWD
</code>```

I understand BASE64 is no encryption, but I only want to protect the password to shoulder surfing in this case.

答: A good server logs all requests sent to it, including URLs (often, without variable part after '?'), source IP, execution time...  Do you really want this log (potentially read by a wide group of admins) to contain critically secure info as passwords? Base64 isn't a stopper against them.</p>

Title: Putting a password in a REST API call


答:
Apart from security, the problem with this is that it isn't a very RESTful approach.

OLDPASSWD and NEWPASSWD don't stand for anything in your resource hierarchy and even worse, the operation isn't idempotent.

So you can only use POST as your verb, and you should not include the two passwords in your resource path.

Title: Putting a password in a REST API call

Body:
Suppose I have a REST API that is also used to set/reset passwords. Let's also suppose that this works over a HTTPS connections. Is there any good reason not to put that password in the call path, let's also say I will encode it in BASE64?

An example would be to reset a password like this:

```<code>http://www.example.com/user/joe/resetpassword/OLDPASSWD/NEWPASSWD
</code>```

I understand BASE64 is no encryption, but I only want to protect the password to shoulder surfing in this case.


答:
What you are proposing is neither secure nor RESTful.

@Netch has already mentioned the issue with logs, but there is also another issue in that you are showing passwords being sent by HTTP, making it trivial to capture passwords with any sort of wire sniffer or man-in-the-middle attack.

When you do a GET request using REST, the different elements in the URL represent more fine grained elements.  Your URL reads like you are returning a NEWPASSWD part of an OLDPASSWD that's part of a resetpassword.  That does not make any sort of semantic sense.  GETs should not be used to save data.

You should be doing something like this:

```<code>POST https://www.example.com/user/joe/resetpassword/
{oldpasswd:[data], newpasswd:[data]}
</code>```

POST because you are writing data, and https because you don't want it sniffed.

(This is really the low-bar security.  The absolute minimum you should do.)

Title: Putting a password in a REST API call

Body:
What you are proposing is neither secure nor RESTful.

@Netch has already mentioned the issue with logs, but there is also another issue in that you are showing passwords being sent by HTTP, making it trivial to capture passwords with any sort of wire sniffer or man-in-the-middle attack.

When you do a GET request using REST, the different elements in the URL represent more fine grained elements.  Your URL reads like you are returning a NEWPASSWD part of an OLDPASSWD that's part of a resetpassword.  That does not make any sort of semantic sense.  GETs should not be used to save data.

You should be doing something like this:

POST https://www.example.com/user/joe/resetpassword/
{oldpasswd:[data], newpasswd:[data]}

POST because you are writing data, and https because you don't want it sniffed.

(This is really the low-bar security.  The absolute minimum you should do.)


答:
Here's what works for me:

Break your work down into small tasks which are (1) defined in scope (2) short - e.g. 2 hours.

Start the day by writing them down on a paper, in order. Draw some lines through - stuff you expect to get done before lunch, stuff you'll get done by end of day, etc.

Work your list, crossing items off as you go.

Time box things - if something's starting to drag, give yourself a time limit to research before you ask for help, or solve in a simpler manner.

If possible, structure your work so that you're publicly committing to these timeframes - entering estimates in bug tracking, etc.

If you catch yourself killing time researching, reading, etc., then invert the order - for example, allow yourself a 10 minute reward if you successfully complete a 1 hour task on schedule.

I've seen several comments that you should spend less time on Stack Overflow. If you're using it right, Stack Overflow should make you more efficient, not less. Steer clear of discussions and focus on using it to get work done.

Title: How to become a "faster" programmer?

OwnerDisplayName: Jon Galloway


问:
Intentional misspellings to avoid reserved words
I often see code that include intentional misspellings of common words that for better or worse have become reserved words:

klass or clazz for class: Class clazz = ThisClass.class

kount for count in SQL: count(*) AS kount

Personally I find this decreases readability.  In my own practice I haven't found too many cases where a better name couldn't have been used — itemClass or recordTotal.

An example from the JavaDocs for Class show this in the parameters:

```<code> public <U> Class<? extends U> asSubclass(Class<U> clazz)
</code>```

Does this show a reasonable use case?

答:
I think misspellings are always a bad idea. It's just not nice on your readers. I, for one, would be wondering whether I missed something when I see the word klass. (Did they mean class, or did they mean the pirate?) At least to me, all misspellings that I recognize are irritating.

For the very few cases, where the reserved word is really the only significant thing that is known about the variable, I would use the following alternatives:

If it's a function argument, use aClass instead of class.

If it's a local or member variable, use myClass instead of class.

If it's an accessor, use getClass() instead of class().

Of course, the added prefix is pretty pointless, and should only ever be used as a last resort, consequently. But at least it does not interfere with the mental parser of your reader, and it's a failsafe way to avoid reserved words.


答:
The proposed scheme has issues in several areas.

Security

URL paths are frequently logged; putting unhashed passwords in the path is poor practice.

HTTP

Authentication/authorization information should appear in the Authorization header. Or potentially, for browser-based stuff, the Cookie header.

REST

Verbs such as resetpassword in your URL are generally a clear sign of a non-representational state transfer paradigm. A URL should represent a resource. What does it mean to GET resetpassword? Or DELETE?

API

This scheme requires always knowing the previous password. You will probably want to allow for more cases; e.g. the password is lost.

You could use Basic or Digest authentication, which is are well understood schemes.

```<code>PUT /user/joe/password HTTP/1.0
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Content-Type: text/plain
Host: www.example.com

NEWPASSWD
</code>```

It doesn't put ultra-sensitive information in the path, and it follows HTTP and REST conventions.

If you needed to allow for some other mode of authorization (e.g. some token sent through a verified channel to reset the password), you can simply use a different Authorization header without having to change anything else.

Title: Putting a password in a REST API call

Body:
The proposed scheme has issues in several areas.

Security

URL paths are frequently logged; putting unhashed passwords in the path is poor practice.

HTTP

Authentication/authorization information should appear in the Authorization header. Or potentially, for browser-based stuff, the Cookie header.

REST

Verbs such as resetpassword in your URL are generally a clear sign of a non-representational state transfer paradigm. A URL should represent a resource. What does it mean to GET resetpassword? Or DELETE?

API

This scheme requires always knowing the previous password. You will probably want to allow for more cases; e.g. the password is lost.

You could use Basic or Digest authentication, which is are well understood schemes.

PUT /user/joe/password HTTP/1.0
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Content-Type: text/plain
Host: www.example.com

NEWPASSWD

It doesn't put ultra-sensitive information in the path, and it follows HTTP and REST conventions.

If you needed to allow for some other mode of authorization (e.g. some token sent through a verified channel to reset the password), you can simply use a different Authorization header without having to change anything else.


问:
Can this be considered an API?
I'm writing my first API, but I think I screwed it up from the design. It's a simple CRUD API which behave like this:

READ: /api/data gets redirected to api.php?data1=data. POST variables: user, HMAC, action (read).

CREATE: /api/newgets redirected to api.php. POST variables user, HMAC, action, data1, data2, data3.

DELETE: api/delete gets redirected to api.php. POST variables: user, HMAC, action, data1.

UPDATE: api/update gets redirected to api.php. POST variables: user, HMAC, action, data1, data2, data3.

Then in my api.php I have for if statements for performing each action based on $_POST['action']

However... is this an API? The READ behaves as expected I guess, but not sure if the other methods comply to the definition of an API.

答:
An API, probably yes. A REST API probably not.

If it works and another program can interact with it then it's an API (Application Programming Interface)  IMHO.

However, your implementation can probably be improved.

It looks like you are going Restful. Typically HTTP methods (GET, POST, PUT, DELETE...) and used on a single URL that represents your entity.

Example:

GET /api/v1/widgets/1234

Would return widget with id=1234

POST /api/v1/gadgets

Creates a new widget. Data/payload would be sent in the body of the post as form data, json etc.

In your PHP code (or whatever language) use the HTTP method in the incoming request context to switch to a function to handle each method.

This is basically an MVC type pattern. There'll be plenty of articles on the Web that explain this in detail.

Generally these days there are frameworks that make life easier. Examples are ASP.NET Web API and Restify for NodeJS. Unfortunately, I don't know much about the PHP ecosystem. This article may help
http://www.gajotres.net/best-available-php-restful-micro-frameworks/

Title: Can this be considered an API?