答:
Quick Answer

Members inheritance modifiers allows developers to put guidelines, on how an object members should be inherited.

Long, Boring, Extended Answer

The combination of non-virtual methods and virtual methods, (and "final" or "sealed", and "abstract" methods), in an algorithm, allows to restrict a goal.

Remember that those modifiers may vary from one Programming Language to Another P.L.

MustInherit from V.B. is commonly used as virtual, in other P.L.

Overriden from V.B. is commonly used as override, in other P.L.

NotOverridable from V.B. is not explicitly used in many P.L., I usually add a small, one line comment like /* nonvirtual */.

In Java, before the @override marker or directive was added, I used /* @override */.

I develop a lot of large O.O. programs, usually done entirely by myself, most of them for work, sometimes as a hobby. Even, in small programs, I add modifiers, because the logic of trhe program requires.

A good example, is when you combine several of them:

public class EntityClass
{

        public virtual bool IsReady()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool IsReady()

        public virtual bool GenerateKey()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool GenerateKey()

        public virtual bool BeforeInsert()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool BeforeInsert()

        public virtual bool ConfirmedInsert()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool ConfirmedInsert()

        public virtual bool AfterInsert()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool AfterInsert()

        public /* nonvirtual */ bool InsertAndGenerateKey()
        {
            bool Result = false;

            if (this.IsReady())
            {
                Result = GenerateKey();
                if (Result)
                {
                    Result = BeforeInsert();
                    if (Result)
                    {
                        Result = ConfirmedInsert();
                        if (Result)
                        {
                            AfterInsert();
                        }
                    }
                }
            } // if (this.IsReady())

            return Result;
        } // bool InsertAndGenerateKey

        public /* nonvirtual */ bool InsertAndIgnoreKey()
        {
            bool Result = false;

            if (this.IsReady())
            {
                Result = BeforeInsert();
                if (Result)
                {
                    Result = ConfirmedInsert();
                    if (Result)
                    {
                        AfterInsert();
                    }
                }
            } // if (this.IsReady())

            return Result;
        } // bool InsertAndIgnoreKey(...)

        public /* nonvirtual */ bool InsertWithAssignedKey()
        {
            bool Result = false;

            if (this.IsReady())
            {
                Result = BeforeInsert();
                if (Result)
                {
                    Result = ConfirmedInsert();
                    if (Result)
                    {
                        AfterInsert();
                    }
                }
            } // if (this.IsReady())

            return Result;
        } // bool InsertWithAssignedKey(...)

} // class EntityClass
```

In this C# example, there are several methods, part of a single class.

Check that the combined non virtual methods, usually call other virtual methods.

This combination, restricted by the modifiers, defines a process,
called "Strategy Design Pattern", that has a goal, but, yet, allows,
some customization by subclassing.

Title: How and Why should class modifiers enforce or prevent inheritance and the ability to override

Body:
This isn't really related to anything I am working on currently, its more of a question I really couldn't find an answer for.

Class modifiers like MustInherit or NotOverridable to me, seem like they only need to be used in larger programs that have multiple people working on and editing it.

I can see in a situation like that how forcing or preventing people to inherit or override makes sense, but in smaller programs I just don't see why or if these would be used.

Is that basically what these modifiers are for or am I missing the purpose of them.

Body:
Quick Answer

Members inheritance modifiers allows developers to put guidelines, on how an object members should be inherited.

Long, Boring, Extended Answer

The combination of non-virtual methods and virtual methods, (and "final" or "sealed", and "abstract" methods), in an algorithm, allows to restrict a goal.

Remember that those modifiers may vary from one Programming Language to Another P.L.

MustInherit from V.B. is commonly used as virtual, in other P.L.

Overriden from V.B. is commonly used as override, in other P.L.

NotOverridable from V.B. is not explicitly used in many P.L., I usually add a small, one line comment like /* nonvirtual */.

In Java, before the @override marker or directive was added, I used /* @override */.

I develop a lot of large O.O. programs, usually done entirely by myself, most of them for work, sometimes as a hobby. Even, in small programs, I add modifiers, because the logic of trhe program requires.

A good example, is when you combine several of them:

public class EntityClass
{

        public virtual bool IsReady()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool IsReady()

        public virtual bool GenerateKey()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool GenerateKey()

        public virtual bool BeforeInsert()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool BeforeInsert()

        public virtual bool ConfirmedInsert()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool ConfirmedInsert()

        public virtual bool AfterInsert()
        {
            bool Result = false;

            // depends on the class

            return Result;
        } // bool AfterInsert()

        public /* nonvirtual */ bool InsertAndGenerateKey()
        {
            bool Result = false;

            if (this.IsReady())
            {
                Result = GenerateKey();
                if (Result)
                {
                    Result = BeforeInsert();
                    if (Result)
                    {
                        Result = ConfirmedInsert();
                        if (Result)
                        {
                            AfterInsert();
                        }
                    }
                }
            } // if (this.IsReady())

            return Result;
        } // bool InsertAndGenerateKey

        public /* nonvirtual */ bool InsertAndIgnoreKey()
        {
            bool Result = false;

            if (this.IsReady())
            {
                Result = BeforeInsert();
                if (Result)
                {
                    Result = ConfirmedInsert();
                    if (Result)
                    {
                        AfterInsert();
                    }
                }
            } // if (this.IsReady())

            return Result;
        } // bool InsertAndIgnoreKey(...)

        public /* nonvirtual */ bool InsertWithAssignedKey()
        {
            bool Result = false;

            if (this.IsReady())
            {
                Result = BeforeInsert();
                if (Result)
                {
                    Result = ConfirmedInsert();
                    if (Result)
                    {
                        AfterInsert();
                    }
                }
            } // if (this.IsReady())

            return Result;
        } // bool InsertWithAssignedKey(...)

} // class EntityClass

In this C# example, there are several methods, part of a single class.

Check that the combined non virtual methods, usually call other virtual methods.

This combination, restricted by the modifiers, defines a process,
called "Strategy Design Pattern", that has a goal, but, yet, allows,
some customization by subclassing.


问:
Controller / Service - Should a service save changes to the database
I have an action on my controller called DeleteLine. This removes a line from the users basket.

My controller action looks like this:

```<code>[HttpGet]
public ActionResult DeleteLine(int orderId, int lineId)
{
    var orderResult = _salesOrderService.DeleteLine(_workerContext.CurrentCustomer, orderId, lineId);

    var errorMessage = "";
    switch (orderResult.Type)
    {
        case SalesOrderResultType.Deleted:
            errorMessage = "Item Removed. You now have no items in your basket.";
            break;
        case SalesOrderResultType.Failed:
            errorMessage =
                "Something went wrong and your item could not be removed from your cart. Please try again.";
            break;
        case SalesOrderResultType.FailedAlreadyComplete:
            errorMessage =
                "The item you are trying to remove is part of an order that has already been completed.";
            break;
        case SalesOrderResultType.NotFoundForCustomer:
            errorMessage =
                "The item which you are trying to delete does not belong to an order we can find for you.";
            break;
    }

    if (errorMessage.IsNotEmpty())
        return ErrorNotificationView(errorMessage);

    AddSuccessNotification("Your item has been deleted successfully.", false);

    if (Request.UrlReferrer != null)
        return Redirect(Request.UrlReferrer.ToString());

    return View();
}
</code>```

Most of the actual leg work is done in _salesOrderService.DeleteLine which does checks to see if the order id belongs to the customer, removes the selected item and then finally removes the whole order if no lines are left on it.

My Question Is: Should the service be handling this or is it up to the controller?

From my perspective, I've put it in the service as it means I can remove an item from a users basket anywhere with relative ease but I want to make sure this is the correct approach before continuing.

答: I'm in the "thin controllers" school of thought -- or in this case the service should be responsible for all persistance operations -- the controller is just there to be a traffic cop between HTTP requests and the service layer -- sending input in, interperting results out and doing the right thing. On the flip side the service layer should be blissfully unaware it is being called via a web controller, web api, console app or whatever else you might use.</p>

ContentLicense: CC BY-SA 3.0


问:
How to calculate figure rotation efficiently?

I have a Figure represented through a matrix of bytes (bitmap-like matrix).
Example Figure is shown on the Picture 1.

The goal is to find the best rotation angle of some given Figure.
When Figure is rotated by best angle, the rectangle that is parallel to X and Y axes and inscribes the Figure has the smallest area.

Rectangles that inscribes the figure are shown as light-gray on the pictures.
In the Picture 2, you can see that ideal rotation of the Figure is about 30 degrees clockwise.

Now, I know algorithm how to find this angle, but it seems to me that is very inefficient.
It goes like this:

Loop through angles from 0 to 45.

For the current angle, for every figure point calculate new, rotated, location

Find bounds of rectangle that contains figure (minimum and maximum x,y) and register it if is the best match so far

Next angle

This is a kind of brute-force method and works well and reasonably fast for the small figures.
However, I need to work with figures that contain up to 10 million points,
and my algorithm becomes slow.

What would be good algorithm for this problem?

答:
It looks like you can find the arbitrarily aligned minimum bounding box using the linear time Rotating calipers algorithm.

Once you have the bounding box, you just need to determine the angle of rotation by calculating the slope of one of the sides.


问:
Can objects constructed from the same class have unique method definitions?
I know this seems like a weird question, since the point of two or more objects sharing the same class is that their behavior is the same, i.e. their methods are identical.

However, I'm curious if there are any OOP languages that allow you to redefine the methods of objects in the same way that you can assign different values for their fields. The result would be objects constructed from the same class no longer exhibiting the exact same behavior.

If I'm not mistaken, you can do this JavaScript? Along with this question, I ask, why would someone want to do this?

答:
I'm not saying it's a good thing to do, but this is trivially possible in Python.  I can't thing of a good use case off the top of my head, but I'm sure they exist.</p>

```<code>    class Foo(object):
        def __init__(self, thing):
            if thing == "Foo":
                def print_something():
                    print "Foo"
            else:
                def print_something():
                    print "Bar"
            self.print_something = print_something

    Foo(thing="Foo").print_something()
    Foo(thing="Bar").print_something()
</code>```

Body:
I'm not saying it's a good thing to do, but this is trivially possible in Python.  I can't thing of a good use case off the top of my head, but I'm sure they exist.

    class Foo(object):
        def __init__(self, thing):
            if thing == "Foo":
                def print_something():
                    print "Foo"
            else:
                def print_something():
                    print "Bar"
            self.print_something = print_something

    Foo(thing="Foo").print_something()
    Foo(thing="Bar").print_something()


答:
The first step of your approach is flawed - there are an infinite number of real values between 0 and 45, so it makes no sense to "loop through them". However, your algorithm can be repaired:

find the convex hull of the polygon

loop through the finite (!) number of angles given by the outer edges of the convex hull

now apply the steps 2 to 4 using these angles.

This works because it can be shown that the minimum enclosing rectangle must touch one of the outer edges of the convex hull.

Title: How to calculate figure rotation efficiently?

Body:
I have a Figure represented through a matrix of bytes (bitmap-like matrix).
Example Figure is shown on the Picture 1.

The goal is to find the best rotation angle of some given Figure.
When Figure is rotated by best angle, the rectangle that is parallel to X and Y axes and inscribes the Figure has the smallest area.

Rectangles that inscribes the figure are shown as light-gray on the pictures.
In the Picture 2, you can see that ideal rotation of the Figure is about 30 degrees clockwise.

Now, I know algorithm how to find this angle, but it seems to me that is very inefficient.
It goes like this:

Loop through angles from 0 to 45.

For the current angle, for every figure point calculate new, rotated, location

Find bounds of rectangle that contains figure (minimum and maximum x,y) and register it if is the best match so far

Next angle

This is a kind of brute-force method and works well and reasonably fast for the small figures.
However, I need to work with figures that contain up to 10 million points,
and my algorithm becomes slow.

What would be good algorithm for this problem?


问:
Architecture for a mobile (Android) chat application
I want to develop a chat application that reminds a bit whatsapp, I am doing it as a learning project. I am currently doing it on Android just because I am doing an Android course.

The requirements are:

users register with some data (phone number, name)

users can write messages to friends who also use the same application

messages are written to DB - I think there are many writes but less reads just because that when a message is sent to the server and written to DB a notification is sent to the receiver's mobile, but maybe in the future I would also want to add web interface so it might include also many reads from DB.

when message is read I want to update the DB.

I was thinking first to use MySQL for storing all users and some NoSQL for the purpose of storing the messages - MongoDB, this is because the messages data can grow to large scales very fast and using RDB might be a problem.

Do you think it will be right to use this architecture? Will MongoDB be a problem since there might be many updates? after a message was written and when the receiver's phone accepts the message an update is sent to the server indicated message received?

Maybe I am missing something that you can please think of?

If you think there is a better architecture I will appreciate if you can contribute.

Thanks.

答:
Some considerations:

Choice of database: relational databases such as Mysql or Postgres are not necessarily harder to scale than MongoDB and such. In many cases it's quite the opposite. Here is a great comparison of different storage technologies: http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis

"Event-driven" architecture: You have a lot of requirements that boil down to "when this happens, do something". A typical way to build an architecture like that is to think of events being emitted and event listeners acting upon those events. For example:

"message read" is an event that your Android app will be sending back to the server when somebody reads a message. Server can have a listener waiting for events like that, and every time it gets one, it'll go and mark the message as "read" in the database

You can think of other use cases like that: "message received" is an event - listener will take that message and forward it on to the recepient.

Another one: "user connected" - when somebody launches the app and connects to the server, you'd probably like to forward any messages directed to them that gathered while they were offline - that can be easily addressed using events.

You would typically have a message queue as the center piece of your application, with all kinds of listeners connected to it, and all events that are emitted sent through it.

3rd party solutions: If you are doing this as a learning exercise with focus on Android development, consider using a 3rd party solution that can take care of a lot of your backend needs. One example is https://www.firebase.com/. Building a full-blown backend system for an app like this, with serious scaling and performance requirements is a lot of effort which will take your time away from learning Android.

Start simple, iterate: I'd start with a very simple back-end app without a database, and develop it in parallel with the Android app. Make sure you understand as much as possible about your requirements before you make big decisions about what database to use etc - the only real way to do that is to prototype and iterate as quickly as possible.

Now, some concrete solution "templates" that you can use as starting points:

Firebase-powered backend

Go this route if:

You would rather focus on learning Android and not worry about the backend

You favor getting something running quickly over getting your hands dirty with every part of the system at once

Firebase can take care of much of your needs. You won't need to think about the database and scaling. But you'll need to understand their data models.

Some places to start with:

https://stackoverflow.com/questions/21119470/dataserver-design-based-on-firebase-for-mobile-apps

Android notifications: https://stackoverflow.com/questions/24713765/firebase-android-notifications-childadded-how-to-get-only-new-childs

Node.js + Socket.io + MongoDB + Redis

Go this route if:

You want to use a popular framework that fits the realtime communications requirement

You don't mind introducing a whole other language and set of technologies

You don't mind working with JavaScript

Rough outline of the system:

Node.js and socket.io handling all of your communication to/from Android app

MongoDB is used to store messages and user information

Redis is used as a "message queue" to connect your event emitters and event listeners

Socket.io is good at communications: you won't need to write low-level networking code. Node.js has good performance for things like that.

Pointers:

Socket.io client for Android: https://github.com/nkzawa/socket.io-client.java

Get started quickly with socket.io and node.js: http://socket.io/get-started/

Message queue choices to use with node.js: https://stackoverflow.com/questions/4700935/what-are-good-message-queue-options-for-nodejs

Java Netty + RabbitMQ + MongoDB

Go this route if:

You want to stick with Java as much as possible

You don't mind learning a whole lot about low level networking stuff

You like to understand and control as much of your infrastructure as possible

Outline:

Netty for network communications

RabbitMQ as the message queue for communications between event emitters and listeners

MongoDB to store messages and user information

Pointers:

http://netty.io/

https://github.com/netty/netty

Google for things like "java netty chat server"


问:
Given a number which is power of 2, check if it is even power or odd power
I am given a number n , which is always a power of 2.
I want to check whether n is odd power of 2 or even power of 2.

For example: n=4 , ans= even
n=8, ans=odd (because 8 is 2^3)
n=1024 , ans=even.

Can I do it using bitwise operations/ or some faster method.

答:
I'll turn my comment into an answer, maybe I'll get a +1 or two.

The exponent of a power of 2 is even when the number is a power of 4.

That is, if the exponent is even, you can divide it by 2, so

```<code>2 ^ n = 2 ^ (2 * m) = 4 ^ m
</code>```

So (pseudocode)

```<code>function isEvenExponent(int n)
    return (n % 4) == 0
</code>```

...or if you like bitwise operations

```<code>function isEvenExponent(int n)
    return (n & 3) == 0
</code>```

Body:
I'll turn my comment into an answer, maybe I'll get a +1 or two.

The exponent of a power of 2 is even when the number is a power of 4.

That is, if the exponent is even, you can divide it by 2, so

2 ^ n = 2 ^ (2 * m) = 4 ^ m

So (pseudocode)

function isEvenExponent(int n)
    return (n % 4) == 0

...or if you like bitwise operations

function isEvenExponent(int n)
    return (n & 3) == 0


问:
Proper tree NoSQL structure with focus on full-text searching
I developing an app with tree(folder-file) structure, on which I should perform full-text searches with MongoDB. I did a research on the best tree structure practices and found this great article, but I still can not decide which DB structure will fit my needs.

I have the following requirements in my mind:

I should be able to perform full-text search on individual folders, as well as everything from specific users

The folders/files should be shareable, so I need to be able to perform full-text search on all items accessible by specific user

I've been thinking about the following structures.

Structure 1

```<code>Fields of Users collection

 1. _id - objectid
 2. name - string

Fields of Folders collection

 1. _id - objectid
 2. name - string
 3. owner - objectid
 4. sharedWith - array of objectIds
 5. location - objectid of parent folder, null if in root
 6. createDate - datetime

Fields of File collection

 1. _id - objectid
 2. name - string
 3. owner - objectid
 4. sharedWith - array of objectIds
 5. data - string
 6. location - objectId of folder
 7. createDate - datetime
</code>```

So here comes my questions:

Should I use model tree structures with Parent References or Child References?

Should I use 1 collection for both files and folders(with type field) or I should separate them.

Does it worth to have only folder collection and nest documents in it.

This were my most important questions, thought I will greatly appreciate any advice on how I can improve the structure.

答:
Some of the answers depend on how you foresee the system being used. Without knowing more about your specific requirements, my answer is aimed at a generally flexible system that could work OK with a wide variety of use cases, and not assuming any "shortcuts" (like, absolute limit on number of folders etc). More specifically:

Should I use model tree structures with Parent References or Child References?

If you use parent references, then no matter how many documents a folder might have, the size of the object representing that folder will stay constant. If you use child references, you'll need to update the folder document object every time a file is created - this might introduce synchronization issues (2 files being added to the same folder at the same time), or document size issues (imagine a folder with a million files in it). However, having such a "normalized" structure will make it more expensive to do things like "find all folder/files nested under this root folder" without additional optimizations.

Should I use 1 collection for both files and folders(with type field) or I should separate them.

File systems typically represent both files and folders as "nodes" that then carry additional data/type information. Splitting them into separate collections only makes sense if you have some very specialized operations that you need to run on those data sets (can't think of anything off the top of my head), and having separate collections might help.

Does it worth to have only folder collection and nest documents in it.

You will lose the ability to access individual files without loading everything else that's in that folder. Plus, this will be problematic if the number of files per folder grows and your folder objects start getting very big. Separate documents that represent separate "nodes" of your file system is probably the way to go.

Tradeoff: if you know that you'll have a rigid folder structure with a handful of folders and not too many documents, a nested structure could be convenient.

When answering questions like these, it's very helpful to either know all of your requirements upfront, OR if the requirements are vague then develop a generally flexible system that's easy(er) to change/maintain once requirements are understood better.

I generally find it useful to ask extreme questions, such as "what happens if I have a billion folders with billion files each?", or "what if I have a structure that's nested a billion folders deep?". Questions like that tend to illuminate the problem in helpful ways.


问:
Git push to deploy technique
I'm adopting a git push to deploy method where I setup a bare repository on the live server which I push my local changes to. Using a post-update hook, executed after I've pushed I pull my changes to the directory housing the live site.

This method works extremely well but as we are using virtual servers sometimes disk space can be an issue, especially for out larger sites. My concern is that the bare repository and the repository where the site actually resides and is accessible means two (possibly large) repositories on the server, no?

Is i possibly to lighten this up a little? In my post-update hook, is it possible to only pull the latest changes and overwrite the previous files. Or, should I use 'cp' instead of 'git pull' for this?  I suppose after every commit I could just remove all files in the site's directory and then do a pull, then delete the .git directory?

Anyway would appreciate hearing from anyone how this is best handled. Thank you

答:
"git clone" has a couple of options that might help:

"git clone --local" tries to save space by hardlinking files if you are cloning a repository on the same machine

"git clone --shared" points your cloned repository over the where you cloned it from (on the same machine) and avoids copying objects over. There is a serious warning around this, read "man git-clone"

"git clone --reference" is similar to "--shared"

git tries to use "clone --local" by default if you are cloning a repo located on the same machine, so you might already be benefiting from that.

Title: Git push to deploy technique


问:
Using PHP or C++ for in real world electronic devices
I want to use my programing skills to make my day-to-day life easier, to do this I want to be able to program in my appliances like alarm clock or microwave or refrigerator, air conditioner etc, wish they had firmware that I could flash with my program to control them and adjust their work to my liking.

Right now I am limited with desktop or laptop you know when power goes down all you done is not there anymore.

I know in school they show how to program basic clock on electronics class with some 3rd party programming language, currently I assume there are 10's of different programming languages for devices and I don't want to learn different language for each device, wish there was like API on each device that I can use with whatever programming language I normally use e.g. PHP.

I am basically looking for way to adjust /expand functionality of real life standalone electronics (without connecting them to PC or using virtual analogue) learning programming language company used when created it.

Are there any appliances that support this or is there some language converter I can add to make it possible?

P.S. Currently there are Raspberry PI computers for $40 bucks that fit in hand perhaps I can create my own say alarm if I put it in a box and attach speaker to it and then program is with using PHP or it's currently not possible?

Not interested in inventing anything, just wondering if there are ready tools / ways to customize application firmware without learning their specifics today?

答:
This is a quick article about the relationship between APIs and hardware.

Generally, if you are accessing hardware directly, you would generally use a C or C++ driver. You might raise the question: how do all the other languages access the hardware? They utilize the C or C++ compiled driver.

EDIT: One of the commenters provided a list of high-level language compilers and interpreters for microcontrollers, so my statement was outdated. These would give you the options of using Embedded Java, Python, Lisp, etc. It would be interesting to investigate if each of the interpreters is tightly coupled to a processor, or if it is as simple as a recompile by processor.

Does this mean you need C and C++ for anything you do? Yes and no. It depends upon the APIs available to you. A C driver may have a C# wrapper around it, and you can do what you need in C#! I was on a C# project, and we had a couple C# wrappers for C++ libraries. However, if you are really interested in programming specifically for the hardware, you will not be able to use an interpreted language (as is PHP) or a non-native language (Java). You will need to run native, as compiled C or C++ does.

And this really assumes that you are creating your own clock, light, microwave, etc. I suppose a Raspberry PI machine would do -- or would be an accessible overkill -- for what you want to do. If you want to control a commercial product, the manufacturer needs to provide you an interface to manipulate their product.


问:
Why aren't HTML, CSS, and JavaScript used for desktop apps?
HTML, CSS, and JavaScript can be used to build beautiful (and useful) UI's (especially now we have HTML5 and CSS3), and lots of people already know them. Though it's still way beyond my reach, how difficult can it be to bring the whole web app thing to desktop apps? We already test apps on our local servers before hosting them.

In my opinion, it's a nice, simple idea which will create a boom in desktop apps. Plus, given that these apps will already be sharing so much code with web apps, they might be able to offer better connectivity.

Why isn't it being done?

答:
A bit late, but if you use AsYouWish in Firefox (or create Firefox add-ons if you don't mind zipping up your files and testing with their tools), you can create apps in HTML which have desktop privileges. If you use WebAppFind (currently Windows only), you can also get desktop files to open from the desktop directly into a web app (without a need for drag and drop).

Disclaimer: These (open-source) add-ons were created by me.


答:
Rather than trying to modify the firmware of devices, and alternative is to harness what is already in place. As you say, a small single-board computer is a good solution.

Try a Google search on Arduino. These boards are cheap, and are designed to control lots of IO lines. Programming in C or C++ is the norm and you are working with bare metal - there is no operating system. There is a SE Arduino community.

Compared to the Rasberry PI, Arduino has better IO capabilities and lower power consumption, but far less RAM and CPU power. You can run a web server on Arduino, but only just. HTTPS and a solid authentication scheme are probably impossible, meaning you need something more powerful to front it to the Internet.

Don't discount controlling modern electronic devices via their IR remote port. I control my heatpump across the Internet using an Arduino to synthesise the IR stream. This is a great solution, as there is no modification to the device, and no danger of zapping yourself accross the mains.

There are some crossover boards appearing: the Arduino YUN has both an Arduino IO processor and a Linux capable processor. This would be ideal for tasks where you need to publish a secure web server. You can program in PHP under Linux and control the IO from the Arduino.

Title: Using PHP or C++ for in real world electronic devices

Body:
I want to use my programing skills to make my day-to-day life easier, to do this I want to be able to program in my appliances like alarm clock or microwave or refrigerator, air conditioner etc, wish they had firmware that I could flash with my program to control them and adjust their work to my liking.

Right now I am limited with desktop or laptop you know when power goes down all you done is not there anymore.

I know in school they show how to program basic clock on electronics class with some 3rd party programming language, currently I assume there are 10's of different programming languages for devices and I don't want to learn different language for each device, wish there was like API on each device that I can use with whatever programming language I normally use e.g. PHP.

I am basically looking for way to adjust /expand functionality of real life standalone electronics (without connecting them to PC or using virtual analogue) learning programming language company used when created it.

Are there any appliances that support this or is there some language converter I can add to make it possible?

P.S. Currently there are Raspberry PI computers for $40 bucks that fit in hand perhaps I can create my own say alarm if I put it in a box and attach speaker to it and then program is with using PHP or it's currently not possible?

Not interested in inventing anything, just wondering if there are ready tools / ways to customize application firmware without learning their specifics today?


答:
Here are two other options.

Instead of pushing to an intermediate repository, have the repository you push to be the directory for the live site. In there, you can simply create a post-update hook that calls git checkout HEAD. This way, the repository is stored only once.

A second option, if you cannot change where you push to, is to use git archive. That command exports the contents of a commit as a tar or ZIP file. If you read through git help archive, it has the following example, which may be relevant to your use case:

git archive --format=tar --prefix=junk/ HEAD | (cd /var/tmp/ && tar xf -)

Create a tar archive that contains the contents of the latest commit on the current branch, and extract it in the /var/tmp/junk directory.

You could wire up something similar to export the HEAD commit into your live site directory.

Title: Git push to deploy technique

Body:
I'm adopting a git push to deploy method where I setup a bare repository on the live server which I push my local changes to. Using a post-update hook, executed after I've pushed I pull my changes to the directory housing the live site.

This method works extremely well but as we are using virtual servers sometimes disk space can be an issue, especially for out larger sites. My concern is that the bare repository and the repository where the site actually resides and is accessible means two (possibly large) repositories on the server, no?

Is i possibly to lighten this up a little? In my post-update hook, is it possible to only pull the latest changes and overwrite the previous files. Or, should I use 'cp' instead of 'git pull' for this?  I suppose after every commit I could just remove all files in the site's directory and then do a pull, then delete the .git directory?

Anyway would appreciate hearing from anyone how this is best handled. Thank you


问:
Socket Connecting to Large number of IPs
I have a text file of ~600 CIDR notation IP blocks which, when expanded, amount to ~17.5M IP addresses. I need to socket connect to each one. If it connects, I add it to a "live" list, if it returns an error/refusal, to a "dead" list. Then the socket is closed. I don't need to read from it, I don't need to write to it. Obviously, this is a problem of scale, if we generously assume that the connection takes only one second to return success or failure, it would take months to complete, but likely several years. I need to get it down to <24 hours.

Right now I'm using Python to expand/count each of the IP addresses, because it is trivial to do so. I am writing a simple multi-threaded C program to address the above problem. There are a few ways I have thought of to tackle this:

Purely using C: I have not found a way to expand a CIDR block in C, (handling strings in general is a pain). I could probably cook something up, but if something already exists I'd love to hear about it.
Will I be able to spawn enough threads? Even if I spawn a thread for each block, that 600 threads! I feel like I need to shrink the stack space allotted to the threads to do this maybe? Even so, I need to be able to handle a large number of strings because the blocks need to be expanded. Regardless, I have looked at the list by hand, and one of the blocks has a /10 CIDR notation, which amounts to >4M IPs by itself. This would still take far too long.

Spawning C processes from Python: This would trivialize the string problem, and each individual IP could be sent to an instance of a C function called from Python, which would then end. The question I have is: when Python calls an external C function, does it continue running with the C process in parallel? Or does it wait for the C function to complete? I know Python does not allow multi-threading (or rather, it does, but it's somewhat of a joke since only one line is interpreted at a time), so is this the correct way to "export" multi-threading?

Vice versa: As above, but with C calling Python code, is this "more" correct? Which is to say, can C initiate multiple Python processes and continue to do it's own thing?

Something completely different.

Any questions, suggestions, or concerns are welcome. Please point out anything I might be missing or incorrect assumptions I have made.

Thank you for your help.

答:
You need to break this down into two steps:
First, use python to parse the text file and generate a list of IP address that are easy to consume in  C.

Second, let's look at the exact problem.
You want to "connect" but you are not going to read or write. I am not sure what the purpose of this is. Couldn't you use ping to accomplish the same thing?
If you still want to open a socket then you  need to implement the three way TCP/IP handshake ( SYN, SYN-ACK, ACK) in a single thread. You will be dealing directly with the underlying IP layer, essentially simulating what  TCP does for you.
If you remember that each 'connection' is really just a pair of address, port combinations and you have 64k ports at your disposal, then your speed is limited only by the latency of the handshake.
(This is starting to sound like a good homework question...)
If you can fire out the SYN packets at a rate of several hundred a second, and each transaction has a round trip latency of 200 ms... You can work out how long it will take you to work through your list of millions of addresses.

Here are some useful references.
You want to learn to use raw sockets. You will be implementing the taco handshake yourself.

http://www.tenouk.com/Module43a.html

https://stackoverflow.com/questions/110341/tcp-handshake-with-sock-raw-socket

http://gonullyourself.org/library/A%20brief%20programming%20tutorial%20in%20C%20for%20raw%20sockets.txt

Good luck


问:
When to choose an open source license?
There are many good questions out there about choosing an open source license, reasons to go open source, etc. However I have not seen an answer to this question and I feel like more people could relate...

Say I am working on a project, putting up code on GitHub for the world to see. At what point do I go about selecting and using an open source license? Should I have done that already? After a few forks? Does interest matter?

答:
All code is protected by copyright in one form or the other (unless it has been placed explicitly in the public domain). If you do not attach an explicit copyright license, the default copyright license applies, which amounts to "the code belongs to the author and nobody else can use it."

If you publish your code, especially if it is on a code sharing site like GitHub, you should decide on the license you want to use before committing the very first revision.

Some things to remember:

If you don't have a license that allows making copies, forking your repository is a violation of your copyright.

Once you have uploaded a revision of a file with a particular copyright license, you can't change that license. You can upload a new version with a different copyright license (either more or less restrictive), but people will only ever be bound by the license that was in effect at the time that they copied/forked your repository.

Title: When to choose an open source license?


问:
How to introduce Agile to a team that uses rigid non-Agile methods?
Consider a company that is proudly certified for some non-Agile methodology, uses it as a selling point to its customers to demonstrate accountability.

How do you go about introducing Kanban or Scrum progressively without breaking their whole system and still making them confident that it can still be just as accountable / auditable?

I know this is possibly related to "How would you introduce an agile methodology like Scrum", but here I am wondering about ways to circumvent/work around the fact that the company imposes a certain way of managing the SDLC under the false pretense that it's the only way to have an audit trail.

答:
Like any new thing you will try to introduce to an organization, you will face strong opposition. Are you ready to be criticized and be the responsible if it fail? You have to be a strong person. That's the price to pay when expose yourself.

Ask yourself why you want to use Scrum. Do you need to solve a real problem?

Ensure that YOU are committed to it, because nobody will do it for you. You will be the owner of the thing. At least until it brings positive effects in the organization

Train yourself. Books and internet is not enough. Go to a course first, or you will increase dramatically your chance to implement Scrum incorrectly. Which will probably lead your team to worse results than before

Sell it to the team first. You must have their full support, obviously

Don't propose a change, propose a test. And consider it like that. Scrum may not be suitable to your organization (or to your team)

Find a sponsor in the top management

ContentLicense: CC BY-SA 2.5


问:
Using Code First concept of Entity Framework in production
I'm developing an application and I have a database with it using Entity Framework Code First concept. I like this approach very much. I'm using the latest version of EF which is 6.1.1.

My main concerns are how to deal with database changes without losing data. I've done quite a few changes and a few of those changes gave me a hard time during the migration process. I just had to delete the database and start over again with the Seed() etc.

My question is, can I/should I use Code First in production for a serious business application or not? The database schema isn't that big, around 20 tables and less than a half of them are just lookup tables.

This question kind of has been asked before (see this post), but EF has been evolved a lot since than. And I'm struggling with this question quite some time now. I could really use some peace in my mind and a good night rest.

答:
The answer is YES, of course, you can use Code First in production. I have seen a lot of projects that succeed in it. You could use EF's migration engine: there are lot of examples around. Or you could give a try to another migration framework, like FluentMigrator.

And there is no danger of using migrations in production if you follow good practices in deployment: e.g. you have DEV, STAGE servers where you could test your migrations before production, + you make backups of database before each PROD release. Ideally, when all these processes are managed from your Continuous Integration server.


问:
How to deal with no code reviews in my new place when I come from that practice?
The team in my new company does not have a code review process.

I come from companies with code review as a must culture and thus I don't feel comfortable committing my code without having it reviewed by someone.

I'm a firm believer that code review is a way to improve quality and save time because it catches potential problems earlier (note I am not talking about pair programming though).

How can I show that code review is not a time waster but a time saver?

Can code review be skipped if you have unit tests?

答:
If you're an advocate of code reviews, I'm afraid there's no real substitute. The unfortunate and stereotypical case is a workplace which doesn't do code reviews because (A) they're not familiar with the practice, and/or (B) they don't want to devote the time and effort to getting a code review system in place.

Basically, to get what you want here, you need a workplace culture change - and that's never simple or easy. Don't forget that even if your workplace is 100% persuaded that code reviews are excellent and they want to adopt them, actually shifting into the new way of working will still require a significant investment of time, energy and productivity. This investment should pay itself back - but you need to have buy-in for the investment, not just for the payoff. See Roy Osherove's video "Unit Testing and TDD - How To Make It Happen" - the challenges of adopting code reviews are very very similar to those of adopting unit testing.

In the meantime, do what you can to get as much as you're able:

If there are other developers who see the value of code reviews, try
reviewing each other, even informally.

If you have a mentor or some developer responsible for your training, explain to him the value you see in code reviews, and ask if they'd be willing to review your  code, at least on occasion.

Tell your manager you'd like to review  other people's code, because it'll help you understand the system   better.

If at some point you become a team lead, you can instate   code reviews locally, just for your team.

A major benefit of any of these is, if you're able to maintain them over time, then developers around you will start noticing the code reviews. You'll effectively be demonstrating how code reviews can be integrated within the existing culture - and that opens the way for the culture to begin to change. Code reviews help, so if you're able to demonstrate that at a small scale, that will open the way for others - and the culture as a whole - to follow your example.


答:
You should also take a look at X10, which has been around at least 25 years to my knowledge. Back in the day I used to just power deceives on and off, but it has grown to be much more sophisticated since.

X10 is a protocol for communication among electronic devices used for
  home automation (domotics). It primarily uses power line wiring for
  signaling and control, where the signals involve brief radio frequency
  bursts representing digital information. A wireless radio based
  protocol transport is also defined.

X10 was developed in 1975 by Pico Electronics of Glenrothes, Scotland,
  in order to allow remote control of home devices and appliances. It
  was the first general purpose domotic network technology and remains
  the most widely available.1

Although a number of higher bandwidth alternatives exist, X10 remains
  popular in the home environment with millions of units in use
  worldwide, and inexpensive availability of new components.


问:
Big O notation allocate array of N element
In Big O notation, allocate an array of N element is defined by O(1) or O(n) ?
For example in C#, if I allocate an array like this :

```<code>int[] a = new int[10]
</code>```

When I display this array, I have :

```<code>{0,0,0,0,0,0,0,0,0,0}
</code>```

答:
Normally, size of an array has no effect on complexity of allocation itself. AFAIK, an array is internally a pointer to some address where the array begins and hidden fields for element size and element count. So it would be O(1).

At least this is the case in Object Pascal, though I am not sure for C# or other languages.

But finding the chunk of memory which fits for your array has some higher complexity which depends on the size at some point but is more dependent to how the active memory manager works: Time complexity of memory allocation.


问:
OOP CLI menu structure organization?
This problem has kept me from pursuing a project I'm working on because it influences the entire structure of the application. This question has been briefly touched on here, but I feel that it wasn't seen by many people and therefore wasn't very well answered.

I'm working on an application in charge of navigating and manipulating a binary search tree. This application is controlled through a selection menu, with some options leading to submenus. The most hack-ish approach to this problem is something like this:

```<code>int main(int argc, char *argv[])
{
    // Create the object using the data in the file at path argv[1].
    BinarySearchTree tree(argv[1]);

    bool exit = false;
    while (!exit) {
        // Print the menu out here with std::cout statements.
        // This always adds several lines that don't do much.

        // Store the users input in a variable here.
        // Coding a way that ensures something valid is input adds
        // many more lines of clutter.

        // If-elseif-else or switch statement here. More complexity with more
        // submenus that look exactly like this here. You get how complex
        // this will get.
    }
}
</code>```

Anyone who wants to type good code doesn't want their main function to be this long and messy. Breaking it into other functions sitting in my main file doesn't really help much either, it's still messy and not very object-oriented. A possible solution would be to put each menu into their own class like this.

```<code>int main(int argc, char *argv[])
{
    BinarySearchTree tree(argv[1]);
    MainMenu main_menu;
    main_menu.run();
}
</code>```

Definitely the cleanest main method, but not a viable option since my tree object can no longer be accessed from within the MainMenu methods, and I definitely don't want to pass it around endlessly within my class methods since that'd be terrible style. So finally some middle ground I came up with was like this.

```<code>int main(int argc, char *argv[])
{
    BinarySearchTree tree(argv[1]);

    MainMenu main_menu();
    bool exit = false;
    while (!exit) {
        unsigned long prompt = main_menu.prompt();

        // The switch statement here. Still a lot of complexity I don't like
        // because this can go on for quite a while depending on how deep my
        // submenus go or how much I need to do for specific commands.
    }
}
</code>```

Ok, all my sample code is out of the way. I don't like any of them, and I haven't found any truly better solutions on the internet. I'm an undergrad, so I don't have any practical experience in this. Is there some widely accepted best-practice in the industry that I don't know about? How would you approach this personally? Remember, this is being implemented in C++ so I'm trying to be as object-oriented as possible. However, if there's a functional way you know of that works really well that you'd like to share, I'd be open to it.

答:
First off, there is absolutely nothing about C++ which forces (or even encourages) you to use OOP. This is a common misunderstanding. Other languages lend themselves to OOP much better than C++, and while C++ supports OOP, it supports other paradigms much better.

That said, your problem is classic, and lends itself well to the command pattern. It’s worth noting that this can also be implemented without the use of a subclass hierarchy but let’s stick to the “classical” OOP implementation here.

A command is a subclass of the general command base class:

```<code>struct command {
    virtual std::string description() const = 0;
    virtual void run(context&) = 0;
    virtual ~command() = default;
};

using command_ptr = std::unique_ptr<command>;
</code>```

The context object contains the necessary information to fulfil the command. In your case, this could be the BinarySearchTree. So yes, you do need to pass this around. There’s no clean way around this. In fact, this is not a bad thing: it’s certainly not “terrible style” as you claim – quite the opposite!

Here is a simple command implementing this:

```<code>struct open_command : command {
    std::string description() const override {
        return "Open a file";
    }

    void run(context& context) override {
        // TODO implement.
    }
};
</code>```

Now your menu structure would contain a list of commands and show them in a loop. Simplified:

```<code>struct menu {
    menu(context& context, std::vector<command>& commands)
        : context{context}, commands{commands} {}

    void show() {
        for (int i{}; i < commands.length(); ++i)
            show(i, commands[i].description());

        show(0, "Exit");

        int choice{};
        for (;;) {
            choice = input();
            if (choice == 0) return;
            if (choice > 0 and choice <= commands.length())
                break;
        }

        commands[choice - 1].run(context);
        // Don’t leave the menu:
        show();
    }

    // TODO:
    int choice() const;
    void show(int, std::string) const;

private:
    context& context;
    std::vector<command_ptr> commands;
};
</code>```

Now the interesting thing is this: A submenu would also be a subclass of command, and could wrap the menu class. That way, you can elegantly nest command menus arbitrarily deeply.

Finally, to use this menu, you’d initialise it thusly:

```<code>std::vector<command_ptr> cmds {
    make_unique<open_command>(),
    make_unique<save_command>(),
    make_unique<edit_submenu>(
        bst,
        std::vector<command_ptr>{
            make_unique<edit_delete_command>(),
            make_unique<edit_insert_command>(),
            …
        }
    ),
    …
};
menu menu{bst, cmds};
menu.show();
</code>```

This creates some commands, of which one (edit_submenu) is a submenu, initialises a menu and shows it.

That’s it, in a nutshell. The above code requires C++14 (actually, just C++11 + std::make_unique). It can easily be rewritten to run on C++03 but C++11 is just less painful.

Two tangential remarks:

iostreams are not designed for interactive input and output. Using them to implement such an interactive menu works badly, since they cannot cope well with the peculiarities of user input. Unfortunately there is no good CLI library for C++ that I know of. The de-facto standard for CLI in the Unix world is the GNU readline library but (a) it only has a C API, and (b) its license forbids its use in anything but GNU licensed software.

There is no really good solution for this. However, most command line applications would eschew an interactive CLI in favour of command line options and commands, so that each invocation of your program would execute one command (or a combination of several), controlled by command line arguments:

```<code>bst add entry my_database.file
bst add another-entry my_database.file
bst lookup entry my_database.file > output.file.
</code>```

This is the conventional workflow of command line applications, and it’s in most regards superior, since it’s trivially scriptable and can be combined with other command line tools.

It is worth noting that, for the case of static menus (i.e. where the number of submenu items doesn’t change at runtime) the Boost.Variant library offers a superior alternative to the above class hierarchy. Each menu would be a boost::variant of the relevant commands. However, the general idea remains the same.

Title: OOP CLI menu structure organization?

Body:
First off, there is absolutely nothing about C++ which forces (or even encourages) you to use OOP. This is a common misunderstanding. Other languages lend themselves to OOP much better than C++, and while C++ supports OOP, it supports other paradigms much better.

That said, your problem is classic, and lends itself well to the command pattern. It’s worth noting that this can also be implemented without the use of a subclass hierarchy but let’s stick to the “classical” OOP implementation here.

A command is a subclass of the general command base class:

struct command {
    virtual std::string description() const = 0;
    virtual void run(context&) = 0;
    virtual ~command() = default;
};

using command_ptr = std::unique_ptr<command>;

The context object contains the necessary information to fulfil the command. In your case, this could be the BinarySearchTree. So yes, you do need to pass this around. There’s no clean way around this. In fact, this is not a bad thing: it’s certainly not “terrible style” as you claim – quite the opposite!

Here is a simple command implementing this:

struct open_command : command {
    std::string description() const override {
        return "Open a file";
    }

    void run(context& context) override {
        // TODO implement.
    }
};

Now your menu structure would contain a list of commands and show them in a loop. Simplified:

struct menu {
    menu(context& context, std::vector<command>& commands)
        : context{context}, commands{commands} {}

    void show() {
        for (int i{}; i < commands.length(); ++i)
            show(i, commands[i].description());

        show(0, "Exit");

        int choice{};
        for (;;) {
            choice = input();
            if (choice == 0) return;
            if (choice > 0 and choice <= commands.length())
                break;
        }

        commands[choice - 1].run(context);
        // Don’t leave the menu:
        show();
    }

    // TODO:
    int choice() const;
    void show(int, std::string) const;

private:
    context& context;
    std::vector<command_ptr> commands;
};

Now the interesting thing is this: A submenu would also be a subclass of command, and could wrap the menu class. That way, you can elegantly nest command menus arbitrarily deeply.

Finally, to use this menu, you’d initialise it thusly:

std::vector<command_ptr> cmds {
    make_unique<open_command>(),
    make_unique<save_command>(),
    make_unique<edit_submenu>(
        bst,
        std::vector<command_ptr>{
            make_unique<edit_delete_command>(),
            make_unique<edit_insert_command>(),
            …
        }
    ),
    …
};
menu menu{bst, cmds};
menu.show();

This creates some commands, of which one (edit_submenu) is a submenu, initialises a menu and shows it.

That’s it, in a nutshell. The above code requires C++14 (actually, just C++11 + std::make_unique). It can easily be rewritten to run on C++03 but C++11 is just less painful.

Two tangential remarks:

iostreams are not designed for interactive input and output. Using them to implement such an interactive menu works badly, since they cannot cope well with the peculiarities of user input. Unfortunately there is no good CLI library for C++ that I know of. The de-facto standard for CLI in the Unix world is the GNU readline library but (a) it only has a C API, and (b) its license forbids its use in anything but GNU licensed software.

There is no really good solution for this. However, most command line applications would eschew an interactive CLI in favour of command line options and commands, so that each invocation of your program would execute one command (or a combination of several), controlled by command line arguments:

bst add entry my_database.file
bst add another-entry my_database.file
bst lookup entry my_database.file > output.file.

This is the conventional workflow of command line applications, and it’s in most regards superior, since it’s trivially scriptable and can be combined with other command line tools.

It is worth noting that, for the case of static menus (i.e. where the number of submenu items doesn’t change at runtime) the Boost.Variant library offers a superior alternative to the above class hierarchy. Each menu would be a boost::variant of the relevant commands. However, the general idea remains the same.


问:
DDD and edit of Aggregate's descendants
In a DDD approach, suppose I have an Order (this is my aggregate root) and a Line (a descendant of an Order). In both objects I have private setter for properties and a builder that handle creations of the cluster of object.

As far as I know every action on the cluster goes through the aggregate root. Is this right?
For instance, if I need a command to hide a line I can't have simply an hide() method on the Line object, but instead I should have an hideLine() method in the aggregate root that traverse the cluster of object down to the Line.

At this point I imagine a scenario like that:

```<code>// in the aggregate root
public void HideLine(Line line){
    line.Hide();
}

// in the Line class
public void Hide(){
   this.Hidden = true;
}
</code>```

but in this way someone could do something like:

```<code>Order orderA = _repo.getById(id_A);
Order orderB = _repo.GetById(id_B);

orderB.HideLine(orderA.Lines.First());
</code>```

with unknown side effects (right now the side effect is clear, but in a more complex scenario this could create headache).

So I could take this counter-measures:

Accept an id as parameter for HideLine mehtd (i.e. public void HideLine(Guid lineId))

Check in HideLine(Line line) method that line is actually in Order.Lines collection

How I handle consistency issues? Are my solutions meaningful or I have completly miss the point?

Post scriptum after comment(s)

@Songo: The Order aggregate (note: in my real scenario it isn't an Order but a more complex cluster) starts a saga/process manager during its life that oversees the Order publishing process (try to imagine that in a real scenario an order need to be published). As soon OrderPublishingRequestEvent is catched the saga starts and try to validate the Order checking if each Line is valid, and if not the line will be hided.
Thus my command handler is something like:

```<code>public void Handle(OrderValidationCommand message)
{
    // get the aggregate
    Order order = _repository.GetById(message.OrderId);

    // call a service to make validation
    foreach (Line line in order.Lines)
    {
        var result = validator.Validate(line);

        if (result.IsValid)
            order.HideLine(line);
        else
            // do something else
    }

    order.Validate(); // raise event ValidatedOrderEvent
    _repository.Update(fornitura);
}
</code>```

答:
The Command Handler doesn't seem like the best place to put line hiding logic. It should contain orchestration but not domain rules.

Is there a way you could give the validator to Order and have it validate itself, as a single action executed in one transaction ? That would solve the Line access problem at the same time.

Maybe this would be more in line with the domain too, since I doubt you have "hide a line" as part of your ubiquitous language. It seems to me more like a side effect of validating Order lines, not a domain requirement.

Title: DDD and edit of Aggregate's descendants


问:
Managing non-domain application behaviour in CQRS
Here's a scenario.

I am building QueueUnderflow, a community-edited Q&A site for people who haven't yet grasped the basics of data structures. My users don't like it when people edit their posts so, because I want to encourage as much conflict as possible, I want to send email notifications whenever a user's post is edited so he can log in and insult the editor.

I am experimenting with CQRS. I'm not using event sourcing and have a single data store but I am using event handlers to deal with the persistence of any state changes.

In a normal N-Tier/CRUD app this might be triggered by an application facade or service layer. In my CQRS architecture, I can see a few options:

The event handler: I like this idea because it seems that sending a notification email is a concern that could well lie with an independent part of the system that wants to listen for an appropriate time to send an email and then send it, transparent to the rest of the system. I dislike this idea because Greg Young (reasonably) points out in his videos that if I were to introduce event sourcing, this would result in the same notification emails being sent out potentially many times.

The command handler: This is a more explicit approach that still makes sense to me; however, it seems that the general consensus is that command handlers should just be for coordinating domain objects and not directly performing behaviour.

The domain: This seems plain wrong. The sending of notification emails is a concern of the application, not so much the domain which is concerned primarily with business logic.

The presentation layer (or potentially some intermediate application facade that simply hands a command off to its handler and performs other application-specific actions such as sending notifications).

The question is - what part of my architecture is responsible for sending emails?

答:
Number 1 jumps out as an elegant way to do this. Can you elaborate on why Event Sourcing would result in the same emails being sent multiple times ? ES systems normally have ways to distinguish between when an event is raised for the first time and when it is reapplied later. See line 90 of this code from one of Greg Young's repos.

2 . is also an option if you consider the command handler as an Application Service. Notification sending may be viewed as application-dependent -- if the applicative context is a UI-less batch program editing thousands of posts, maybe you don't want emails to be sent.


问:
How to organize all classes derived from SRP?
As the SRP says, the way to achieve this principle is divide all into smaller. And what you have just made small, make more smaller. As consequence we got more files and my question is about it, how organize all this new classes that are generated to keep our dirs clean, as the code.

For example. I'm developing an Android app on which I have a functionality about read a rss feed. It is invoked from different screens. It's obvious that it is a responsibility but to achieve that, I have my sub responsibilities.

To read a RSS Channel I have to...:

Download XML file from URL.

Parse the XML file downloaded getting the channel details and all feed items.

So, I will have RSSChannelReader.java whose public method, something like read() will invoke NetworkRequest.java and RSSDocumentParser.java. As SOLID principles suggest interface segregation, I will use the interfaces INetworkRequest.java IRSSDocumentParser.java to operate.

Also, my RSSDocumentParser.java will use ChannelRSS.java and ChannelRSSFeedItem.java that works as vo for general channel description and feed items values.

So, I will have all this new classes: RSSChannelReader.java, INetworkRequest.java, IRSSDocumentParser.java, NetworkRequest.java, RSSDocumentParser.java, ChannelRSS.java, ChannelRSSFeedItem.java.

My app dir structure is:

Activities/: Contains the app screens.

Models/:

Business/:

Libs/:

[...]

Then, where do I put all these new files? I supposed to put RSSChannelReader.java, IRSSDocumentParser.java,RSSDocumentParser.java, ChannelRSS.java, ChannelRSSFeedItem.java in business/RSSChannelReader. There is some problem if I mix the interfaces files with their implementations?

What about ChannelRSS.java, ChannelRSSFeedItem.java. Must be there on bussiness/RSSChannelReader or as they act as value object must be on models\. I have to say that I work with them in the windows/screens of my app. Or maybe to create an adapter to transform the result object generated by my RSSChannelReader.java to my model object?

INetworkRequest.java and NetworkRequest.java should be in a different folder from business/RSSChannelReader.

My real problem, I think, is that some responsibilities, in this case ReadRSSChannel can produce other that can actuate as responsibilities for other responsibilities, for example my NetworkRequest. I can use to read rss but also could be useful for download images.

Do I have to create a new folder for each responsibility?

I'm a little confused because my project is increasing and some files aren't place in the correct place. In some places my package name is too long with sub levels.

答:
I am not an android developer but your question is generic enough so I will take a stab at it.

how organize all this new classes that are generated to keep our dirs
  clean

In Java world you will be doing this by placing code in separate packages. For example in your case, you can create a package com.yourcompany.rss and place all files in there.

As long as com.yourcompany.rss package contents stick to SRP and define interface only for RSS parsing/consumption it is okay to mix interfaces with implementation. However, if in an app you get dozens of interfaces and implementation, you should consider sub-packages.


问:
Programming against interfaces in Java
Supposing I have an interface Foo and a given implementation FooImpl.

```<code>public class FooImpl implements Foo
</code>```

If I want to define a new operation on this class that depends on the particular implementation, is it correct to define it in the implementation class or as a static method on an Util class like FooUtils.operation?

```<code>public class FooImpl {
  public void operation() {
    ...
  }
}

public class FooUtils {
  public static void operation(Foo f) {
    ...
  }
}
</code>```

The first option forces me to cast to the given implementation class whenever I want to use it on an object that is declared of the type of the interface (it is good practice to program against interfaces). For example:

```<code>Foo f = FooImpl.newInstance();
((FooImpl) f).operation();
</code>```

which is a bit ugly.

The second option doesn't have this problem but it is not very pretty either:

```<code>FooUtils.operation(f)
</code>```

答:
If not every implementer of Foo is supposed to contain operation(), then operation() cannot be declared in Foo, plain and simple.

Programming against interfaces rather than concrete classes is a good idea, but only if the interface actually is sufficient for your needs. If you need to call operation(), then you should declare FooImpl, or maybe a custom subinterface of Foo, but never Foo. That would completely subvert the point of using an interface: not having to know concrete subclasses.

Title: Programming against interfaces in Java


答:
First, if you find yourself always doing casting before calling some operation, it might be a sign that there's something wrong with your inheritance structure. If your inheritance is good, all the methods can be called by other classes are exposed in the interface and you will not need to do casting

Not everything needs to be abstracted in the interface. You will generally use interface for testability (to introduce fake object easily) or if you have several implementation. I'll not use interface for domain entities.

Whether to put operation in the class or in another class, need to see the nature of the operation. Does the operation use most of the fields from this class? If so most probably it belongs to this class. For me, generally I'll try to avoid static method, unless it's really something not related to domain logic

Title: Programming against interfaces in Java

Body:
Supposing I have an interface Foo and a given implementation FooImpl.

```<code>public class FooImpl implements Foo
</code>```

If I want to define a new operation on this class that depends on the particular implementation, is it correct to define it in the implementation class or as a static method on an Util class like FooUtils.operation?

```<code>public class FooImpl {
  public void operation() {
    ...
  }
}

public class FooUtils {
  public static void operation(Foo f) {
    ...
  }
}
</code>```

The first option forces me to cast to the given implementation class whenever I want to use it on an object that is declared of the type of the interface (it is good practice to program against interfaces). For example:

```<code>Foo f = FooImpl.newInstance();
((FooImpl) f).operation();
</code>```

which is a bit ugly.

The second option doesn't have this problem but it is not very pretty either:

```<code>FooUtils.operation(f)
</code>```


问:
Is factory pattern a right pattern for the situation described here?
Is factory pattern a right pattern when we want to consolidate the related objects?

Problem - In the Set-top box, I have a user-io, basically the interface to control the settop box - The user-io can be rcu i.e. remote control, front panel - the buttons on the Set-top box, and the rear-rcu - this is used for testing the bunch of settop boxes.

Solution -  A factory object that checks whether the user-io type is rcu or front-panel. This factory object will create the required product. The factory object has a dependency on the abstract user-io. This user-io will force to have the concrete class the following methods - Channel up, Channel down, Volume up, Volume down, Power Up/down and the number key ( which may not be in the front-panel). Thus front panel will not do anything on the method number key pressed.

The factory object will create the concrete class ( rcu or fp) and will store in the user-io type pointer.

The main class, will create a factory object, that can be singleton, and will have the related objects with it.

Can I say that the advantage here what I will gain is the following
a. The related classes are consolidated/organized together.
b. When I want to access the rcu or fp. I see them as only user-io, which is true by concept.
c. The FP will have the led or flash light functionality.So, while creating the fp, I need to create LED object also. A FP dependency on the LED,which I can hide from the user

Disadvantage -
1. Although frontpanel doesn't have number key pressed functionality. I will be adding the dummy method for frontpanel also.

答:
You could use a factory, but you said that the factory would have "a dependency on the abstracted user-io", which would already be instantiated.

The factory should be the means by which the abstracted user-io is created in the first place. If that is already created then you've already passed the point where the factory would be useful.

Something will happen that will determine which user-io should be used. This could be a UX event, input value, or a difference in IR signal, whatever. That should be what the factory has a dependency on, if a factory is indeed necessary.

Technically you only need an abstract class or interface, where the FP implementation does not support everything. Alternatively the common interface could only include the common functionality of the two implementations.

Ultimately only you have enough info for which to decide how to implement the solution, we can only help provide understanding about where certain tools and patterns can be beneficial.


问:
Looking for advice for the following MS SQL Schema
We currently have the following SQL Schema:

```<code>Projects
   Budgets
       BudgetTabs
            BudgetSections
                BudgetTasks
                   BudgetTaskDetails
                   BudgetUnits
</code>```

The data held in these tables is used to specify how much a project will cost to complete.

The problem I foresee is that whenever we need to get the total value of a project we have a query with a minimum 6 joins (there maybe more if including some other project information). As our db is a multi-tenant the these tables are likely to contain hundred of thousands of rows.

We've been wondering whether this information would be better stored in a document db such as MongoDB, which would also enable us to move some of the calculations out of SQL and into our code.

答:
Six joins doesn't sound like a lot to me, and I work with multi-tenant databases all day long. My advice is to join on your tenant ID at each step, and build your primary keys with tenant ID in them. That should get you 90% of the way there. If you still need more performance, look at the execution plans and determine if you need to reorder some joins or add indexes.

Rather than think up hypothetical performance problems, measure the real ones you have. SQL Server is more than happy to process billions of rows... a few hundred thousand won't give it pause so long as you give SQL Server some help along the way.


问:
What did people do before templates in C++?
I am not new to programming, but I am one that started a few years ago, and I do love templates.

But in the before times, how did people deal with situations where they needed compile-time code generation like templates? I'm guessing horrible, horrible macros (at least that's how I'd do it), but googling the above question only gets me pages and pages of template tutorials.

There are many arguments against using templates, and while it typically boils down to readability, "YAGNI", and complaining about how poorly it is implemented, there is not a lot out there on the alternatives with similar power. When I do need to do some sort of compile-time generics and do want to keep my code DRY, how does/did one avoid using templates?

答:
The traditional way to implement generics without having generics (the reason templates were created) is to use a void pointer.

```<code>typedef struct Item{
        void* data;
    } Item;

typedef struct Node{
    Item Item;
    struct Node* next;
    struct Node* previous;
} Node;
</code>```

In this example code, a binary tree or doubly-linked list can be represented.  Because item encapsulates a void pointer, any data type can be stored there.  Of course, you would have to know the data type at runtime so that you can cast it back to a usable object.

Body:
The traditional way to implement generics without having generics (the reason templates were created) is to use a void pointer.

typedef struct Item{
        void* data;
    } Item;

typedef struct Node{
    Item Item;
    struct Node* next;
    struct Node* previous;
} Node;

In this example code, a binary tree or doubly-linked list can be represented.  Because item encapsulates a void pointer, any data type can be stored there.  Of course, you would have to know the data type at runtime so that you can cast it back to a usable object.


答:
As Robert Harvey already said, a void pointer is the generic data type.

An example from the standard C library, how to sort an array of double with a generic sort:

```<code>double *array = ...;
int size = ...;
qsort (array, size, sizeof (double), compare_doubles);
</code>```

Where compare_double is defined as:

```<code>int compare_doubles (const void *a, const void *b)
{
    const double *da = (const double *) a;
    const double *db = (const double *) b;
    return (*da > *db) - (*da < *db);
}
</code>```

The signature of qsort is defined in stdlib.h:

```<code>void qsort(void *base, size_t nmemb, size_t size,
    int (*compar)(const void *, const void *)
);
</code>```

Note that there is no type checking at compile time, not even at run time.  If you sort a list of strings with the comparator above that expects doubles, it will happily try to interpret the binary representation of a string as a double and sort accordingly.

Title: What did people do before templates in C++?

Body:
I am not new to programming, but I am one that started a few years ago, and I do love templates.

But in the before times, how did people deal with situations where they needed compile-time code generation like templates? I'm guessing horrible, horrible macros (at least that's how I'd do it), but googling the above question only gets me pages and pages of template tutorials.

There are many arguments against using templates, and while it typically boils down to readability, "YAGNI", and complaining about how poorly it is implemented, there is not a lot out there on the alternatives with similar power. When I do need to do some sort of compile-time generics and do want to keep my code DRY, how does/did one avoid using templates?

Body:
As Robert Harvey already said, a void pointer is the generic data type.

An example from the standard C library, how to sort an array of double with a generic sort:

double *array = ...;
int size = ...;
qsort (array, size, sizeof (double), compare_doubles);

Where compare_double is defined as:

int compare_doubles (const void *a, const void *b)
{
    const double *da = (const double *) a;
    const double *db = (const double *) b;
    return (*da > *db) - (*da < *db);
}

The signature of qsort is defined in stdlib.h:

void qsort(void *base, size_t nmemb, size_t size,
    int (*compar)(const void *, const void *)
);

Note that there is no type checking at compile time, not even at run time.  If you sort a list of strings with the comparator above that expects doubles, it will happily try to interpret the binary representation of a string as a double and sort accordingly.


答:
As other answers pointed out, you can use void* for generic data structures.  For other kinds of parametric polymorphism, preprocessor macros were used if something got repeated a lot (like dozens of times).  To be honest, though, most of the time for moderate repetition, people just copied and pasted, then changed the types, because there are a lot of pitfalls with macros that make them problematic.

We really need a name for the converse of the blub paradox, where people have a hard time imagining programming in a less expressive language, because this comes up a lot on this site.  If you've never used a language with expressive ways of implementing parametric polymorphism, you don't really know what you're missing.  You just sort of accept the copying and pasting as somewhat annoying, but necessary.

There are inefficiencies in your current languages of choice that you aren't even aware of yet.  In twenty years people will be wondering how you eliminated them.  The short answer is you didn't, because you didn't know you could.


答:
I think templates get used a lot as a way to reuse container types that have a lot of algorithmic values such as dynamic-arrays (vectors), maps, trees, etc. sorting, etc.

Without templates, necessarily, these contain implementations are written in a generic way and are given just enough information about the type required for their domain.  For instance, with a vector, they just need the data to be blt'able and they need to know the size of each item.

Let's say you have a container class called Vector that does this.  It takes void*.  The simplistic usage of this would be for the application layer code to do a lot of casting.   So if they are managing Cat objects, they have to cast Cat* to void*, and back all over the place.   Littering application code with casts has obvious problems.

Templates solve this.

Another way to solve it is to create a custom container type for the type you're storing in the container.    So if you have a Cat class, you'd create a CatList class derived from Vector.   You then overload the few methods that you use, introducing versions that take Cat objects instead of void*.   So you'd overload the Vector::Add(void*) method with Cat::Add(Cat*), which internally simply passes the parameter to Vector::Add().  Then in your application code, you'd call the overloaded version of Add when passing in a Cat object and thus avoid casting.   To be fair, the Add method wouldn't require a cast because a Cat* object converts to void* without a cast.  But the method to retrieve an item, such as the index overload or a Get() method would.

The other approach, the only example of which I recall from the early 90s with a large application framework, is to use a custom utility that creates these types over classes.   I believe MFC did this.  They had different classes for containers like CStringArray, CRectArray, CDoulbeArray, CIntArray, etc.   Rather than maintain duplicate code, they did some type of meta-programming similar to macros, using an external tool that would generate the classes.   They made the tool available with Visual C++ in case anyone wanted to use it -- I never did.   Maybe I should have.   But at the time, the experts were touting, "Sane subset of C++" and "You don't need Templates"


答:
You can use Javascript, HTML and CSS to build apps for the Windows Store, Windows Phone and - I assume - XBox via "Universal Apps". (To be clear, starting in Visual Studio using File|New Project...)

This is using the above to build your UX and the application code against an implementation of the native APIs.

Naturally instead of this being seen as an attempt by Microsoft to open up the platform to more developers it was seen as deprecating C# and XAML based dev - which of course they weren't but that's not nearly as good a story... regardless whilst these are not necessarily the sorts of desktop apps the question considers they are native.

Title: Why aren't HTML, CSS, and JavaScript used for desktop apps?

Body:
HTML, CSS, and JavaScript can be used to build beautiful (and useful) UI's (especially now we have HTML5 and CSS3), and lots of people already know them. Though it's still way beyond my reach, how difficult can it be to bring the whole web app thing to desktop apps? We already test apps on our local servers before hosting them.

In my opinion, it's a nice, simple idea which will create a boom in desktop apps. Plus, given that these apps will already be sharing so much code with web apps, they might be able to offer better connectivity.

Why isn't it being done?


问:
DDD models and localization?
Let's say I have a Book that has it's title and description localized in any number of languages.

Localization only matters for e.g. administrators, because users chooses their localization and they need to see only their localization, not all of them. Administrators, however, needs to have full support for localization management.

I would have two entities for this: Book - that is localized for the user. The repository would be aware of localization, so we don't even need to pass current localization all the time.

Then, I will have another entity: Book2 (yeah, needs a better name) that will contain a Map<Locale, String> instead of simple string for a title. This entity would be use in 'admin' context.

I also do not see a way to make both Books to be of the same type.

Would this be a good approach? Any wisdom on this?

答:
I have used a complex properties for this kind of situation, with the following structure:

```<code>TranslatedValue
    Value
    TranslationList
        Translation1
            Locale
            Value
        Translation2
            Locale
            Value
        Translation3
            Locale
            Value
...
</code>```

The Value inside TranslatedValue is filled with value for the current user's locale.
The TranslationList contains all of the transaltions for the locales.

This way, you can easily control which values you want to load,
and simple access both current locale and other locales:

```<code>MyBook.Title.Value // Gives the value for the current locale
MyBook.Title.Translations["french"].Value // Gives the value for the french locale
</code>```

Hope that this idea helps you.

Title: DDD models and localization?

Body:
I have used a complex properties for this kind of situation, with the following structure:

TranslatedValue
    Value
    TranslationList
        Translation1
            Locale
            Value
        Translation2
            Locale
            Value
        Translation3
            Locale
            Value
...

The Value inside TranslatedValue is filled with value for the current user's locale.
The TranslationList contains all of the transaltions for the locales.

This way, you can easily control which values you want to load,
and simple access both current locale and other locales:

MyBook.Title.Value // Gives the value for the current locale
MyBook.Title.Translations["french"].Value // Gives the value for the french locale

Hope that this idea helps you.


答:
Horrible macros is right, from http://www.artima.com/intv/modern2.html:

Bjarne Stroustrup: Yes. When you say, "template type T," that is really the old mathematical, "for all T." That's the way it's considered. My very first paper on "C with Classes" (that evolved into C++) from 1981 mentioned parameterized types. There, I got the problem right, but I got the solution totally wrong. I explained how you can parameterize types with macros, and boy that was lousy code.

You can see how an old macro version of a template was used here: http://www.xvt.com/sites/default/files/docs/Pwr++_Reference/rw/docs/html/toolsref/rwgvector.html


问:
Functional programming pattern for async JavaScript code
I have adopted a pattern in one of my projects that I really like and I suspect it's likely to be something standard.   I'd like to describe it here and see if you guys can tell me how other JavaScript programmers solve this type of problem.

A few rules I established for myself before I started the project.
1.  Functional / Lazy evaluation wherever possible.   Don't do a bunch of things at startup.
2.  Use promises (I happen to be using Angular's $q, but the syntax is all pretty much similar)

For the sake of simplicity, let's say that I am wanting to update the screen and display say at the top the user's name, how many Likes they have, and their current Friend count.  Some of this may seem contrived, but bare with me.

In my controller on the client side I would make simple calls to a client-side service that does something like:

```<code>   function getCurrentUserName() {
       getCurrentUser().then( function(user) {
           return user.name;
       }
   }

   function getCurrentUserLikeCount() {
       getCurrentUser().then( function(user) {
           return user.likeCount;
       }
   }

   function getCurrentUserFriendCount() {
       getCurrentUser().then( function(user) {
           return user.friendCount;
       }
   }
</code>```

Now I might have multiple UI elements that access the controller, and who knows what order the requests might come in at.   Heck, it's possible there might be a 3rd party widget that access the controller, so there might be multiple calls to one of these routines coming in quickly.

Now, the first obvious problem is that getCurrentUser() is async and does some kind of an ajax/rest call to the server.    So:
1) You don't need to make unnecessary calls to the server.  If getCurrentUser() got called already, you don't need to call it again (given some rationale such as the user is still logged in, etc.)

So let's assume getCurrentUser() is smart enough to cache the results.  On subsequent calls, it may return the cached value (still asynchronously using when()).

The second problem is, what happens when getCurrentUser() gets called while another call to getCurrentUser() is already processing.   The cache hasn't been updated yet, so the second call doesn't see the cache so it makes another HTTP call to the server.   You don't want that.   So you need to know that there's a pending request to the server and throttle the call.

So the pattern I adopted is that an async function that makes a call to the server follows the following high-level idea:
1.  If it's the first call, issue the call to the server, and immediately return a promise to the client.  Also, hang on to this promise.   When the server responds, resolve the promise but also keep the original value returned from the server (i.e. cache)

If it's not the first call, determine if the first call completed.  If the first called has already completed, return the value that was returned from the server (i.e. the cache).  Of course, you'd do this using when() since the client is expecting a promise.

If it's not the first call, but the first call has not yet completed, then return to the client the cached promise that was returned by the first call.   When then promise is resolved, all clients are notified.

In fact, what also works with the angular $q (and probably others), is to reuse the original promise even after it was returned in the past.  Then you can avoid caching the data as well since the promise contains the data returned from the server.

I call this whole thing throttling, for lack of a better term.

The following function wraps an existing async function and makes a new function that automatically throttles:

```<code>    // This routine makes a custom throttle wrapper for the async-function that's passed in.
    // A throttle function, when called, calls an async function (one that returns a promise)
    // in such a way to ensure the async function is only called when it's not already in progress.
    // in which case rather than calling it again, this routine returns the original promise to the caller.
    // If it's already in progress, then the original promise is returned instead.
    var makeThrottleFunction = function (asyncFunction) {
        var asyncPromise = null;
        return function (asyncInParam) {
            if (!asyncPromise) {
                var asyncDeferred = $q.defer();
                asyncPromise = asyncDeferred.promise;
                asyncFunction(asyncInParam).then(function (asyncOutParam) {
                    asyncDeferred.resolve(asyncOutParam);
                }).catch(function (parameters) {
                    return $q.reject(parameters);
                }).finally(function () {
                    asyncPromise = null;
                });
            }
            return asyncPromise;
        };
    };
</code>```

Example usage:

```<code>var getCurrentUser = makeThrottleFunction(function() {
    // async call to server to get data
    // return promise..
});
</code>```

I'm curious what the experts have to say about this approach.  What is an alternative, etc.   I used it all over the place in my app and it works really well.   I also don't think I could do without it, which begs the question: if something like this isn't already in the frameworks, then I may be missing something obvious, like some setting or library that already does this very exact thing.   So I'd love to get some feedback.

Although I'm looking for opinions from others on how they solve this common problem, in order to satisfy this being a Q&A, I think a good answer would be one of the following:
1.  Point to a library that does this type of thing.
2.  Points out that there's a simpler way to do this.

答:
I'm not aware of a published implementation of this technique, but it's a fairly standard way of using promises.  An interesting side effect of the composability, reusability, and extensibility of functional programming is that often you don't find things in libraries that you would expect.

In a less composable paradigm, you would need support in a library to do something like your throttle function, because you have to weave support for it throughout other functions.  In functional code, programmers just write it themselves once, then they can reuse it everywhere.

After you write something like this, who do you share it with, and how?  It's too small to be its own library.  It's a little too specific to not be considered bloat in a promise library.  Perhaps some sort of promise utilities library, but then it would be in a not very cohesive module with other functions vaguely related to promises, which makes it hard to find.

What happens to me a lot is I search for 10 minutes or so, then just write it myself because it would only take me a half hour.  I put it in a "utilities" file I keep around with other odds and ends functions that are short but highly reusable, but don't really fit anywhere.  Then six months later I happen upon it by chance in a community-maintained library with some weird name.

My point is, with functional programming, not being able to find an existing implementation for something that feels fairly "standard" is not a sign that other people are either doing it in a superior way, or that you're the first to come up with it.  It's just a symptom of the difficulty of sharing short, reusable code in a way that's easy to discover by a search.


答:
Besides the void * pointer which is covered in Robert's answer, a technique like this was used (Disclaimer: 20 year old memory):

```<code>#define WANTIMP

#define TYPE int
#include "collection.h"
#undef TYPE

#define TYPE string
#include "collection.h"
#undef TYPE

int main() {
    Collection_int lstInt;
    Collection_string lstString;
}
</code>```

Where I have forgotten the exact preprocessor magic inside collection.h, but it was something like this:

```<code>class Collection_ ## TYPE {
public:
 Collection_ ## TYPE () {}
 void Add(TYPE value);
private:
 TYPE *list;
 size_t n;
 size_t a;
}

#ifdef WANTIMP
void Collection_ ## TYPE ::Add(TYPE value)
#endif
</code>```

Body:
Besides the void * pointer which is covered in Robert's answer, a technique like this was used (Disclaimer: 20 year old memory):

#define WANTIMP

#define TYPE int
#include "collection.h"
#undef TYPE

#define TYPE string
#include "collection.h"
#undef TYPE

int main() {
    Collection_int lstInt;
    Collection_string lstString;
}

Where I have forgotten the exact preprocessor magic inside collection.h, but it was something like this:

class Collection_ ## TYPE {
public:
 Collection_ ## TYPE () {}
 void Add(TYPE value);
private:
 TYPE *list;
 size_t n;
 size_t a;
}

#ifdef WANTIMP
void Collection_ ## TYPE ::Add(TYPE value)
#endif

ContentLicense: CC BY-SA 4.0