问:
Django CBVs vs FBVs
For creating a large Django project with many apps, my first initial thought was to used Class Based Views (as the Django tutorials seem to emphasize). However, I noticed that due to a lot of the customizations to each app (multiple forms on each page etc), it became very tedious and was much easier to just implement Function Based Views where I just added decorators such as @require_GET and @login_required for easy authentication and method not supported messages, and am thoroughly convinced I will never go back to CBVs.

From a long term support perspective, has anyone had issues with choosing FBVs over CBVs? Am I doing something in the short term that will hurt long term, and could perhaps be solved by custom Class Based Views?

Update 12/2014

I have now become a complete advocate for CBVs! I will never go back! The reusability, inheritance, mixings create for an absolutely reusable and flexible system. I have reduced the amount of code I've used by a huge percent thanks to CBVs. There was admittedly a learning curve and I did not immediately see the results, but after refactoring I could not be happier. For large projects, it seems that CBVs are a necessity.

答:
CBVs tend to make a lot of things easier once you get the hang of them. While it may seem like everything is extremely complicated if you just subclass TemplateView for everything, CBVs take a lot of unnecessary boilerplate away when you really need to have them.

CBVs also help organize things into bite-size pieces. The name of the template used for your view will pretty much always be the template_name variable. What happens when my function gets a GET request? It calls get(). POST? That's post(). Instead of having multiple codepaths, you now have two mutually exclusive functions that each independently handle a different scenario. What's in my context? Check out get_context_data. Need to display info about a DB object? Make a DetailView, with the PK in the URL and the model defined in the view. No manually coding DB lookups (though you can specialize the queryset if you want it). If you're dealing with a form, it will run all the validation for you, and then you just need to define form_valid (runs when the form is valid), and probably don't even need to bother with form_invalid, since the default is just to recall the page with the errors in the form.

The key to using CBVs effectively is to know which CBV to use for the right scenario. Writing up a FBV to display an object creation form, validate it, and create the object is a pain in the butt, but a CreateView CBV just requires the form class, model class, and template name. DetailView is great for just spitting out info from a database. If you're doing something like a blog where year/month/day lookup would be useful, there's a half a dozen different date-based CBVs that will automate most of it.

Most notably, FBVs give you no choice other than to create a monolithic function, and while extremely simple views might be faster and easier in FBVs, the fact that CBVs encapsulate each step of the rendering process (dispatching, retrieving templates, handling different request types, passing context variables, validating forms, etc) makes anything even remotely complex much easier to break down. You also generally don't need to declare most CBV functions, since the defaults are pretty sane. If you let the CBVs do most of the work for you, you'll end up with a much better appreciation for them.

A couple tips that I've found extremely helpful:

https://github.com/brack3t/django-braces - Braces is a CBV mixin library, which provides a lot of helpful mixins for CBVs. Instead of using an FBV and decorating with @login_required, you can make your view a subclass of LoginRequiredMixin and it'll do the same thing. It also has mixins for superuser access, permission based access, and even JSON access for APIs and AJAX calls.

If you're absolutely attached to your decorators, note that you can still use FBV decorators for CBVs by decorating the dispatch function in your CBV. As a result, the following is equivalent:

```<code>@login_required
def FunkyView(request):
    return HttpResponse("Funky!")

class ClassyView(View):
    @login_required
    def dispatch(self, request, *args, **kwargs):
        super(ClassyView, self).dispatch(request, *args, **kwargs)
</code>```

You can also decorate the as_view function in the URLConf, like so:

```<code>url(r'^classy/$', login_required(ClassyView.as_view()), name='decorated_classy')
</code>```

http://ccbv.co.uk/ is the ultimate resource for Class Based Views, giving you  an easy way to view CBV code, see what inherits from what, and see where functions are available.

Title: Django CBVs vs FBVs

Body:
CBVs tend to make a lot of things easier once you get the hang of them. While it may seem like everything is extremely complicated if you just subclass TemplateView for everything, CBVs take a lot of unnecessary boilerplate away when you really need to have them.

CBVs also help organize things into bite-size pieces. The name of the template used for your view will pretty much always be the template_name variable. What happens when my function gets a GET request? It calls get(). POST? That's post(). Instead of having multiple codepaths, you now have two mutually exclusive functions that each independently handle a different scenario. What's in my context? Check out get_context_data. Need to display info about a DB object? Make a DetailView, with the PK in the URL and the model defined in the view. No manually coding DB lookups (though you can specialize the queryset if you want it). If you're dealing with a form, it will run all the validation for you, and then you just need to define form_valid (runs when the form is valid), and probably don't even need to bother with form_invalid, since the default is just to recall the page with the errors in the form.

The key to using CBVs effectively is to know which CBV to use for the right scenario. Writing up a FBV to display an object creation form, validate it, and create the object is a pain in the butt, but a CreateView CBV just requires the form class, model class, and template name. DetailView is great for just spitting out info from a database. If you're doing something like a blog where year/month/day lookup would be useful, there's a half a dozen different date-based CBVs that will automate most of it.

Most notably, FBVs give you no choice other than to create a monolithic function, and while extremely simple views might be faster and easier in FBVs, the fact that CBVs encapsulate each step of the rendering process (dispatching, retrieving templates, handling different request types, passing context variables, validating forms, etc) makes anything even remotely complex much easier to break down. You also generally don't need to declare most CBV functions, since the defaults are pretty sane. If you let the CBVs do most of the work for you, you'll end up with a much better appreciation for them.

A couple tips that I've found extremely helpful:

https://github.com/brack3t/django-braces - Braces is a CBV mixin library, which provides a lot of helpful mixins for CBVs. Instead of using an FBV and decorating with @login_required, you can make your view a subclass of LoginRequiredMixin and it'll do the same thing. It also has mixins for superuser access, permission based access, and even JSON access for APIs and AJAX calls.

If you're absolutely attached to your decorators, note that you can still use FBV decorators for CBVs by decorating the dispatch function in your CBV. As a result, the following is equivalent:

@login_required
def FunkyView(request):
    return HttpResponse("Funky!")

class ClassyView(View):
    @login_required
    def dispatch(self, request, *args, **kwargs):
        super(ClassyView, self).dispatch(request, *args, **kwargs)

You can also decorate the as_view function in the URLConf, like so:

url(r'^classy/$', login_required(ClassyView.as_view()), name='decorated_classy')

http://ccbv.co.uk/ is the ultimate resource for Class Based Views, giving you  an easy way to view CBV code, see what inherits from what, and see where functions are available.


问:
How does a CLI-oriented programmer's workflow differ from a GUI-oriented one?
I've heard a lot about the advantages of doing less programming work in GUI apps and using more command-line tools (especially with regard to getting things done more efficiently).  However, since I don't understand how my workflow would be different if I depended more on command-line tools, I can't readily evaluate whether there's enough of a payoff for me personally to invest time and effort learning a new toolset and changing my workflow.

Right now:

I code some side projects in languages like C/C++/D/C#/Java/Python using Visual Studio, Eclipse, etc., and run them by setting up the build settings, and pressing F5 to build/run.

I'm developing a web program at work, so that involves using Django to set up a server, connect to a database, etc... almost all within the SciTE text editor.

For launching regular programs, I use Launchy... still no terminal. :)

For copying files and whatnot, I use a regular find/move in the graphical file manager (Windows Explorer, Nautilus).

Debugging: I use either Visual Studio or Debugging tools for Windows (if I'm on Windows). I haven't done much debugging on Linux, but for the things I've done, I've used Eclipse (also for Java on Windows).

At work: To connect to the build system and set up a project, I just use tools that have been integrated into Eclipse for my use -- no need for a terminal or anything (although I'm certainly welcome to use a terminal if I indeed want to)

What is it like to do these things in CLI?  Which parts become more/less efficient?  Which aspects of my workflow would need to be changed to get the greatest advantage from a shift to working mostly in CLI?  In other words... If you magically transformed me into a command-line guru, how would my new coding workflow be different from my current, GUI-centered, way of doing things?

答:
The way I work favours GUI by far.

Typical usage:

Three IDEs for three different platforms. Also a Notepad++ window for some scripts. There's simply no way I would be able to remember commands for all those build systems. The problem with CLI is you need to know a lot of details just to get a build working. Modern IDES normally have some appropriate options in there by default. You can always have a closer look when the time comes.

SVN or Git integrated. There's so many options for a program which is ancillary to programming, and most of the time I'm only doing commit or update.

Network stuff: Lucky me, I get to do all the network setup in our office as well. Most of the network boards will give you a load of CLI commands, but if there's one thing where you need an overview of state, it's firewall and routing. For routing I  can just about live with command line, but firewalls get complicated, and if there's one thing GUIs are good at it's displaying lots of info.

Generally there's a lot of moving from one thing to another. Contexts switches are easier with a visual context.

As for the main benefit of CLI, scripting, I barely ever do that. The repeated tasks we have are just cron job apps that's we've thrown together in c# and not often changed. We do have ways to get things running in Linux, but mainly it's ported (boost), so messing about with files and such things are minimised. And if things get hairy, there are good IDEs for Linux too.

ContentLicense: CC BY-SA 3.0


问:
What UML diagram should be used for modelling permissions/users/files in Linux?
If I am planning a structure for support testing in Linux, a structure that will contain packages, such files as shell and build scripts, app configurations, DBs, sources, tests and jars for to be managed, applications for be managers, users, permissions, etc., what diagram could be used for it? Just now I am using the Component Diagram with some stereotyping, but it is not at all convenient in the part of permissions/users stuff. There are such diagrams as RBAC, but they are not UML, and it remains unclear how to combine them.

An example picture and/or a real experience description would be highly appreciated. But any fresh thought will be useful, too.

答:
I think you would need more than one UML diagarams to model.

Package and component diagram to model the app, config, db etc...

Use case diagram to model the authorization and authentication part.


问:
Front-end structure of large scale Django project
Few days ago, I started to work in new company. Before me, all front-end and backend code was written by one man.

As you know, Django app contains two main directories for front-end: /static - for static(public) files and /templates - for django templates

Now, we have large application with more than 10 different modules like: home, admin, spanel, mobile etc.

This is current structure of files and directories:

FIRST - /static directory. As you can see, it is mixed directories with some named like modules, some contains global libs.

one more:

SECOND - /templates directory. Some directories named like module with mixed templates, some
depends on new version =), some used only in module, but placed globally.

and more:

I think, that this is ugly, non-maintainable, put-in-stress structure!

After some time spend, I suggest to use this scheme, that based on module-structure.

At first, we have version directories, used for save full project backup, includes: /DEPRECATED directory - for old, unused files and /CURRENT (Active) directory, that contains

production version of project.

I think it's right, because we can access to older or newer version files fast and easy.
Also, we are saved from broken or wrong dependencies between different versions.

Second, in every version we have standalone modules and global module.

Every module contains own /static and /templates directories. This structure used to avoid broken or wrong dependencies between different modules, because every module has own js app,  css tables and local images.

Global module contains all libraries, main style-sheets and images like logos or favicon.

I think, this structure is much better to maintain, update, refactoring etc.

My question is:

How do you think, is this scheme better than current? Can this scheme live, or it is not possible to implement this in Django app?

答:
By "module", do you mean app? Django already has a pretty standard structure for where to place files.

I suggest you consider using that structure. For one thing, just about all help you will get will have examples with this structure.

As for your structure, it looks pretty sprawling to me. It's up to you, though. In particular if it fits the business problem, you won't have issues navigating it.


问:
Should the commit history be used to convey critical information to developers?
During a meeting regarding the rollback of a third-party SDK from the latest version it was noted that the our developers already flagged in the commit history that the latest version should not be used.

Some developers argued that this was a bad practice and it should have instead been noted either in the source file (i.e. // Don't upgrade SDK Version x.y.z, see ticket 1234) or in a project level README file. Others argued that since the commit history is part of the project documentation it is an acceptable location for such information since we should all be reading it anyway.

Should the commit history be used to convey critical information to other developers or should such information be duplicated to another location such as a project README or comments in the relevant source file?

答:
Expanding on Karl's answer, I would go with an approach that automatically enforces the restriction as part of the checkin process itself. You need something that does not require any proactive action on behalf of the developer, such as reading a doc/wiki/README, and can not be overridden covertly.

In TFS source control land you can code custom checkin policies that execute rules on checkin. For example, you could define a policy that evaluates the version in a config file with a pending checkin and will fail if it does not equal x.y.z. These rules actually prevent the developer from performing the checkin and can provide a descriptive message. The policies can be overridden, but it is possible to generate alerting when this happens.

An alternative could be gated-checkins that fail will with some form of unit test that either directly or indirectly evaluates the SDK version, as Karl mentioned.

I appreciate this answer is very TFS-centric, but possibly similar features exist in the version control/CI systems that apply in your situation (if not TFS).


问:
Long running task initiated in the web site
The plan is to develop generic solution for long running task initiated in web site by users such as:
1. upload large file and do some custom processing and then insert in the database.
2. export large amount of data

But we do not want to run these tasks on web servers and instead run on dedicated other sever. I have a couple of following solutions but looking for suggestion on these solutions or a new option.

Web site calls WCF service on other server (one-way operations / fire-forget). WCF service has all the information to process request and task will run in WCF service.

Window service but not sure how Window service will start the job as soon as possible as we do not want any delay between user submitted the form and process start time. Need some kind of flag for Window service to start.

答:
Actually, one way to host WCF services is as a windows services. The difference is how customized those services can be.

The windows service can keep listening a port and response at real time when you use them. Actually a service can have several clients connected at the same time. for example IIS.

To me, seems to be easier the WCF fire and forget option; less coding for the same result.


问:
When copy/pasting private methods is it necessary to carry along the Javadoc?
So, unfortunately, I'm stuck with code where I'm doing this:

```<code>@Override
method A{
    //calls private methods 1-8
}

private method 1{
    //copy/pasted
}
</code>```

And so on for all of the private methods. I'd have preferred if the developers of the method I'm overriding had made the private methods protected, but I can't change that now.

All of these private methods have javadoc along with them - should I carry this along with the copy/pasted functions in my class and adjust them accordingly, or not waste my time since it is documented in the original file?

答: For questions like this, I start by answering the question "what makes the code easier to understand for me and my organization?". That's by far the most important consideration. </p>


问:
What would the register-machine bytecode for this code look like?
I hope this kind of question isn't off-topic on this site.

I'm finally getting the hang of what a stack based machine is, and how to compile code for it. For example, the following code: 2 * 5 + 1 would compile to this bytecode:

```<code>push 2
push 5
mult
push 1
add
</code>```

However what I want to understand is, the fundamental differences between compiling for a stack based machine and compiling for a register based machine.

Basically I want to see what a register-machine's bytecode would look like, as opposed to a stack-machine's bytecode.

To understand this, I'd like to ask you to show me what the bytecode for the above expression would look like, for a register machine. I.e. what this: 2 * 5 + 1 would compile to.

答:
Fortunately, there are a variety of well-known real register machines that you can look at. For example, x86 code for the above might be:

```<code>mov eax, 2
mul eax, 5
add eax, 1
</code>```

(In x86 Intel notation, the destination is the left operand.)

Body:
Fortunately, there are a variety of well-known real register machines that you can look at. For example, x86 code for the above might be:

mov eax, 2
mul eax, 5
add eax, 1

(In x86 Intel notation, the destination is the left operand.)


问:
How can I figure out if another project is mostly maintenance and bugs?
I started working in a relatively big company that unfortunately has its share of quite a lot of legacy code and I ended up spending an extra ordinary amount of time in maintainance and bug fixes.

I would like to switch project as on the surface there are other project that "seem" interesting. The issue is I am not really sure if it is any better there either.

I have asked some colleagues to see what's going on and they "claim" that they are involved in cool things but I don't really believe them as in one of the cases I know for sure he is the same situation as I am.

So my question is the following:

If I don't have someone I can really trust to make a good choice about swapping to another project is there a way I could find out myself (I mean if it is the same everywhere)?

One idea would be to do some "reverse" engineering i.e. start tracking each persons commit in the repository to figure out what he's been up to. But this approach seems to me irrational.

Surely there must be a better way?

答:
The main thing to figure out is how old is the project and is it replacing / converting another project or truly a new project not attempted before.

I would try and find this out by talking to the people currently on the project.  Use some discretion of course, just ask them about what they actually do and draw your own conclusions.

You may also find the following viewpoints worth mulling over:

generally 80% of programming is maintenance and bug fixes.

consider legacy code to include... the code you currently have in production

legacy code is also the code that... pays the bills.  and maybe your salary.

as soon as a new project actually goes live, maintenance and bug fixes are required.

new projects often have more bugs than anticipated so the switch to bug fixing is often quick.


问:
Why are private variables described in the publicly accessible header file?
OK, so hopefully this is a subjective enough question for Programmers, but here goes.  I am continuously broadening my knowledge of languages and software engineering practices... and I've run into something that just makes no sense to me whatsoever.

In C++, class declarations include private: methods and parameters in the header file, which, theoretically, is what you pass to the user to include if you make them a lib.

In Objective-C, @interfaces do pretty much the same thing, forcing you to list your private members (at least, there's a way to get private methods in the implementation file).

From what I can tell, Java and C# allow you to provide an interface/protocol which can declare all the publicly accessible properties/methods and gives the coder the ability to hide all implementation details in the implementation file.

Why?  Encapsulation is one of the main principles of OOP, why do C++ and Obj-C lack this basic ability?  Is there some kind of best-practices work-around for Obj-C or C++ that hides all implementation?

Thanks,

答:
Due to the design of C++, in order to create an object on the stack the compiler must know how big it is. To do this it needs to have all the fields present in the header file, as that is all that the compiler can see when the header is included.

For instance if you define a class

```<code>class Foo {
    public int a;
    private int b;
};
</code>```

then sizeof(Foo) is sizeof(a) + sizeof(b). If there was some mechanism to separate the private fields, then the header might contain

```<code>class Foo {
    public int a;
};
</code>```

with sizeof(Foo) = sizeof(a) + ???.

If you want to really hide private data, try the pimpl idiom, with

```<code>class FooImpl;
class Foo {
    private FooImpl* impl;
}
</code>```

in the header and a definition for FooImpl only in Foo's implementation file.

ContentLicense: CC BY-SA 2.5

Body:
Due to the design of C++, in order to create an object on the stack the compiler must know how big it is. To do this it needs to have all the fields present in the header file, as that is all that the compiler can see when the header is included.

For instance if you define a class

class Foo {
    public int a;
    private int b;
};

then sizeof(Foo) is sizeof(a) + sizeof(b). If there was some mechanism to separate the private fields, then the header might contain

class Foo {
    public int a;
};

with sizeof(Foo) = sizeof(a) + ???.

If you want to really hide private data, try the pimpl idiom, with

class FooImpl;
class Foo {
    private FooImpl* impl;
}

in the header and a definition for FooImpl only in Foo's implementation file.


答:
Register machine bytecode often comes in three-address form, that is, it talks about data flow relationships between registers, and operations take explicit destination registers. So a basic instruction set may look like this:

```<code>set register, constant
mul out, in1, in2
add out, in1, in2
</code>```

You could assume you have an infinite number of registers r0, r1, etc. and rewrite this in SSA form:

```<code>set r0, 2       // int r0 = 2;
set r1, 5       // int r1 = 5;
mul r2, r0, r1  // int r2 = r0 * r1;
set r3, 1       // int r3 = 1;
add r4, r2, r3  // int r4 = r2 + r3;
</code>```

Then various analyses and optimisations become easy. You can reuse registers that are no longer active:

```<code>set r0, 2       // int r0 = 2;
set r1, 5       // int r1 = 5;
mul r0, r0, r1  // r0 *= r1;
set r1, 1       // r1 = 1;
add r0, r0, r1  // r0 += r1;
</code>```

You can also allow instructions to take immediate constants, rather than loading everything into registers:

```<code>set r0, 2      // int r0 = 2;
mul r0, r0, 5  // r0 *= 5;
add r0, r0, 1  // r0 += 1;
</code>```

When you do that, you notice a resemblance with existing register architectures such as x86, and indeed you can perform register allocation to map your virtual register machine onto real hardware:

```<code>mov eax, 2
mul eax, 5
add eax, 1
</code>```

In either case, the bytecode is a flat representation of a data and control flow graph:

```<code>+---+
| 2 |
+---+
  r0
  |
  | +---+
  | | 5 |
  | +---+
  |   r1
  |   |
+-------+
|   ×   |
+-------+
  r2
  |
  | +---+
  | | 1 |
  | +---+
  |   r3
  |   |
+-------+
|   +   |
+-------+
  r4
  |
</code>```

In the stack notation, each stack operation corresponds to one row of this diagram, and the width of the diagram at any point corresponds to the maximum stack depth at that point. In the SSA form, each register corresponds to a point in the graph where a value is produced. They’re simply different structures for talking about the same thing.

Title: What would the register-machine bytecode for this code look like?

Body:
I hope this kind of question isn't off-topic on this site.

I'm finally getting the hang of what a stack based machine is, and how to compile code for it. For example, the following code: 2 * 5 + 1 would compile to this bytecode:

```<code>push 2
push 5
mult
push 1
add
</code>```

However what I want to understand is, the fundamental differences between compiling for a stack based machine and compiling for a register based machine.

Basically I want to see what a register-machine's bytecode would look like, as opposed to a stack-machine's bytecode.

To understand this, I'd like to ask you to show me what the bytecode for the above expression would look like, for a register machine. I.e. what this: 2 * 5 + 1 would compile to.

Body:
Register machine bytecode often comes in three-address form, that is, it talks about data flow relationships between registers, and operations take explicit destination registers. So a basic instruction set may look like this:

set register, constant
mul out, in1, in2
add out, in1, in2

You could assume you have an infinite number of registers r0, r1, etc. and rewrite this in SSA form:

set r0, 2       // int r0 = 2;
set r1, 5       // int r1 = 5;
mul r2, r0, r1  // int r2 = r0 * r1;
set r3, 1       // int r3 = 1;
add r4, r2, r3  // int r4 = r2 + r3;

Then various analyses and optimisations become easy. You can reuse registers that are no longer active:

set r0, 2       // int r0 = 2;
set r1, 5       // int r1 = 5;
mul r0, r0, r1  // r0 *= r1;
set r1, 1       // r1 = 1;
add r0, r0, r1  // r0 += r1;

You can also allow instructions to take immediate constants, rather than loading everything into registers:

set r0, 2      // int r0 = 2;
mul r0, r0, 5  // r0 *= 5;
add r0, r0, 1  // r0 += 1;

When you do that, you notice a resemblance with existing register architectures such as x86, and indeed you can perform register allocation to map your virtual register machine onto real hardware:

mov eax, 2
mul eax, 5
add eax, 1

In either case, the bytecode is a flat representation of a data and control flow graph:

+---+
| 2 |
+---+
  r0
  |
  | +---+
  | | 5 |
  | +---+
  |   r1
  |   |
+-------+
|   ×   |
+-------+
  r2
  |
  | +---+
  | | 1 |
  | +---+
  |   r3
  |   |
+-------+
|   +   |
+-------+
  r4
  |

In the stack notation, each stack operation corresponds to one row of this diagram, and the width of the diagram at any point corresponds to the maximum stack depth at that point. In the SSA form, each register corresponds to a point in the graph where a value is produced. They’re simply different structures for talking about the same thing.


答:
Just as one does not copy and paste all of the methods from the superclass when writing code, so to should one not copy and paste all of the documentation when documenting overridden methods.

From javadoc at docs.oracle.com:

{@inheritDoc}

Inherits (copies) documentation from the "nearest" inheritable class or implementable interface into the current doc comment at this tag's location. This allows you to write more general comments higher up the inheritance tree, and to write around the copied text.

This tag is valid only in these places in a doc comment:

In the main description block of a method. In this case, the main description is copied from a class or interface up the hierarchy.

In the text arguments of the @return, @param and @throws tags of a method. In this case, the tag text is copied from the corresponding tag up the hierarchy.

See Automatic Copying of Method Comments for a more precise description of how comments are found in the inheritance hierarchy. Note that if this tag is missing, the comment is or is not automatically inherited according to rules described in that section.

And thus, you inherit the documentation from the superclass.  If the superclass documentation updates, yours does too.

Just as with inheritance of code, you can extend the comments.

Lets see what things look like in an IDE and code...

```<code>public interface IFace {
    /**
     * This is a method.
     */
    public void method1();

    /**
     * This is also a method
     */
    public void method2();
}
</code>```

This is just an interface with some javadocs and two methods.

Lets have a class implement this...

```<code>public class CClass implements IFace {

    /**
     * {@inheritDoc}
     * This just returns.
     */
    public void method1() {
    }

    public void method2() {
    }
}
</code>```

And then the javadocs themselves:

public void method1()
This is a method. This just returns.
Specified by:
method1 in interface IFace
```
<p>img</p>
<pre class="lang-none prettyprint-override"><code>public void method2()
Description copied from interface: IFace This is also a method
Specified by:
method2 in interface IFace
</code>```

img

The first thing to see is that with method1, the javadoc is included and extended with the {@inheritdoc}.  However, no javadoc will also inherit the javadoc from wherever.

If you are not changing the javadoc, don't specify it.  Let the IDE do its thing. Let the automatic javadoc generation do its thing too.  Copying and pasting documentation can be just as bad as copying and pasting code as it violates DRY and may lead to the documentation from the superclass or interface getting out of sync with the documentation of the method.

On the other hand, if you are going to write something more, inherit the documentation and write it.

Title: When copy/pasting private methods is it necessary to carry along the Javadoc?

Body:
So, unfortunately, I'm stuck with code where I'm doing this:

```<code>@Override
method A{
    //calls private methods 1-8
}

private method 1{
    //copy/pasted
}
</code>```

And so on for all of the private methods. I'd have preferred if the developers of the method I'm overriding had made the private methods protected, but I can't change that now.

All of these private methods have javadoc along with them - should I carry this along with the copy/pasted functions in my class and adjust them accordingly, or not waste my time since it is documented in the original file?

Body:
Just as one does not copy and paste all of the methods from the superclass when writing code, so to should one not copy and paste all of the documentation when documenting overridden methods.

From javadoc at docs.oracle.com:

{@inheritDoc}

Inherits (copies) documentation from the "nearest" inheritable class or implementable interface into the current doc comment at this tag's location. This allows you to write more general comments higher up the inheritance tree, and to write around the copied text.

This tag is valid only in these places in a doc comment:

In the main description block of a method. In this case, the main description is copied from a class or interface up the hierarchy.

In the text arguments of the @return, @param and @throws tags of a method. In this case, the tag text is copied from the corresponding tag up the hierarchy.

See Automatic Copying of Method Comments for a more precise description of how comments are found in the inheritance hierarchy. Note that if this tag is missing, the comment is or is not automatically inherited according to rules described in that section.

And thus, you inherit the documentation from the superclass.  If the superclass documentation updates, yours does too.

Just as with inheritance of code, you can extend the comments.

Lets see what things look like in an IDE and code...

public interface IFace {
    /**
     * This is a method.
     */
    public void method1();

    /**
     * This is also a method
     */
    public void method2();
}

This is just an interface with some javadocs and two methods.

Lets have a class implement this...

public class CClass implements IFace {

    /**
     * {@inheritDoc}
     * This just returns.
     */
    public void method1() {
    }

    public void method2() {
    }
}

And then the javadocs themselves:

public void method1()
This is a method. This just returns.
Specified by:
method1 in interface IFace

img

public void method2()
Description copied from interface: IFace This is also a method
Specified by:
method2 in interface IFace

img

The first thing to see is that with method1, the javadoc is included and extended with the {@inheritdoc}.  However, no javadoc will also inherit the javadoc from wherever.

If you are not changing the javadoc, don't specify it.  Let the IDE do its thing. Let the automatic javadoc generation do its thing too.  Copying and pasting documentation can be just as bad as copying and pasting code as it violates DRY and may lead to the documentation from the superclass or interface getting out of sync with the documentation of the method.

On the other hand, if you are going to write something more, inherit the documentation and write it.


问:
Why Increment Pointers?
I just recently started learning C++, and as most people (according to what I have been reading) I'm struggling with pointers.

Not in the traditional sense, I understand what they are, and why they are used, and how can they be useful, however I can't understand how incrementing pointers would be useful, can anyone provide an explanation of how incrementing a pointer is a useful concept and idiomatic C++?

This question came after I started reading the book A Tour of C++ by Bjarne Stroustrup, I was recommended this book, because I'm quite familiar with Java, and the guys over at Reddit told me that it would be a good 'switchover' book.

答:
When you have an array, you can set up a pointer to point to an element of the array:

```<code>int a[10];
int *p = &a[0];
</code>```

Here p points to the first element of a, which is a[0]. Now you can increment the pointer to point to the next element:

```<code>p++;
</code>```

Now p points to the second element, a[1]. You can access the element here using *p. This is different from Java where you would have to use an integer index variable to access elements of an array.

Incrementing a pointer in C++ where that pointer does not point to an element of an array is undefined behaviour.

Title: Why Increment Pointers?

Body:
When you have an array, you can set up a pointer to point to an element of the array:

int a[10];
int *p = &a[0];

Here p points to the first element of a, which is a[0]. Now you can increment the pointer to point to the next element:

p++;

Now p points to the second element, a[1]. You can access the element here using *p. This is different from Java where you would have to use an integer index variable to access elements of an array.

Incrementing a pointer in C++ where that pointer does not point to an element of an array is undefined behaviour.


答:
TL;DR version:

Look at whether the project domain interests you, and look at the whole lifecycle, not just the code,  to see if the activities going on are interesting to you.

Elaborating a bit:

To figure out where a project is in terms of truly new development versus maintenance and debugging, looking at the code and code checkins probably isn't enough IMO.

In addition you need to look at other lifecycle activities.

Are new requirements being defined? Can these requirements be met with modifications to existing code or is new code required ?

Is there design going on? Again, is this totally new development or modification?

Often the answer is both.  New requirements and new design are often met with a mix of totally new development and maintenance and expansion of the existing code base.

So you can't necessarily equate maintenance and bug fixing with "uninteresting" - often some of the greatest technical challenges arise in these phases.

Finally, as to "cool" - that's too much a matter of personal opinion. To some, maybe working at Google or a Web startup is the epitome of "cool", but someone doing scientific computing, or embedded development, or medical software, might find Google uninteresting by comparison, believe it or not. So it's hard to specifically comment on that aspect.

Title: How can I figure out if another project is mostly maintenance and bugs?

Body:
I started working in a relatively big company that unfortunately has its share of quite a lot of legacy code and I ended up spending an extra ordinary amount of time in maintainance and bug fixes.

I would like to switch project as on the surface there are other project that "seem" interesting. The issue is I am not really sure if it is any better there either.

I have asked some colleagues to see what's going on and they "claim" that they are involved in cool things but I don't really believe them as in one of the cases I know for sure he is the same situation as I am.

So my question is the following:

If I don't have someone I can really trust to make a good choice about swapping to another project is there a way I could find out myself (I mean if it is the same everywhere)?

One idea would be to do some "reverse" engineering i.e. start tracking each persons commit in the repository to figure out what he's been up to. But this approach seems to me irrational.

Surely there must be a better way?


答:
Incrementing pointers is idiomatic C++, because pointer semantics reflect a fundamental aspect of the design philosophy behind the C++ standard library (based off of Alexander Stepanov's STL)

The important concept here, is that the STL is designed around containers, algorithms, and iterators.  Pointers are simply iterators.

Of course, the ability to increment (or add/subtract from) pointers goes back to C.  A lot of C-string manipulation algorithms can be written simply using pointer arithmetic.  Consider the following code:

```<code>char string1[4] = "abc";
char string2[4];
char* src = string1;
char* dest = string2;
while ((*dest++ = *src++));
</code>```

This code uses pointer arithmetic to copy a null-terminated C-string.  The loop automatically terminates when it encounters the null.

With C++, pointer semantics are generalized to the concept of iterators.  Most standard C++ containers provide iterators, which can be accessed via the begin and end member functions.  Iterators behave like pointers, in that they can be incremented, dereferenced, and sometimes decremented or advanced.

To iterate over an std::string, we would say:

```<code>std::string s = "abcdef";
std::string::iterator it = s.begin();
for (; it != s.end(); ++it) std::cout << *it;
</code>```

We increment the iterator just like we would increment a pointer to a plain C-string.  The reason this concept is powerful is because you can use templates to write functions that will work for any type of iterator that meets the necessary concept requirements.  And this is the power of the STL:

```<code>std::string s1 = "abcdef";
std::vector<char> buf;
std::copy(s1.begin(), s1.end(), std::back_inserter(buf));
</code>```

This code copies a string into a vector.  The copy function is a template that will work with any iterator that supports incrementing (which includes plain pointers).  We could use the same copy function on a plain C-string:

```<code>   const char* s1 = "abcdef";
   std::vector<char> buf;
   std::copy(s1, s1 + std::strlen(s1), std::back_inserter(buf));
</code>```

We could use copy on an std::map or a std::set or any custom container that supports iterators.

Note that pointers are a specific type of iterator: random access iterator, which means they support incrementing, decrementing, and advancing with the + and - operator.  Other iterator types only support a subset of pointer semantics: a bidirectional iterator supports at least incrementing and decrementing; a forward iterator supports at least incrementing.  (All iterator types support dereferencing.)  The copy function requires an iterator that at least supports incrementing.

You can read about different iterator concepts here.

So, incrementing pointers is an idiomatic C++ way to iterate over a C-array, or access elements/offsets in a C-array.

Title: Why Increment Pointers?

Body:
I just recently started learning C++, and as most people (according to what I have been reading) I'm struggling with pointers.

Not in the traditional sense, I understand what they are, and why they are used, and how can they be useful, however I can't understand how incrementing pointers would be useful, can anyone provide an explanation of how incrementing a pointer is a useful concept and idiomatic C++?

This question came after I started reading the book A Tour of C++ by Bjarne Stroustrup, I was recommended this book, because I'm quite familiar with Java, and the guys over at Reddit told me that it would be a good 'switchover' book.

Body:
Incrementing pointers is idiomatic C++, because pointer semantics reflect a fundamental aspect of the design philosophy behind the C++ standard library (based off of Alexander Stepanov's STL)

The important concept here, is that the STL is designed around containers, algorithms, and iterators.  Pointers are simply iterators.

Of course, the ability to increment (or add/subtract from) pointers goes back to C.  A lot of C-string manipulation algorithms can be written simply using pointer arithmetic.  Consider the following code:

char string1[4] = "abc";
char string2[4];
char* src = string1;
char* dest = string2;
while ((*dest++ = *src++));

This code uses pointer arithmetic to copy a null-terminated C-string.  The loop automatically terminates when it encounters the null.

With C++, pointer semantics are generalized to the concept of iterators.  Most standard C++ containers provide iterators, which can be accessed via the begin and end member functions.  Iterators behave like pointers, in that they can be incremented, dereferenced, and sometimes decremented or advanced.

To iterate over an std::string, we would say:

std::string s = "abcdef";
std::string::iterator it = s.begin();
for (; it != s.end(); ++it) std::cout << *it;

We increment the iterator just like we would increment a pointer to a plain C-string.  The reason this concept is powerful is because you can use templates to write functions that will work for any type of iterator that meets the necessary concept requirements.  And this is the power of the STL:

std::string s1 = "abcdef";
std::vector<char> buf;
std::copy(s1.begin(), s1.end(), std::back_inserter(buf));

This code copies a string into a vector.  The copy function is a template that will work with any iterator that supports incrementing (which includes plain pointers).  We could use the same copy function on a plain C-string:

   const char* s1 = "abcdef";
   std::vector<char> buf;
   std::copy(s1, s1 + std::strlen(s1), std::back_inserter(buf));

We could use copy on an std::map or a std::set or any custom container that supports iterators.

Note that pointers are a specific type of iterator: random access iterator, which means they support incrementing, decrementing, and advancing with the + and - operator.  Other iterator types only support a subset of pointer semantics: a bidirectional iterator supports at least incrementing and decrementing; a forward iterator supports at least incrementing.  (All iterator types support dereferencing.)  The copy function requires an iterator that at least supports incrementing.

You can read about different iterator concepts here.

So, incrementing pointers is an idiomatic C++ way to iterate over a C-array, or access elements/offsets in a C-array.


答:
Actually you don't need a multiplication to do 2*5. To multiply any number with a power of 2, use left shift instead. But assume you really must do a multiply, the result depends on whether how many operands an instruction have in that architecture, and whether that architecture has immediate multiplying instruction or not.

For example in a 1-operand machine or accumulator architecture it's possibly done like this

```<code>load 2   # load accumulator with 2
mult 5   # multiply accumulator with 5
add  1
</code>```

In 2-operand architectures:

```<code>move r0, 2
mult r0, 5
add  r0, 1
</code>```

That's the idea for an abstract instruction set. Real architectures may not support all that operations and you may need more instructions to achieve that. For example 8051 is an accumulator architecture but it doesn't have multiply-by-constant instruction so you need one more instruction:

```<code>MOV A, #2
MOV B, #5
MUL AB
INC A
</code>```

In AVR to get the result in R0 you can do like this

```<code>ldi R2, 2
ldi R3, 5
mul R2, R3
inc R0
</code>```

In MIPS where most instructions have 3 operands (but multiplies have only 2 operands) you can do like this

```<code>addi $t0, $zero, 2    # t0 = 2
addi $t1, $zero, 5    # t1 = 5
mult $t0, $t1         # {hi, lo} = t0*t1
mfhi $a0              # high part, maybe unneccessary
mflo $t2              # t2 = LOW(t0*t1)
addi $t2, $t2, 1      # t2 = t0*t1 + 1
</code>```

In x86 you have much more choice. Originally multiplication in x86 has only 1 operand and must be achieved through the accumulator ax

```<code>mov ax, 2
mov bx, 5
mul bx
inc ax
</code>```

You can also use 3-operand imul to shorten the program

```<code>mov  eax, 2
imul eax, eax, 5
inc  eax
</code>```

Or even shorter using LEA instruction:

```<code>mov rax, 5
lea rax, [rax + rax + 1] ; or possibly lea rax, [rax*2 + 1] although I'm not sure about the syntax
; or
mov rax, 2
lea rax, [rax + rax*4 + 1] ; rax = rax*5 + 1
</code>```

Body:
Actually you don't need a multiplication to do 2*5. To multiply any number with a power of 2, use left shift instead. But assume you really must do a multiply, the result depends on whether how many operands an instruction have in that architecture, and whether that architecture has immediate multiplying instruction or not.

For example in a 1-operand machine or accumulator architecture it's possibly done like this

load 2   # load accumulator with 2
mult 5   # multiply accumulator with 5
add  1

In 2-operand architectures:

move r0, 2
mult r0, 5
add  r0, 1

That's the idea for an abstract instruction set. Real architectures may not support all that operations and you may need more instructions to achieve that. For example 8051 is an accumulator architecture but it doesn't have multiply-by-constant instruction so you need one more instruction:

MOV A, #2
MOV B, #5
MUL AB
INC A

In AVR to get the result in R0 you can do like this

ldi R2, 2
ldi R3, 5
mul R2, R3
inc R0

In MIPS where most instructions have 3 operands (but multiplies have only 2 operands) you can do like this

addi $t0, $zero, 2    # t0 = 2
addi $t1, $zero, 5    # t1 = 5
mult $t0, $t1         # {hi, lo} = t0*t1
mfhi $a0              # high part, maybe unneccessary
mflo $t2              # t2 = LOW(t0*t1)
addi $t2, $t2, 1      # t2 = t0*t1 + 1

In x86 you have much more choice. Originally multiplication in x86 has only 1 operand and must be achieved through the accumulator ax

mov ax, 2
mov bx, 5
mul bx
inc ax

You can also use 3-operand imul to shorten the program

mov  eax, 2
imul eax, eax, 5
inc  eax

Or even shorter using LEA instruction:

mov rax, 5
lea rax, [rax + rax + 1] ; or possibly lea rax, [rax*2 + 1] although I'm not sure about the syntax
; or
mov rax, 2
lea rax, [rax + rax*4 + 1] ; rax = rax*5 + 1


问:
Avoiding Double POST
We are implementing a RESTful webservice that will allow client applications to POST documents to it and it will store the document returning a unique identifier in the response. The clients will mostly be Spring MVC applications, but do not have to be.

The two client applications that we are currently working on have various JSPs which contains HTML forms that will contain file elements and other attributes. So a user will submit a form via POST to a Spring Controller in the client application. The Controller will read the bytes from the file and then POST them to the RESTful service, receive the unique identifier back, and store the unique identifier along with the other information from the form in the database.

As each client can have multiple JSPs with widely varying attributes in the forms, we don't see a way to just POST directly to the RESTful web service.

Is there a clean way to avoid the double POST?

I could see the possibility of having a reusable pop-up window that takes care of POSTing the document to the RESTful web service and then holding the unique document id either in the session or a hidden field on the parent form. I can see two downsides to this: 1) the user may not like having the extra step of going to the pop-up and 2) the document could be orphaned if the user does not submit the parent page.

EDIT / CLARIFICATION: the issue is not that a POST is being sent twice to the same resource, but rather avoiding have both a POST from JSP to Controller within the client application and then a second POST of the same data from the client application to the REST resource.

答:
We faced the same issue and, as others suggested in comments, we made our POSTs idempotent. You can return a different code (in the 200 family) if the file was already there, just to inform the client (or you can just answer "200").
In our experience, this also plays nicely with "not-so-connected" devices (smartphones); if you need to retry a submission, you just retry it, without worrying of duplicates.
You can make (and store) a UID that is based on the document content (a MD5 or SHA hash) and maybe even use it as your primary document ID.

We also considered making the client code more complicated, adding a GET to check if a particular document was already inserted:

GET (is this document present?)

POST (insert document)

...

but this make the client heavier (especially if you compute the hash twice).
It does not really waste bandwidth (in our case, being on a cell network, it was an important issue); most of the time, you just POST once and receive a OK answer (document was not there).

AND it will not solve your issue anyway; if you POST the document from another page just after the GET?
Still, you can combine the two approaches, if you see that the double POST happens many times in your web application.

Title: Avoiding Double POST


问:
How should I recursively process a file in Haskell?
Basically I'm expanding a literate program in Haskell. There are two things I need to look for to expand. Here's an example file:

```<code>program.c.lit:
==============
Some comments in the source file that I can ignore
    <main>=
    code.. code ...
    code..
    <a>

Some comments in the source file that I can ignore
    <a>=
    code... code...
    code..
</code>```

In a file, I need to look at each <some var> and substitute it with its matching definition defined below <some var>=. All the lines which are indented with 4 spaces below a <some defn>= are included in that chunk. In the end i should have a file consisting of only code ... lines.

How should I approach this problem in terms of file processing, what's a good approach? I'm comfortable with recursion, less comfortable with monads.

答:
I will make a few assumptions in my answer. Feel free to correct me if one of them is incorrect:

you are doing this as an exercise

you only want to inline the top level definitions

there is at most only one definition for a given variable name

you want to simplify a given definition by inlining all known variables

If you are doing this for a "real" project, or want to make more complex transformations, I recommend that you look at existing packages such as haskell-src-exts.

Now if you want a robust solution, you will need those functions:

```<code>parse
    :: String        -- the input text
    -> [Declaration] -- a datastructure representing the expression
inline
    :: Declaration   -- the definition to inline
    -> Declaration   -- the definition to modify
    -> Declaration   -- the result definition
showDecl :: Declaration -> String
simplify
    :: String        -- the input text
    -> String        -- the variable name to simplify
    -> String        -- the result
</code>```

Declaration can be as simple as  (String, String) (the variable name and its definition). Note that I am using loosely typed definitions. I am also using String, which may not be the most efficient solution. You may consider using Text to speed things up.

The parse function can be tricky. I recommend using the parsec library. It uses a monad, but don't feel intimidated by it. Using monads does not require understanding them at a fundamental level. Actually the opposite is true. See here for an introduction. You can view the parsec type as a statement which consume a piece of text and maybe return some result.

```<code>parse input = /case analysis of / runParser (many parseBlock) () "source name" input

parseBlock = do
    skipComment
    parseDef

parseDef = do
    varName <- parseVar
    string " = "
    definition <- parseExpr
    return $ Declaration varName defintion

parseExpr = ...
</code>```

Here, unit tests are your best friends. Be sure that all your smaller parsers are working well before combining them. Pay attention to the backtracking semantics (ie the try combinator) because you can easily shoot yourself in the foot with that.

The inline function is easier. It will just be a well thought out search and replace. The simplify function is just a matter of calling parse, extracting the declaration to simplify, and calling inline with all the other ones on it. No recursion needed.

Alternatively, your inline function can be of type Declaration -> String -> String, and edit directly the input string. This way you won't have to write the showDecl function.

Body:
I will make a few assumptions in my answer. Feel free to correct me if one of them is incorrect:

you are doing this as an exercise

you only want to inline the top level definitions

there is at most only one definition for a given variable name

you want to simplify a given definition by inlining all known variables

If you are doing this for a "real" project, or want to make more complex transformations, I recommend that you look at existing packages such as haskell-src-exts.

Now if you want a robust solution, you will need those functions:

parse
    :: String        -- the input text
    -> [Declaration] -- a datastructure representing the expression
inline
    :: Declaration   -- the definition to inline
    -> Declaration   -- the definition to modify
    -> Declaration   -- the result definition
showDecl :: Declaration -> String
simplify
    :: String        -- the input text
    -> String        -- the variable name to simplify
    -> String        -- the result

Declaration can be as simple as  (String, String) (the variable name and its definition). Note that I am using loosely typed definitions. I am also using String, which may not be the most efficient solution. You may consider using Text to speed things up.

The parse function can be tricky. I recommend using the parsec library. It uses a monad, but don't feel intimidated by it. Using monads does not require understanding them at a fundamental level. Actually the opposite is true. See here for an introduction. You can view the parsec type as a statement which consume a piece of text and maybe return some result.

parse input = /case analysis of / runParser (many parseBlock) () "source name" input

parseBlock = do
    skipComment
    parseDef

parseDef = do
    varName <- parseVar
    string " = "
    definition <- parseExpr
    return $ Declaration varName defintion

parseExpr = ...

Here, unit tests are your best friends. Be sure that all your smaller parsers are working well before combining them. Pay attention to the backtracking semantics (ie the try combinator) because you can easily shoot yourself in the foot with that.

The inline function is easier. It will just be a well thought out search and replace. The simplify function is just a matter of calling parse, extracting the declaration to simplify, and calling inline with all the other ones on it. No recursion needed.

Alternatively, your inline function can be of type Declaration -> String -> String, and edit directly the input string. This way you won't have to write the showDecl function.


问:
Commercial Apps with an Open Source on github
I am going to be launching a small web service soon and was wondering if it's a good idea to upload the code to a public github repo.

The code will not be licensed for commercial use but the public could download the code and hack around with it.

Is this a good idea?

Would it help produce more secure/bug-free code?

Or would it run my startup into the ground?

Thanks,
Ben

答:
I would not expect this to harm your startup but I also would not expect you to gain much benefit from the scenario you describe.

Let's start by considering some of the possible risks (and why I don't worry about them).

Your published code becomes a part of the product you are marketing. If this work is of poor quality that may do more harm than good. On the other hand it can also be an asset demonstrating both confidence and quality in your work. Developing software in the open may encourage you to produce higher quality work and follow better patterns. That might serve you we'll in the long run but it might also discourage you from deliberately and appropriately incurring some technical debt even when doing so is in the best interest of your product or company.

Publishing your code might enable imitators. If you have a product other people want to imitate you are already in a fortunate position. Maybe you have some process you want to keep secret but for most web apps the implementation is not significant. Instead most web products derive value from the product/market fit they have found. Finding that is expensive but the result does not depend on your source code. Either anyone can imitate your product from its interface alone or no one can without your understanding of the market which is unlikely to appear in git.

So why do I think this won't help?

A community of contributors helping improve your code is not something that appears magically or for free just because you made some code publicly readable.

What incentive would anyone have to spend time reading your code much less attempting to understand and improve it? Open source projects at least provide a tool their contributors can use so every participant might derive value from improvements they work on. With a restrictive license no one can use this software so why should they care for its quality? Do you expect that users of the product will be so invested in it that they would be willing (and have the skill to) take on its development?

Some projects award prestige and social currency even if the work done in them is not of immediate use to its author. That does not seem to be the case here.

I think the biggest impact releasing this code would have would be on you directly. What would you do differently knowing some one could read it? Would it make a good portfolio piece to share if the product fails? Would it help you sell the product or recruit if you have this code visible to point to?


问:
Does the pattern of passing in one object instead of many parameters to a constructor have a name?
If you have a constructor that takes a lot of parameters, like this:

```<code>  public OrgUnitsHalRepresentation(List<OrgUnitSummaryHalRepresentation> orgUnitSummaryHalRepresentationList,
  int count, int providedCount, int total, int page, int filterLimit, boolean hasNextPage, boolean isDefaultCount)
</code>```

You can use a separate class that takes nothing in the constructor and set these parameters using setters and pass in this into the constructor instead:

```<code>public OrgUnitsHalRepresentation(Pagination(Name of pattern) p)
</code>```

Does this have a name so that I can use it in my class name?

答:
This seems to me like a normal case of grouping related variables into compact structure, that has been practiced since structures were invented. Considering it is so ancient, I would imagine there is no name for it.

Also, remember one thing : Patterns are much complex than that. Pattern usually means something that introduces SOLID into code. Your case is too simple to be considered pattern. I would simply call it "PaginationParameters"


问:
How does a stack VM manage with only one stack?
Lately I've been asking a lot of questions here about VMs. Here's another one:

I understand that often stack based VMs use only one stack - the call stack - for everything. E.g. it is also used for evaluation of arithmetic expressions.

What I don't understand is, how doesn't this complicate things a whole lot? I'll demonstrate what I mean with an example.

Please consider the following psuedocode program:

```<code>func main:
    funcA()

func funcA:
    2 + 4 * 8
</code>```

This would compile to the following bytecode:

```<code>main:
call funcA
end
funcA:
push 2
push 4
push 8
mult
add
end
</code>```

(In this bytecode, the program starts at main:. call pushes the program counter onto the stack and jumps to the specified label. When an end is reached, the top of the stack - assumed to be a line number - is popped and we jump there.)

So let's see what happens here:

In call funcA, we push the program counter (i.e. next line number) onto the stack. Then we jump to funcA.

In funcA some computation is made. After the computation, the number 34 is left at the top of the stack.

When we reach end, we pop the top of the stack, assuming it's the line number we should return to
 But it isn't, the line number to return to is buried underneath. How should end know about this?

To avoid all this mess, we can just have a separate data stack and call stack, and not mix the two.

So my question is: why do some VMs (such as the JVM) use one stack for everything, and when the do: how do they handle situations such as the one described above?

答:
When we reach end, we pop the top of the stack, assuming it's the line number we should return to But it isn't, the line number to return to is buried underneath. How should end know about this?

You compiled the source to the wrong opcodes. There are two ways to solve this:

Put a swap before each end. Because the return address sits immediately underneath the return value, this will put the return address onto the top. After end has performed the return, the return value will be the top value.

Define an operation return which pops two values off the stack. The second value is the return address, the first value is the return value. After updating the instruction pointer to point to the return address, the return value is pushed back onto the stack. Then use this sane return instead of end.

The compiler is responsible for emitting correct instructions.

It is possible to write a VM using only one stack. However, this vastly restricts the expressiveness. When using multiple stacks, it becomes far more easy to implement more advanced control flow such as coroutines, continuations, error handlers. In a multi-stack architecture, there would typically be a value stack, and a separate call stack which stores not only the return address but possibly also debugging data, or cleanup actions to perform when the current scope is left. If you're already using multiple stacks, it also becomes easier to use segmented stacks, which are a technique to avoid stack overflows. Essentially, the stack is actually a linked lists of smaller stacks. If one segment is full and would overflow, then another segment is allocated and added to the list.

For a well-studied multi-stack VM look at the SECD machine, essentially a lambda calculus interpreter.


问:
Executing ajax calls in setTimeout after set intervals?
We develop an application involving a lot of ajax. Such as showing users notifications, updating what they see via ajax while they are on the web page. This update is due to the actions of other users in the application.

In the code base we are generating a query inside setTimeout
function of javascript. This makes an ajax call.

Every call is a separate query to the database.

There are many calls on the same page.

So we run queries against the database after 15 seconds, no matter if something changes or not. Will this approach work if we are expecting high traffic?

答:
Polling like this can get expensive (in terms of resource usage), but whether or not that causes a problem depends on a lot of factors (number of users, size of db, hardware...).

Maybe you should consider using server sent events instead.


答: Issues will mainly arise due to current browsers' limitations to perform only a limited number of concurrent requests. The number of concurrent request varies by browser but usually within 2-6. So, if a page has multiple setTimeOut(), only the predetermined number of requests will pass through. Others will follow only when those requests are complete. </p>

Title: Executing ajax calls in setTimeout after set intervals?

Body:
We develop an application involving a lot of ajax. Such as showing users notifications, updating what they see via ajax while they are on the web page. This update is due to the actions of other users in the application.

In the code base we are generating a query inside setTimeout
function of javascript. This makes an ajax call.

Every call is a separate query to the database.

There are many calls on the same page.

So we run queries against the database after 15 seconds, no matter if something changes or not. Will this approach work if we are expecting high traffic?


答: This is the Parameter Object Design Pattern (or Argument Object), the related Refactoring is called Introduce Parameter Object.

Title: Does the pattern of passing in one object instead of many parameters to a constructor have a name?

Body:
If you have a constructor that takes a lot of parameters, like this:

```<code>  public OrgUnitsHalRepresentation(List<OrgUnitSummaryHalRepresentation> orgUnitSummaryHalRepresentationList,
  int count, int providedCount, int total, int page, int filterLimit, boolean hasNextPage, boolean isDefaultCount)
</code>```

You can use a separate class that takes nothing in the constructor and set these parameters using setters and pass in this into the constructor instead:

```<code>public OrgUnitsHalRepresentation(Pagination(Name of pattern) p)
</code>```

Does this have a name so that I can use it in my class name?


答:
Pointer arithmetic is in C++ because it was in C. Pointer arithmetic is in C because it's a normal idiom in assembler.

There are plenty of systems where "increment register" is faster than "load constant value 1 and add to register". Moreover, quite a few systems let you do "load DWORD into A from address specified in register B, then add sizeof(DWORD) to B" in a single instruction. These days you might expect an optimising compiler to sort this out for you, but this wasn't really an option in 1973.

This is basically the same reason that C arrays aren't bounds-checked and C strings don't have a size embedded in them: the language was developed on a system where every byte and every instruction counted.

Title: Why Increment Pointers?


问:
Avoiding polling with components
Once you create separate components that need to communicate with each other you enter the realm of systems programming where you have to assume that errors could originate at any step in the process.  You throw try-catch blocks out the window and have to develop robust alternatives for error handling yourself.

We have two systems both with REST apis.  Both systems have GUIs that users can use to add/update information.  When information is added to one system it must be propagated to the other.  We have integration software (the middleman) that polls on a minute-by-minute basis, picks up adds/edits and translates them from one system to the other.  Each invokation keeps track of the timestamp of the last successful run--we have one timestamp for communication in either direction.  In this way, if any part of the system fails, we can resume right where we left off when the issues are corrected.

I have heard bad things about poll-based approaches: namely the fact that it runs without regard to whether there is actually work.  I have heard that push-based approaches are more efficient because they are triggered on demand.

I am trying to understand how a push-based approach might have worked.  If either system attempts to push an add/edit, we have to assume that it could fail because the other system is down.  It would seem to me that either system would need to maintain its own outgoing queue in order to resume once the issue with the other system is corrected.

It seems to me that using a push approach eliminates the middleman, but heaps more responsibility on each system to manage its messages to the other system.  This seems to not be a clean way of separating concerns.  Now both systems have to take on middleman responsibilities.

I don't see how you would redesign the middleman for a push-based architecture.  You run the risk that messages are lost if the middleman himself fails.

Is there a fault-tolerant architecture that could be used to manage system interactions without the polling?  I'm trying to understand if we missed a better alternative when we devised/implemented our poll-based middleman.  The software does the job, but there's some latency.

答: If the middleman is currently pulling data based on the time of the previous successful run, then, to cut out the middleman, each individual system could do the same in a push architecture.  Yes, each system would need to keep track of this, but it's only a single timestamp, not a full blown message queue.</p>

Title: Avoiding polling with components


答:
It would seem to me that either system would need to maintain its own outgoing queue in order to resume once the issue with the other system is corrected.

Yes, queueing is a good solution for such a scenario. That's what queues are made for: queing up messages for its consumers. But I do not quite get, why a system has to maintain its own outgoing queue.

A simple setup would be, that you have two services A and B, both of which have in Incoming Messages queue. Those queues act like mailboxes. A sends messages to B's Inbox and vice versa. The queues do, what they could do best: queueing those messages.

The conditions under which messages arrive at the consument of such a queue are a) on start, the service registers as a consumer and gets the information, that there are messages in the "mailbox", so the service pops them one by one until the "inbox" is empty and b) everytime a new message arrives, the service gets a notification and pops unread messages until the inbox is empty.

You decouple your systems with two message queues. You send messages in a fire-and-forget-manner. The question whether the recipient is alive doesn't bother the sender.
A queue would do what your current middleware does - but in an easier way.

The point of failure shifts from the direct recipient, e.g. service A, to the queueing infrastructure, which has to be built resilient/redundant = fault-tolerant.

Each invokation keeps track of the timestamp of the last successful run--we have one timestamp for communication in either direction. In this way, if any part of the system fails, we can resume right where we left off when the issues are corrected.

The queues in the above scenario were acting like stacks and would preserve order.

And since it is a distributed system, you have to deal with CAP; simply spoken: the problem, that you have two out of sync services, which both could get queryied simultanously.

Title: Avoiding polling with components

Body:
Once you create separate components that need to communicate with each other you enter the realm of systems programming where you have to assume that errors could originate at any step in the process.  You throw try-catch blocks out the window and have to develop robust alternatives for error handling yourself.

We have two systems both with REST apis.  Both systems have GUIs that users can use to add/update information.  When information is added to one system it must be propagated to the other.  We have integration software (the middleman) that polls on a minute-by-minute basis, picks up adds/edits and translates them from one system to the other.  Each invokation keeps track of the timestamp of the last successful run--we have one timestamp for communication in either direction.  In this way, if any part of the system fails, we can resume right where we left off when the issues are corrected.

I have heard bad things about poll-based approaches: namely the fact that it runs without regard to whether there is actually work.  I have heard that push-based approaches are more efficient because they are triggered on demand.

I am trying to understand how a push-based approach might have worked.  If either system attempts to push an add/edit, we have to assume that it could fail because the other system is down.  It would seem to me that either system would need to maintain its own outgoing queue in order to resume once the issue with the other system is corrected.

It seems to me that using a push approach eliminates the middleman, but heaps more responsibility on each system to manage its messages to the other system.  This seems to not be a clean way of separating concerns.  Now both systems have to take on middleman responsibilities.

I don't see how you would redesign the middleman for a push-based architecture.  You run the risk that messages are lost if the middleman himself fails.

Is there a fault-tolerant architecture that could be used to manage system interactions without the polling?  I'm trying to understand if we missed a better alternative when we devised/implemented our poll-based middleman.  The software does the job, but there's some latency.


问:
Is making a small change, testing it, then "rinse and repeat", a bad habit?
I am a programmer with a number of years of experience. I realized I got a certain habit. I'm not sure whether it's really a bad habit or not.

I get a list of tasks to perform for a solution, even small small tasks, for example,

Change resources of this user control

Change size of another one

Add some HTML and coding on another user control

All of these tasks are small. I mean they can be done within 10 minutes, but I got a bad habit of making small changes and then test them again and again in a web browser. Is this a good practice?

Or should I perform them all at once and then test them together?

If it is really a bad habit then how do I rectify it, since it feels like wasting time testing small changes over and over?

答:
Making lots of little changes and testing each one is not a bad thing. It allows you to see the effect of each change, and then when one change causes a problem, it's much easier to know which change caused issues - the most recent one!

If you have a task list with 10 items, and you do all of them at once and then test the page and then notice that the page looks wrong, it might be harder to know which change broke the page.

Of course, it's possible to take this approach to the extreme. Finding balance is the key, and that comes with gaining a better understanding of what you're changing and how the changes might affect each other.


答:
It's a good practice.

You are following the scientific method.

If you change several things before any testing, then the testing of each will be more difficult, and perhaps not reliable, since preconditions will be more difficult to prepare and the different changes can interact with each other in manners you didn't foresee.

The time you feel you are "wasting" now, you will regain later in the intregration, testing and maintaining stages.

Way to go.

Title: Is making a small change, testing it, then "rinse and repeat", a bad habit?

Body:
I am a programmer with a number of years of experience. I realized I got a certain habit. I'm not sure whether it's really a bad habit or not.

I get a list of tasks to perform for a solution, even small small tasks, for example,

Change resources of this user control

Change size of another one

Add some HTML and coding on another user control

All of these tasks are small. I mean they can be done within 10 minutes, but I got a bad habit of making small changes and then test them again and again in a web browser. Is this a good practice?

Or should I perform them all at once and then test them together?

If it is really a bad habit then how do I rectify it, since it feels like wasting time testing small changes over and over?


答:
Your question has two parts:

should I perform them all once and then test them together ?

I assume you are using a VCS.

And to track, what tasks were done it makes sense to distribute the list of tasks to a list of commits: one task, one commit.

That makes it easy to manage different versions of the current code base; you could revert to a previous state, cherry-pick the changes you want to enter the main trunk, etc.

The answer is cleary:

No, make changes only one by one - one task one commit.

but I got a bad habit of making small small changes and then test them again and again in web browser, is this a good practice ?

It is a good practice to test code/UI whatever, but it is nonsense to do it over and over again in the browser. There are tools, to do that automatically for you (Selenium, PhantomJS/Casper, ZombieJS)

The answer for this case is:

Yes, it is good practice to test software more than once, but use automation


问:
Client-side coding: How to prevent malicious use?
Over the last few years, the trend for client-side (browser) applications has really taken off.

For my latest project, I have decided to try and move with the times and write a client-side application.

Part of this application involves sending transaction emails to users (for example, validate signup, password reset emails, etc.). I am using a third-party API to send the emails.

Normally I would have my application running on a server. I would call the third-party API from code on my server.

Running a client-side application means this now needs to happen on a user's browser. The third-party API provides the necessary JavaScript files to achieve this.

The first glaring issue I can see is I need to use an API key. This would normally be safely stored on my server, but now presumably I will need to provide this key to the client browser.

Assuming I can get round this problem, the next problem is what stops a tech-savvy user loading up the JavaScript developers tool on a browser and using the email API anyway they like, rather than say adhering to any rules I have set in the application.

I guess my general question is - how can we prevent malicious use of a client-side application?

答:
Client-Side application, in my opinion, is mostly about the UI. For example, all your UI system will be sent once to the client, and then the client would do whatever it wants with it.

Normally I would have my application running on a server. I would call the third-party API from code on my server.

Running a client-side application means this now needs to happen on a user's browser. The third-party API provides the necessary JavaScript files to achieve this.

If you have an API Key, then it's not intended to work on the client side. If you give the API Key on the client side, then anyone has access to it, and can then use it for it's own purpose. Store it and use it server-side when the client needs it, then send the result using Ajax/WebSockets.

It's like if your bank was saying : "Well, I'm going to put the password of the main database client side so that the client can request it himself and he will not bother our servers anymore."


问:
Java-Like 'throws'-information in method signature C#
From Java I know that the signatures of methods that can throw exceptions contain a throws block, that contains the Exception(s) that might be thrown.

In C# there is no such thing and it is also not common practice to include such info in the XML-Header.

Is there a generally accepted way of drawing attention to potential exceptions or a place to commonly denote them?

答:
XML headers (e.g. <exception>) are the best way of drawing attention to exceptions in C#, as this information will appear in IDE when typing the function name, as well as in auto-generated docs.  However you cannot force a user to deal with the exception since C# specifically avoids checked exceptions.

Most people don't put exception information in XML doc comments because it's too much work with low payoff, but if it was to be done, this would most reliably draw attention to the exceptions thrown.


问:
Open Source-Only license
I want to know if a license exists that is similar to GPL but allows only source distribution (that is no binary distribution).

Why do I want this? The idea is that I want fellow programmers to be able to have the benefits of open source software BUT also retain control over the consumer binary distribution. Specifically I want to prevent my software to be picked by organazations like the linux distributors. I want the users of my software to dowlnload binaries only from my site.

Is this possible?

Thanks

答:
No, that is not possible if you want to call what you're doing "open source."  As noted in the comments, there are innumerable difficulties in trying to grant a copyleft that prohibits recompilation or distribution of compiled binaries, not the least of which is the cultural resistance you'll encounter.

However, you're selling a non-OSS product and don't care about granting a copyleft, so there's nothing stopping you from including the source code to your application with a limited right to recompile and patch for internal use. It's just that you wouldn't call that "open source", since that's not what you're doing.

(One of the key benefits of Open Source is the ability to take code and use it in your project, even if said project is yet another Linux distribution.)

Title: Open Source-Only license


问:
Is it a bad practice to have an interface to define constants?
I am writing a set of junit test classes in Java.
There are several constants, for example strings that I will need in different test classes.
I am thinking about an interface that defines them and every test class would implement it.

The benefits I see there are:

easy access to constants: MY_CONSTANT instead of ThatClass.MY_CONSTANT

each constant defined only once

Is this approach rather a good or bad practice? I feel like doing so is a little like abusing the concept of interfaces.

You can answer generally about interfaces/constants, but also about unit tests if there is something special about it.

答:
In our case we're doing this because the values of the constants represent a contract for end states that a service implementation is required to provide. Putting these constants in the interface specifies the end states as a part of the contract, and if any implementation of the interface didn't use them it would not be doing its job.

SOMETIMES constants are implementation details. SOMETIMES they are not. As usual, an engineer needs to use his brain to decide what to do, and not rely on a sweeping pattern or practice.

ContentLicense: CC BY-SA 4.0


问:
A question about static types
How would you statically type the following JavaScript program

```<code>function c(str) {
  c = eval(str);
  return c(str);
}
</code>```

I'm not trying to start a flame war but I'm genuinely curious. I've always assumed that dynamic languages allow more programs to be written because of examples like the above. But if a statically typed language is Turing complete then it should be able to express the equivalent of the above program. So where exactly does my reasoning break down because this seems paradoxical to me? My reasoning is that this is obviously a function that can not be typed in a statically typed language and still allow the generality that the above code allows for.

答:
There are a few ways you could go about typing this.

Forget All The Types!

You can mimic dynamic types in statically typed languages by simply forgetting that you had types in the first place and switching to using runtime type information.

In haskell this would look something like

```<code>evalThingy s = let result = eval s
                   resultTy = typeOf result
               if resultTy == typeOf (id :: String -> String)
               then unsafeCoerce result s
               else fail in some manner
</code>```

So we have a runtime switch which just checks whether it's safe to continue and if it is, beat the typechecker into submission and proceed.

Personally I dislike this way since if I'm going to have to write something in a static type system, I want to get the safety benefits. That means coercions like the above are a no-no.

Explicit Failure

The simplest is to force eval to either return a specific type or fail in a controlled manner

```<code>eval : String -> Either Error a
</code>```

And then we could say something like

```<code> c = eval(str) : Either Error (str -> Int)
 case c of
   Right f -> f str
   Left err -> blowup str
</code>```

In order to support this well are language needs something called return type [parametric] polymorphism. ATM I'm only aware of this being supported through type classes. That means that we need to different things depending on what the type called is.

Dependent Types

The more convoluted approach would be to actually reflect the typing judgement of the language into some function, let's say typeOf.

```<code>typeOf : String -> TypeOfTypes
</code>```

Where TypeOfTypes is the universe of all types that programs normally use. This can't include itself if we want some sanity in our type system.

Next we can assign eval a fairly convoluted dependent type to eval

```<code>eval : (s : str) -> typeOf str

applySelf : (s : String) -> typeOf s = (String -> String) -> String
applySelf = function(s, p){
  case p of
    reflexivity -> eval(s)(s)
}
</code>```

So we force the caller of applySelf to prove that the string they're asking us to evaluate will have the type string -> string at which point we can ignore the safety checks since we have a static proof of correctness.

Title: A question about static types

Body:
There are a few ways you could go about typing this.

Forget All The Types!

You can mimic dynamic types in statically typed languages by simply forgetting that you had types in the first place and switching to using runtime type information.

In haskell this would look something like

evalThingy s = let result = eval s
                   resultTy = typeOf result
               if resultTy == typeOf (id :: String -> String)
               then unsafeCoerce result s
               else fail in some manner

So we have a runtime switch which just checks whether it's safe to continue and if it is, beat the typechecker into submission and proceed.

Personally I dislike this way since if I'm going to have to write something in a static type system, I want to get the safety benefits. That means coercions like the above are a no-no.

Explicit Failure

The simplest is to force eval to either return a specific type or fail in a controlled manner

eval : String -> Either Error a

And then we could say something like

 c = eval(str) : Either Error (str -> Int)
 case c of
   Right f -> f str
   Left err -> blowup str

In order to support this well are language needs something called return type [parametric] polymorphism. ATM I'm only aware of this being supported through type classes. That means that we need to different things depending on what the type called is.

Dependent Types

The more convoluted approach would be to actually reflect the typing judgement of the language into some function, let's say typeOf.

typeOf : String -> TypeOfTypes

Where TypeOfTypes is the universe of all types that programs normally use. This can't include itself if we want some sanity in our type system.

Next we can assign eval a fairly convoluted dependent type to eval

eval : (s : str) -> typeOf str

applySelf : (s : String) -> typeOf s = (String -> String) -> String
applySelf = function(s, p){
  case p of
    reflexivity -> eval(s)(s)
}

So we force the caller of applySelf to prove that the string they're asking us to evaluate will have the type string -> string at which point we can ignore the safety checks since we have a static proof of correctness.


答:
For any habit a developer has, there are 2 main questions:

How does it influence the quality of the code you make?

How does it influence your productivity?

If the answer to both is "It makes it better", screw habit, teach it to others!

If the answer to one is "Better" and the other "Worse" - it's a style and you have to be conscious about it. It's not always applicable, and you may need to make an effort to suppress it every now and then.

If the answer to both is "Negative" - you've got a serious problem.

Of course for the first 2 cases you should also think about "Can the positive effect be somehow automated or institutionalized?". Maybe it's better to write a test than try out different browsers every time? (Note, I know that it's not that easy to test proper layout in web development, I'm not saying this is always possible or worth the time).

In this particular case, it seems to me that the quality is increased, productivity may be decreased. For small changes it's likely kinda bad (especially if the changes are interrelated), for larger - it's kinda good. As long as you test the end result as well (avoid the "each module was tested and works, so the entire thing works as well, no need to test it!").

Hence - unless 90% of your work day is doing really small changes - it's a perfectly fine habit to have. If your work day is like that, then maybe you might want to review your work style (or work place).


问:
Which Java based web ui framework to use?

Wicket

Click

GWT

Vaadin

As I understand them, these frameworks all enable gui components to be created using java (with all its benefits) without having to do lots of html/javascript.

As well as considering the technical factors, I am also interested to hear if any are gaining popularity fast. Is a particular framework is becoming the leader of the pack, this will also effect the decision.

答:
Consider JSF 2 with facelets.  If nothing else, as it is in Java EE 6, and hence is 1) well-specified and 2) will be available and maintained for a VERY long time.

Unless you want to be an active pioneer, this might be quite good enough.


答:
Yes, polling will work.  Its not the most sophisticated way of watching for changes, but it will do the trick.  We can't tell you if your server will be able deal with it or not, that's just something you'll have to test.  But I imagine if you are doing a single, highly optimized database query per poll and returning small amounts of data, you'd be able to handle fairly high traffic.

That said, you might consider long polling or websockets instead.  That would require changes to how your server piece worked, but would give you more real-time updates from the server.


答:
I don't think it's a good thing to have interfaces only for constants.

But if an interface that defines behavior (methods implementing classes should implement), has constants, it's OK. If it "leaks some implementor's detail" into the API, it's because that's the way it should be. They are also leaking that the implementor implements .foo() and .bar() methods.

Take for example the java.awt.Transparency interface. It has OPAQUE, BITMASK and TRANSLUCENT constants but also has .getTransparency() method.

If the designer put those constants there it's because he/she thought that would be stable enough to be part of the interface, as .getTransparency() is.

Title: Is it a bad practice to have an interface to define constants?

Body:
I am writing a set of junit test classes in Java.
There are several constants, for example strings that I will need in different test classes.
I am thinking about an interface that defines them and every test class would implement it.

The benefits I see there are:

easy access to constants: MY_CONSTANT instead of ThatClass.MY_CONSTANT

each constant defined only once

Is this approach rather a good or bad practice? I feel like doing so is a little like abusing the concept of interfaces.

You can answer generally about interfaces/constants, but also about unit tests if there is something special about it.


答:
Have a look at this:

http://www.binpress.com/license/generator

It allows you to generate your own license where you can specify what the user is allowed/not allowed to do. Additionally, it lets you specify binary distribution.

If reality, it'd be difficult to enforce, but essentially you can say use and modification are okay, but redistribution is not. I imagine you'd have to draw a line between what is modified code and what is original though.

Title: Open Source-Only license

Body:
I want to know if a license exists that is similar to GPL but allows only source distribution (that is no binary distribution).

Why do I want this? The idea is that I want fellow programmers to be able to have the benefits of open source software BUT also retain control over the consumer binary distribution. Specifically I want to prevent my software to be picked by organazations like the linux distributors. I want the users of my software to dowlnload binaries only from my site.

Is this possible?

Thanks


答: As others have stated, this is definitely not a bad habit. I generally prefer to make only a few modifications at once. The only exception is if I have a large list of changes that don't all affect one another (e.g. changes to minor styles or copy, changes on different pages, etc). If you're modifying layouts, stick to making changes one at a time so you can verify everything is 100% in all supported browsers before moving onto the next issue.


问:
How do I ensure my site will be crawled when articles are generated by the database?
I wasn't sure how to ask the question. But basically, it's a textbook scenario. I'm working on a site that's article based, but the article information is stored in a database. Then the page is rendered with the information in the database based on the requested article id:

For example: http://www.mysite.com/articles/9851

I'm new to SEO, so I'm wondering how engines are able to crawl the contents of pages like this and/or what I need to do in order to ensure that it will be crawled.

So for instance, this site. All of the articles/posts on this site appear to live in a database somewhere. The URL has an ID which looks like it is used to tell the server which data to use to generate the page -- so the page doesn't actually exist somewhere, but it's template does. When I search google, I might find one of these posts based on the content of the post.

I understand that crawlers normally just find a page and follow it's links and follow its links' links and so on, but how does that work when the site is search based like this? Do have to create a page that randomly picks articles out of the database so that the crawler can see it or something?

答:
Since Google is the largest Search Engine, and ALL sites want to be crawled by google, I suggest you start with google's webmaster tools page. (https://www.google.com/webmasters/). It is full of helpful resources.

To answer your question, you provide a robot.txt or a sitemap with all links that you want search engines to crawl and index. Here's a detailed answer about how to submit a sitemap to google. https://support.google.com/webmasters/answer/183669?hl=en