问:
Store generated image in database or generate it on server/client
I have been thinking what could be the fastest way to show base64/img data to the user, i could generate the data when the user is registered and then store it to database, or generate it every time it is requested.

this is something i am thinking to make the response fast and i could just generate the img data in client. which many elements will have them generated, but i don't know if this could make the loading data take longer time.

So, is it better to store base64/img generated data on database?.. if not then who should generate them.. client or server?

update: To be more clear on the question, the generated data is Identicon, my concern is what would be the fastest way to show it to user, this could be shown once or multiple times in a single view regardless the power on server

答:
I would say the easiest way is to store it physically : you don't need any kind of handler or database call to retrieve the image, further managing will most probably be easier aswell as client-cache handling.

There's actually not a lot of good reasons to clutter your database with images, so I would say this alternative is only just acceptable in some specific cases like needing this image distributed among several servers. And even then, you could think about something like a CDN to share physically stored images accross multiple servers.

In some cases, you could also think about BASE64 encoded images in the CSS file, which may open the doors to responsiveness and have an impact on loading time by reducing the number of requests, with an impact on CSS file size though.

So, long story short: unless very specific requirements, the best is to store it in a (distributed) filesystem.


答:
Nosthertus, please clarify your question more. I'll answer based on what I can understand now but will change/update it once you clarify.

If you generate once and read many times, then storing is a good idea.

Storing directly in the database is a bit more programming but has the benefits of putting everything in logically a single view that any app can use. Storing in a filesystem is not advisable because you don't get some of the DB beneits (depending on your choice of database platform) like transaction handling etc.

However what little I know about identicons is that depending upon what you're doing, the identicon for any use could be different if they moved to another machine or IP address. So in that case you have to generate every time.

Your follow on question about "is it better to generate on client or server"... This is important in that can you safely guarantee that if generated on client or server, the resulting image will be identical? That depends on what algorith you're using.

So clarifications needed are.. instead of vague "let's assume", can you clearly state what you're trying to do?
What are you concerns? Performance or space usage?
How does this image get used in the UI?

ContentLicense: CC BY-SA 3.0

Title: Store generated image in database or generate it on server/client

Body:
I have been thinking what could be the fastest way to show base64/img data to the user, i could generate the data when the user is registered and then store it to database, or generate it every time it is requested.

this is something i am thinking to make the response fast and i could just generate the img data in client. which many elements will have them generated, but i don't know if this could make the loading data take longer time.

So, is it better to store base64/img generated data on database?.. if not then who should generate them.. client or server?

update: To be more clear on the question, the generated data is Identicon, my concern is what would be the fastest way to show it to user, this could be shown once or multiple times in a single view regardless the power on server


问:
What's the difference between a Factory method and Entity Translator

The entity translator provides a function that takes one or more data
  contract classes as parameters and returns a specific business entity.

Within the implementation of the function, a new instance of the
  business entity is created and initialized using data from the data
  contract classes.

After a new instance of the business entity has been initialized, it
  is returned to the application that made the request.

source: https://msdn.microsoft.com/en-us/library/ff699418.aspx

So this description sounds very similar to a Factory method.

Would it be safe to assume that the only difference between them is the type of parameters used to create the object?

答:
A Factory or Factory method is a way of creating objects without having the calling method be aware of the specific class of object that is being created or the dependencies it has. It takes away the complexity of instantiating objects for which (some of) the properties are not known at code-time but can only be known at run-time.

Your Entity Translator seems to deal with translating from data contracts to business entities. In that sense it will create objects, but that alone does not make it a Factory because a lot of OO code is mostly about creating objects. It really serves to isolate changes in the data contracts and the business from each other and centralize the logic that converts from a data contract to a business object. It removes coupling between the data contracts on one end and the application using the data contracts to create business objects and perform business logic on them on the other end.


问:
How to reduce a switch in a switch statement?
So I'm making a method to create a salutation line based on two people from a database.

There are four parameters: the two names (name1 and name2) and the two genders (gender and gender2).

For every gender combination, I have a kind of different output.

For example: if gender 1 is M (man) and gender 2 is also M, the output should be something like:

```<code>Dear Sir name1 and Sir name2,
</code>```

At this time, my switch looks like this:

switch(gender1){
    case 'M':
        switch(gender2){
            case 'M': printf("Dear Sir %s and Sir %s", name1, name2); break;
            case 'W': printf("Dear Sir %s and Madame %s", name1, name2); break;
            case 'R': ...
        }
        break;
    case 'W':
        switch(gender2){
            case 'M': printf("Dear Madame %s and Sir %s", name1, name2); break
            case 'W': printf("Dear Madame %s and Madame %s", name1, name2); break;
            case 'R': ...
        }
        break;
    case ...etc.
}
```

Note that I have multiple gender options, like 'R' for "Dear Relation" and some more that I do not have the time to translate.

How can I reduce this double switch statement?

Putting the second switch in a method is not an option because there is also a case where both of the names are the same and then the output should be combined like: "Dear Sir and Madame name1,"

答:
Add the title to the parameters of the printf:

char* title1;
switch(gender1){
    case 'M':
        title1 = "Sir";
        break;
    case 'W':
       title1 = "Madam";
        break;
    case ...etc.
}
char* title2;
switch(gender2){
    case 'M':
        title2 = "Sir";
        break;
    case 'W':
       title2 = "Madam";
        break;
    case ...etc.
}
printf("Dear %s %s and %s %s", title1, name1, title2, name2);
```

you can extract the switch to its own function for re-usability and compactness.

Body:
Add the title to the parameters of the printf:

char* title1;
switch(gender1){
    case 'M':
        title1 = "Sir";
        break;
    case 'W':
       title1 = "Madam";
        break;
    case ...etc.
}
char* title2;
switch(gender2){
    case 'M':
        title2 = "Sir";
        break;
    case 'W':
       title2 = "Madam";
        break;
    case ...etc.
}
printf("Dear %s %s and %s %s", title1, name1, title2, name2);

you can extract the switch to its own function for re-usability and compactness.


答:
If your language allows you to do it, you can write

```<code>switch(gender1+gender2) {
  case "MM":
    print "Dear Sirs";
    break;
  case "MF":
  case "FM":
    print "Dear Sir and Madam";
    break;
  ...
</code>```

It's not necessarily better than your version, since there's still duplication, but it does avoid the nested switch.

Title: How to reduce a switch in a switch statement?

Body:
So I'm making a method to create a salutation line based on two people from a database.

There are four parameters: the two names (name1 and name2) and the two genders (gender and gender2).

For every gender combination, I have a kind of different output.

For example: if gender 1 is M (man) and gender 2 is also M, the output should be something like:

```<code>Dear Sir name1 and Sir name2,
</code>```

At this time, my switch looks like this:

switch(gender1){
    case 'M':
        switch(gender2){
            case 'M': printf("Dear Sir %s and Sir %s", name1, name2); break;
            case 'W': printf("Dear Sir %s and Madame %s", name1, name2); break;
            case 'R': ...
        }
        break;
    case 'W':
        switch(gender2){
            case 'M': printf("Dear Madame %s and Sir %s", name1, name2); break
            case 'W': printf("Dear Madame %s and Madame %s", name1, name2); break;
            case 'R': ...
        }
        break;
    case ...etc.
}
```

Note that I have multiple gender options, like 'R' for "Dear Relation" and some more that I do not have the time to translate.

How can I reduce this double switch statement?

Putting the second switch in a method is not an option because there is also a case where both of the names are the same and then the output should be combined like: "Dear Sir and Madame name1,"

Body:
If your language allows you to do it, you can write

switch(gender1+gender2) {
  case "MM":
    print "Dear Sirs";
    break;
  case "MF":
  case "FM":
    print "Dear Sir and Madam";
    break;
  ...

It's not necessarily better than your version, since there's still duplication, but it does avoid the nested switch.


问:
How can I transition to a job using the Microsoft stack?
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?

答:
Its always difficult to make that switch after working on a specific technology for a few years. Your day job wouldn't let you focus on learning the new technology and you wouldn't get a job on it, not at least with a same pay scale as you don't have much experience on it.

Gladly, making a switch to MS technologies shouldn't be too difficult as there are plenty of good resources available to learn from and plenty of jobs available for it. But, you would have to work on small projects get some real knowledge, that is the best way to learn. Not that I know too much, but whatever I have learnt is due to the challenges I faced, working on the projects.

Other than working on a pet project yourself, you can probably try and hookup with a developer friend, who is already working on dotnet. Ask him to assign you small tasks to assist him with his work. You can also help him find solutions to the issues he gets stuck with. That way, you would learn about the features of the language and how and when to use them.

Reading books is another activity that you should do, but that should always be topped up with some hands on, no use otherwise.

I would also like to add, Certifications may look like a nice addon to your resume, but that does not really help you enhance your skills, and recruiters know that.

ContentLicense: CC BY-SA 2.5


问:
My coworker commits and pushes without testing
When my coworker thinks that there is no need for a test on his PC, he makes changes, commits and then pushes. Then he tests on the production server and realizes that he made a mistake. It happens once in a week. Now I see that he made 3 commits and and pushes with deployment to the production server within 5 minutes.

I told him few times that this is not the way how good work is done. I don't want to be rude to him again and he is in the same status with me in the company and he has worked more than me here.

I want this behavior to be punished in some way or make it unpleasant as much as possible.

Before I started, the company was deploying using antique methods, such as FTP, and there was no version control.

I forced them/us to use Git, Bitbucket, Dploy.io, and HipChat. The deployment is not automatic, someone has to login to dply.io and press the deploy button.

Now, how can I force them to not test on the production server? Something like HipChat bot can sense that there is repeated edits on the same line and send a notice to the programmer.

答:
I think you've identified a couple of problems:

It sounds like any code that gets checked can be trivially pushed to production by anyone who has the rights to check in code.

Frankly I think that setup is just insane.  At a minimum the people who can manually trigger a push to production should be restricted to the set of people who can be trusted completely to thoroughly review and test all outbound changes (regardless of who has authored the changes) before triggering the push.  Giving anyone with permission to check in code the power to also arbitrarily trigger a push to production is just asking for trouble.  Not just from careless and/or incompetent developers, but also from disgruntled ones or malicious third-parties who happen to compromise one of your accounts.

And if you're going to use a push-button process to deploy every change that gets checked in, then you need to have a comprehensive suite of automated tests in place, and pushing the button needs to run them (and abort the deployment if any tests fail!).  Your process should not allow code that hasn't even been superficially tested to reach the point where it's being deployed to the production system in the first place.

Your coworker has made a big mistake in terms of checking in code without testing it first.  Your organization has mad a much bigger mistake by adopting a deployment process that allows untested code to reach production under any circumstance.

So the first order of business is to fix the deployment process.  Either limit who can trigger a push to production, or incorporate a reasonable amount of testing into your automated deployment process, or both.

It sounds like you might not have set any clearly-defined development standards/principles.

In particular, it sounds like you're missing a clear "definition of done", and/or using one that does not include "the code has been tested" as a gating factor on checking code in/deploying code to production.  If you had this, instead of just pointing out that "good code isn't produced this way" you could say "this code isn't meeting the minimum standards that we've all agreed upon, and it needs to be better in the future".

You should try to establish a culture that clearly communicates what's expected of developers and the standards and level of quality they're meant to uphold.  Setting up a definition of done that includes at least manual testing (or preferably, automated testcases that can be run as part of the build/deploy process) will help with that.  As can having consequences for breaking the build.  Or more severe consequences for breaking the production system.  Note that those two things should really be independent, and it should be completely impossible to break both the build and the production system concurrently (because broken builds should not ever be deployable).


问:
How to use SOLID principles in this example
I have reading about SOLID principles last week and decided to try to solve real world problem by using them. So I got the problem of real world ecommerce site managing totals.

Problem Statement:
  We have to calculate some totals like subtotal, taxes, vouchers, coupon, total on a cart products.

So I have decided to make TotalManager which returns total_data and total to the rest of the program.

```<code>// total data variable looks like
array('key'=>value)
</code>```

e.g. array('subtotal'=>100,'total'=>150,'tax'=>50)

```<code>    class TotalManager{
        private $total_data;
        public function get_total_data()
        {
            $totals = array('subtotal','total','taxes')
            // foreach totals array gets each object check its instance of interface itotal and called it's get method.
        }
    }

    Interface Itotal
    {
        public function get_total_data();
        public function get_total();
    }

    class subtotal implements Itotal
    {
        public function get_total_data()
        {
            // it needs cart object
            // get the cart product calculate totals and return total_data and total
        }
        public function get_total()
        {
            return the subtotal in double/float
        }
    }

    class total implements Itotal
    {
        public function get_total_data()
        {
            // get the other totals object  and calls it get_total method
            // calulate sum of all totals and return
        }

        public function get_total()
        {
            // calculate total and return back;
        }
    }
</code>```

But I am facing problems in this model:

For dependency inversion principle I cannot directly create the object of cart or subtotal in subtotal, Total class respectively I have to pass them from controller at total manager.

When I think about that whenever I am adding the class I have to change the Total manager for adding the new method so it's violating open/closed principle. How to solve this in OOD?

答:
I see you use php, try to stick to the psr coding styles: psr-1 and psr-2.

Look into the decorator pattern. this is a pattern commonly used in this kind of situations.

You probably have some kind of LineItem class that is used to represent items in your cart. They probably look something like this:

```<code>interface LineItem
{
    public function getPrice();
}
</code>```

With then an implementation for your product:

```<code>class ProductLineItem implements LineItem
{
    public function __construct(Product $product, $quantity) {
        $this->product = $product;
        $this->quantity = $quantity;
    }

    public function getPrice()
    {
        return $this->quantity * $this->product->getPrice();
    }
}
</code>```

Now it is time to create our abstract decorator:

```<code>abstract class LineItemDecorator implements LineItem
{
    public function __construct(LineItem $item) {
        $this->item = $item;
    }

    public function getPrice()
    {
        return $this->item->getPrice(); //delegation
    }
}
</code>```

this abstract class is not needed. I just tend to use it to delegate everything to the base object only in one place. Especially useful if multiple methods exist.

Note also how my Decorator implements the same interface!

And then now it's time for our Discounts:

```<code>class DiscountLineITemDecorator extends LineItemDecorator
{
    public function getPrice()
    {
        return $this->item->getPrice() * 0.75;
    }
}
</code>```

We would then procede to use it:

```<code>$lineItem = new ProductLineItem($theProduct, 2);
$lineItemWithDiscount= new DiscountLineITemDecorator($lineItem);
//lets add it to our cart
$cart->addLineItem($lineItemWithDiscount);
</code>```

Our cart then probably also has a getPrice() method. Probably it will look something like this:

```<code>foreach ($this->lineITems as $lineItem) {
    $price += $lineItem->getPrice();
}
return $price;
</code>```

So what about discount on an entire cart?

```<code>$cartWithDiscount = new DiscountCartDecorator($cart);
</code>```

and boom

```<code>$cartWithDiscount->getPrice();
</code>```

All code used here serves as an example. The naming can be improved a lot, so feel free to edit!

Body:
I see you use php, try to stick to the psr coding styles: psr-1 and psr-2.

Look into the decorator pattern. this is a pattern commonly used in this kind of situations.

You probably have some kind of LineItem class that is used to represent items in your cart. They probably look something like this:

interface LineItem
{
    public function getPrice();
}

With then an implementation for your product:

class ProductLineItem implements LineItem
{
    public function __construct(Product $product, $quantity) {
        $this->product = $product;
        $this->quantity = $quantity;
    }

    public function getPrice()
    {
        return $this->quantity * $this->product->getPrice();
    }
}

Now it is time to create our abstract decorator:

abstract class LineItemDecorator implements LineItem
{
    public function __construct(LineItem $item) {
        $this->item = $item;
    }

    public function getPrice()
    {
        return $this->item->getPrice(); //delegation
    }
}

this abstract class is not needed. I just tend to use it to delegate everything to the base object only in one place. Especially useful if multiple methods exist.

Note also how my Decorator implements the same interface!

And then now it's time for our Discounts:

class DiscountLineITemDecorator extends LineItemDecorator
{
    public function getPrice()
    {
        return $this->item->getPrice() * 0.75;
    }
}

We would then procede to use it:

$lineItem = new ProductLineItem($theProduct, 2);
$lineItemWithDiscount= new DiscountLineITemDecorator($lineItem);
//lets add it to our cart
$cart->addLineItem($lineItemWithDiscount);

Our cart then probably also has a getPrice() method. Probably it will look something like this:

foreach ($this->lineITems as $lineItem) {
    $price += $lineItem->getPrice();
}
return $price;

So what about discount on an entire cart?

$cartWithDiscount = new DiscountCartDecorator($cart);

and boom

$cartWithDiscount->getPrice();

All code used here serves as an example. The naming can be improved a lot, so feel free to edit!


问:
Securing ajax calls to rest api
I need for my app to consume a rest api service and since I will call it from javascript/jquery i need to expose it to the end user.

In this case I would also need to expose credentials to the end user, which is something I would like to avoid. As an alternative I am thinking of using a token that would replace sensitive credentials, but what concerns me is how to prevent an end user to reuse or recall rest api service misuse that same token with different params?

Bottom line, how to successfully protect application so only application can consume rest api and not the end user himself?

EDIT

This question raised a couple of doubts so I would like to make myself clear.
For example:
Javascript from my app contains an ajax call that calls a third party api. For example http://domain.com/api/insert-item?user=username&password=password&userid=1000&itemid=55555&itemvalue=10

What stops any user to change query string to userid=2000&itemid=55555&itemvalue=100

What stops any user to get our credentials for third party api and consumes it without permission?

答:
You can't.

Let me rephrase:
Impossible

You could/should make it harder to use a token. Implementing a max-usage per token, a max life-time, ... It is however impossible to know if it is the scriptkiddie or your 'application' contacting your api.

A lot of people tend to forget that it is never the aplpication calling the api, it's the application, telling the client what api to call. Everything else is based on trust. And on the internet, trust is deprecated

Title: Securing ajax calls to rest api


答:
I think you should not directly access the Third Party API from your JavaScript application. Instead, you should implement your own basic web services which is like a wrapper around the Third Party API.

You can then implement your own authentication method inside your own small web service or do not implement it in case it is not needed.

However, you could hide these calls behind some hard coded pages like:

Example.php would be your own service
/example.php calls Third.Party/API/Example?Some=Complex&Strings=NoOne&Should=See

Title: Securing ajax calls to rest api

Body:
I need for my app to consume a rest api service and since I will call it from javascript/jquery i need to expose it to the end user.

In this case I would also need to expose credentials to the end user, which is something I would like to avoid. As an alternative I am thinking of using a token that would replace sensitive credentials, but what concerns me is how to prevent an end user to reuse or recall rest api service misuse that same token with different params?

Bottom line, how to successfully protect application so only application can consume rest api and not the end user himself?

EDIT

This question raised a couple of doubts so I would like to make myself clear.
For example:
Javascript from my app contains an ajax call that calls a third party api. For example http://domain.com/api/insert-item?user=username&password=password&userid=1000&itemid=55555&itemvalue=10

What stops any user to change query string to userid=2000&itemid=55555&itemvalue=100

What stops any user to get our credentials for third party api and consumes it without permission?


答:
... i could generate the data when the user is registered and then store it to database, or generate it every time it is requested.

This sounds like two completely different operations to me:

1) Generate [static] "image" data when the user registers and store it in a database.

2) Generate some dynamic "image" data whenever the user visits a page.

My question is this: Having loaded your "image" data into a database, what are you going to do with it?  If the answer is simply ...

```<code>Read it back, write it to a file and display it in the user's browser
</code>```

... then you're better off leaving the "image" in the file system, from where it can be served directly.

Even if you're adding some sort of dynamic content to the "image", then storing or, at least, cacheing it in the file system will still make for a quicker, operation overall.

Trying to do anything "client-side" is risky.  Even putting aside the vaguaries of browser implementations of JavaScript (at least until WASM https://en.wikipedia.org/wiki/WebAssembly takes off), you're totally reliant on the available processing power of the client machine to handle all that "image" processing you want to do.  That might be OK on somebody's shiny, new multi-GHz Uber-phone but on their clunky, old, 10-year-old laptop?  Perhaps not so much.

Body:
... i could generate the data when the user is registered and then store it to database, or generate it every time it is requested.

This sounds like two completely different operations to me:

1) Generate [static] "image" data when the user registers and store it in a database.

2) Generate some dynamic "image" data whenever the user visits a page.

My question is this: Having loaded your "image" data into a database, what are you going to do with it?  If the answer is simply ...

Read it back, write it to a file and display it in the user's browser

... then you're better off leaving the "image" in the file system, from where it can be served directly.

Even if you're adding some sort of dynamic content to the "image", then storing or, at least, cacheing it in the file system will still make for a quicker, operation overall.

Trying to do anything "client-side" is risky.  Even putting aside the vaguaries of browser implementations of JavaScript (at least until WASM https://en.wikipedia.org/wiki/WebAssembly takes off), you're totally reliant on the available processing power of the client machine to handle all that "image" processing you want to do.  That might be OK on somebody's shiny, new multi-GHz Uber-phone but on their clunky, old, 10-year-old laptop?  Perhaps not so much.


问:
Are SMART goals useful for programmers?
Several organisations I know use SMART goals for their programmers. SMART is an acronym for Specific, Measurable, Achievable, Relevant and Time-Bound. They are fairly common in large corporations.

My own prior experience with SMART goals has not been all that positive. Have other programmers found them an effective way to measure performance? What are some examples of good SMART goals for programmers (if they exist).

答:
Yes, if set correctly.

If set correctly, the objectives can improve both the team and the individual people. They should be aligned to the job too and designed for the individual.

I've been in places where a whole DBA team has the same bland objectives, as well as high level hand me downs such as "conform to global and regional KPIs as determined by the the KPI committee". Which no-one knows of course..

Then again, I've been at places where the manager sets individual objectives with thought up front.

Edit:

I've read the Mary Poppendieck article and it isn't about SMART. "The Perception of Impossibility" fails "Achievable" for example.

Objectives should be set for the individual, to share their strenghts, help rectify weaknesses, contribute to the team. Measurement is for the individual.

There should be no comparison of x vs y.

The objectives for x and y should be commensurate with their rank or position inside a system though: one does not set the same objectives for seniors and juniors. That's unfair.

Some benchmark is needed to set bonus or payrises from a limited pot: should we count lines of code instead? Peer reviews?

And show me valid alternatives that won't require me to change my global corporate ethos. I have no criticism of SMART: I do have criticisms of piss poor managers...

Title: Are SMART goals useful for programmers?


答:
Radical solution: Let the user specify their own title (from a predefined list that you provide).

Your solution (as viewed through English eyes) only appears to cater for Lords ("Sir") and ladies; most men would be addressed as "Mr", most women as either "Miss", "Mrs" or "Ms", depending on their marital status and personal opinions.  Then there's a whole slew of other honorifics based on professional standings -  "Doctors", "Professors", "Reverends" and even, if you're feeling really optimistic about your site, "Holiness"!

Simpler solution: You need a [single] function to translate "gender" into an honorific.  Code it once and call it for both people:

```<code>printf("Dear %s %s and %s %s"
   , getTitle( gender1 ), name1
   , getTitle( gender2 ), name2
   ) ;
</code>```

Body:
Radical solution: Let the user specify their own title (from a predefined list that you provide).

Your solution (as viewed through English eyes) only appears to cater for Lords ("Sir") and ladies; most men would be addressed as "Mr", most women as either "Miss", "Mrs" or "Ms", depending on their marital status and personal opinions.  Then there's a whole slew of other honorifics based on professional standings -  "Doctors", "Professors", "Reverends" and even, if you're feeling really optimistic about your site, "Holiness"!

Simpler solution: You need a [single] function to translate "gender" into an honorific.  Code it once and call it for both people:

printf("Dear %s %s and %s %s"
   , getTitle( gender1 ), name1
   , getTitle( gender2 ), name2
   ) ;


问:
How to manage ongoing data migrations?
I work in a SaaS project in which each user can have a representation of some common data at a given point in time. For the sake of example, let's consider that each user's data is metadata about them persisted separately on disk as a JSON file:

```<code>{
  "name" : "Bob"
}
</code>```

As new requirements come along, this underlying representation may change (for example, in the above JSON, let's say that name attribute is changed to firstName and another attribute lastName is added). In order to support artifacts that were created at different points in time, we are forced to handle this in one of two ways:

Migrate all data from old representation to new

Follow different code paths/conditional logic depending on underlying representation:

.

```<code>if (oldRepresentation) {
  ... do this ...
} else if (middleRepresentation) {
  ... do that ...
} else {
  ... do something else ...
}
</code>```

Both seem problematic in that one is a big bang approach (and we all know that migrations are rarely smooth) and the other creates some amount of dissonance in the source with all the conditional logic. I'm curious how other projects handle migrations of this sort? Do most of you use one of the above approaches? How does your architecture account for this? Do you have a separate service to do migrations on demand?

答:
Converting your data files from the "old" formats to your latest and greatest one is probably the best option.  Save the reformatted data after converting it.  That way, you're data gets upgraded gradually, over time, instead of a "Big Bang".  Every time a file is accessed, it gets upgraded to the latest version (whichever that is today) and nobody's any the wiser.  It's a bit like Oracle Database; it only checks for block corruption as it reads a block in from disk.

One possible problem is if you have to back out an application release.  You then have to be able to "downgrade" your files to the previous version, which could be something of a challenge.

Title: How to manage ongoing data migrations?


答:
The best way is to store a version number in each of the persisted files. Then you can read any of them, from any time and if the version is not the current one - send it to a migration routine that updates it to the current format and then continue processing it as if it was always the current format.

This allows you to perform the migration on an as-needed basis, rather than a lengthy conversion-of-all-records process. It also allows you to maintain records in offline or disconnected models. Your codebase is significantly simpler as it only had to manage the current format, though you will have to continually append rules to a migration routine as you add new formats.

To make this work, you MUST store a version. Trying to guess that format the file is after 2 or 3 revisions to the format will not be fun. If you current do not store the version number, that's fine - all files without one are simply v0 by default. Migration should add one.

Title: How to manage ongoing data migrations?

Body:
I work in a SaaS project in which each user can have a representation of some common data at a given point in time. For the sake of example, let's consider that each user's data is metadata about them persisted separately on disk as a JSON file:

```<code>{
  "name" : "Bob"
}
</code>```

As new requirements come along, this underlying representation may change (for example, in the above JSON, let's say that name attribute is changed to firstName and another attribute lastName is added). In order to support artifacts that were created at different points in time, we are forced to handle this in one of two ways:

Migrate all data from old representation to new

Follow different code paths/conditional logic depending on underlying representation:

.

```<code>if (oldRepresentation) {
  ... do this ...
} else if (middleRepresentation) {
  ... do that ...
} else {
  ... do something else ...
}
</code>```

Both seem problematic in that one is a big bang approach (and we all know that migrations are rarely smooth) and the other creates some amount of dissonance in the source with all the conditional logic. I'm curious how other projects handle migrations of this sort? Do most of you use one of the above approaches? How does your architecture account for this? Do you have a separate service to do migrations on demand?


问:
Built-in the separate thread execution inside of the method or wrap the method by the thread
Let assume, I have some resource and time-consuming code, which I want to arrange as a separate method. In order to optimize the performance, this code should be executed in the separate thread.

Now the question, where to define this thread:

Inside (built-in) of this «heavy» method;

Or to wrap the execution of this «heavy» class's code by the thread.

In other words, from the design and the best practice point of view, should I built-in the separate thread execution or it is better to write this code without threads and if there is a need to execute this code in the separate thread, the developer will wrap it by the separate thread?

Update:

The main reason I ask this question is that I want to provide a turnkey solution, which can used as a plug-and-play black box, and not to worry if the end-user will forget to execute this code in the separate thread.

答:
Separate your concerns. Complicated business logic should never be intermingled with scheduling logic that is also complex.
Therefore, implement whatever smart solution you want, but wrap it into a well-named method and then schedule that.


问:
Are case-studies an effective way of getting efficiency-focused team members to be willing to trade some efficiency for quality?

Firstly, this does not suggest that efficiency and quality are in conflict... only that some methods prioritize them differently.

Secondly, this is not a question of whether you agree with Scrum practice or not.

An expressed goal of Scrum is to create high quality increments of a deliverable product. This does not exclude that it might be done efficiently, but efficiency is not the focus.

Most programmers want to both deliver quality products and be efficient about it. Scrum's requirement to add product backlog items to a sprint backlog from the top of the prioritized list only... will often result in resistance from programmers, such as:

"But it will be more efficient if we add these other two items, from further down the priority list, to this sprint".

Perhaps the prioritization of the product backlog items could have been influenced differently by the Scrum Master, while working with the Product Owner. Such could be addressed in the next product backlog refinement session.

Setting aside such issues, are case-studies (of other teams' effective uses of Scrum) an effective way of swaying reluctant team members? (particularly on the issue of efficiency) Or, is there something better than case-studies?

答:
Setting aside such issues, are case-studies (of other teams' effective uses of Scrum) an effective way of swaying reluctant team members? (particularly on the issue of efficiency) Or, is there something better than case-studies?

Case studies really are a poor substitute to general experience and even if people read them, it likely won't make any big difference.

Your problem is one of ulterior goals.  A Scrum team is forward thinking only in terms of getting items into the backlog that need to be worked on.  They are also forward thinking in "Sprint Zero" mode where they are planning the project overall, high level design and environment buildouts.  That is it.

Everything else should be a short term goal for the scrum team, completing the next sprint to product owner acceptance.

If your team members are thinking about later rework then they are right to bring it up as a concern during Sprint Planning, but the decision to bring it into the sprint rests solely on the Product Owner.  Rework is only a concern when the Product Owner considers it to be a problem but he/she should be aware of the technical implications of what she is committing the team to.

So how should you convince the team?

You need to get everybody on the team aligned with the same goal in mind.  Report potential technical issues and risks, and spike when you don't have enough information, but ultimately, when you commit to a story your feelings should be left at the door and you should do it regardless of the down stream impacts.  The team just needs to be clear about how much effort will be expended to do this and if it is realistic in terms of the allocated sprint time.

If developers are concerned about having to write a bunch of code that will be thrown away later then they are not aligned.

The goal is quickly delivering business value NOW, not preventing future rework.  It is not about them and their worries about refactoring and future workload, get them to abandon these goals by stressing the importance of Minimum Viable Product and quickly delivering business value.


答:
I need for my app to consume a rest api service and since I will call it from javascript/jquery i need to expose it to the end user

That's your first mistake.  As Pinoniq pointed out in his answer, it's not possible to secure client side code.

However, you can add your own server to the mix.  Have your client side code use JavaScript / jQuery to make a call to your server, then have your server make the call to the 3rd party API.

It's not that hard1 to make your server secure. You can protect the credentials to the 3rd party API and servers are cheap these days - GoDaddy, Amazon, etc. will happily rent you what you need.

I see you edited your question.  The answer remains the same - you cannot prevent the user from seeing or manipulating any data you send to the browser.

The fix is to change your JavaScript to something like

```<code>http://myserver.com/insert-item?parameters
</code>```

Then, have your server make the necessary call to the 3rd party API.

1 "not that hard"... of course depends on how secure you need to be.  For most people, it's not a big deal.

Title: Securing ajax calls to rest api

Body:
I need for my app to consume a rest api service and since I will call it from javascript/jquery i need to expose it to the end user

That's your first mistake.  As Pinoniq pointed out in his answer, it's not possible to secure client side code.

However, you can add your own server to the mix.  Have your client side code use JavaScript / jQuery to make a call to your server, then have your server make the call to the 3rd party API.

It's not that hard1 to make your server secure. You can protect the credentials to the 3rd party API and servers are cheap these days - GoDaddy, Amazon, etc. will happily rent you what you need.

I see you edited your question.  The answer remains the same - you cannot prevent the user from seeing or manipulating any data you send to the browser.

The fix is to change your JavaScript to something like

http://myserver.com/insert-item?parameters

Then, have your server make the necessary call to the 3rd party API.

1 "not that hard"... of course depends on how secure you need to be.  For most people, it's not a big deal.


答: If your implementation of the heavy logic is an ordenary, thread-free method it is much easier to write testcode (unit/integration-Tests) for it and to debug it. Writing junit-tests for threads is a nightmare.</p>

Title: Built-in the separate thread execution inside of the method or wrap the method by the thread

Body:
Let assume, I have some resource and time-consuming code, which I want to arrange as a separate method. In order to optimize the performance, this code should be executed in the separate thread.

Now the question, where to define this thread:

Inside (built-in) of this «heavy» method;

Or to wrap the execution of this «heavy» class's code by the thread.

In other words, from the design and the best practice point of view, should I built-in the separate thread execution or it is better to write this code without threads and if there is a need to execute this code in the separate thread, the developer will wrap it by the separate thread?

Update:

The main reason I ask this question is that I want to provide a turnkey solution, which can used as a plug-and-play black box, and not to worry if the end-user will forget to execute this code in the separate thread.


问:
Python object oriented programming problems while implementing binary search tree
I am shifting from procedural C programming to OOP Python programming and I faced some problems while implementing binary search trees.

I cannot make my Tree_Node null in case of deleting it. In C I could do this because I would handle the case in the function as follows:

```<code>    void insert(Node tree, int key)
    {
      if (tree == null)
      {
        // deal with it
      }
    }
</code>```

But in python using OOP I cannot make my Tree_Node null as it is a class and it contains all my methods.

```<code>class Tree:
  # Tree methods

t = Tree()
t = None  # Cannot do this as then how would I call its methods
</code>```

Q1) How do you solve this problem in general? (not just for binary search trees)
What is the standard OOP practice for this?

Second problem is that I cannot modify self in Python.
In C I could do as follows:

```<code>void foo(Node tree, int key)
{
  tree = tree->left
}
</code>```

But in python's class I cannot do as follows:

```<code>class Tree:
  def foo(self, key):
    self = self.left  # Cannot do this
</code>```

Q2) So how do I solve such problems? Any standard OOP practice?

Q3) A meta question. I thought OOP makes programming easier. But in this case, I find it much tough to implement a rather simple data structure. It adds restrictions such as not able to modify self, not able to make it null etc. Am I doing something wrong?

答:
The OOP way is to combine together polymorphism and recursion. A binary tree is defined as either empty or a set of value, left and right where both left and right are binary trees. To represent it properly left and right must be binary tree themselves, even if they are empty.

To represent that in object oriented way, we'll have a tree base class and node and empty subclasses. These subclasses will contain method implementations that access the fields directly, and the base class can contain methods that use these methods:

```<code>from abc import ABCMeta, abstractmethod

class Tree(metaclass=ABCMeta):
    @abstractmethod
    def infix(self):
        pass

    def set(self):
        return set(self.infix())

class EmptyTree(Tree):
    def infix(self):
        yield from ()

class TreeNode(Tree):
    def __init__(self, value, left=EmptyTree(), right=EmptyTree()):
        self.value = value
        self.left = left
        self.right = right

    def depth(self):
        return 1 + max(self.left.depth(), self.right.depth())

    def infix(self):
        yield from self.left.infix()
        yield self.value
        yield from self.right.infix()

tree = TreeNode(1, TreeNode(2), TreeNode(3, EmptyTree(), TreeNode(4)))

assert list(tree.infix()) == [2, 1, 3, 4]

assert tree.set() == {1, 2, 3, 4}

assert list(EmptyTree().infix()) == []

assert EmptyTree().set() == set()
</code>```

The infix method is in the subclasses, because it behaves differently for EmptyTree and for TreeNode. The set method is defined in the base class, because it only relies on the infix method that is defined for all trees.

The idea is that you don't check yourself if a tree is empty - you simply invoke it's methods, which may differ based on whether the tree is empty(instance of EmptyTree) or not(instance of TreeNode).

Body:
The OOP way is to combine together polymorphism and recursion. A binary tree is defined as either empty or a set of value, left and right where both left and right are binary trees. To represent it properly left and right must be binary tree themselves, even if they are empty.

To represent that in object oriented way, we'll have a tree base class and node and empty subclasses. These subclasses will contain method implementations that access the fields directly, and the base class can contain methods that use these methods:

from abc import ABCMeta, abstractmethod

class Tree(metaclass=ABCMeta):
    @abstractmethod
    def infix(self):
        pass

    def set(self):
        return set(self.infix())

class EmptyTree(Tree):
    def infix(self):
        yield from ()

class TreeNode(Tree):
    def __init__(self, value, left=EmptyTree(), right=EmptyTree()):
        self.value = value
        self.left = left
        self.right = right

    def depth(self):
        return 1 + max(self.left.depth(), self.right.depth())

    def infix(self):
        yield from self.left.infix()
        yield self.value
        yield from self.right.infix()

tree = TreeNode(1, TreeNode(2), TreeNode(3, EmptyTree(), TreeNode(4)))

assert list(tree.infix()) == [2, 1, 3, 4]

assert tree.set() == {1, 2, 3, 4}

assert list(EmptyTree().infix()) == []

assert EmptyTree().set() == set()

The infix method is in the subclasses, because it behaves differently for EmptyTree and for TreeNode. The set method is defined in the base class, because it only relies on the infix method that is defined for all trees.

The idea is that you don't check yourself if a tree is empty - you simply invoke it's methods, which may differ based on whether the tree is empty(instance of EmptyTree) or not(instance of TreeNode).


问:
Multi-threaded winforms with multiple child forms using sockets
I develop application with two main option grouped by groupBox in main form. First option is run server with specific behaviour for example I choose TCP protocol, type IP address, port number and atfter that I click run button which generate independent forms with this specific server. Second option is client which is analogous to first option. Client and server can send/receive information to via sockets.

My question is what is proper way to build this application? I try to put every server and client to independent thread  but I wonder is it a good solution because I find similar question where there is no multithread answer.

答:
Edit: I see that the post is old, however I'll toss the answer up anyways.

In my humble opinion, I think the proper way would be to design this in three pieces.

Server.cs - the logic that behind the server

Client.cs - the logic that behind the client

Your UI.

You would only need two threads, one that the UI runs on which you don't have to worry about and one that either the Server or Client runs on (which you do have to worry about). You have two ways to handle the multi-threaded work. Either on the UI (checking for cross-thread business, invoking, etc) or in the class it self. I personally prefer the latter.

Food for thought:

I personally like to trigger events which the UI can subscribe to and react accordingly. I tend to use AsyncOperation.Post() to handle the cross-threaded stuff.
Look into this: https://msdn.microsoft.com/en-us/library/system.componentmodel.asyncoperation.post(v=vs.110).aspx


问:
Why is code sometimes called "listings"?
When reading Programmers at Work (by Susan Lammers), they often refer to code as "listings". Why is that?

答:
In old line oriented basic system there was an interpreter command LIST to show the programmcode

So LIST produces a source code LIST-ing


答:
As others said, w/ 1 year experience you should be able to find a new job that allows you to code in .Net. I also moved from PHP to ASP.Net/C#, but my path was different. After working in PHP for about a year, I did my Masters, interned in a company, programming primarily in .Net and then I am now working in .Net full time.

Else in case your company is a startup (or not a corporation as you say), why not persuade them to start/look for ASP.Net projects too? Of course, this depends upon the fact that there are people who are proficient in managing/working in .net projects or your company should be ready to hire people w/ .net experience for the new projects? This answer may sound unrealistic too...

Title: How can I transition to a job using the Microsoft stack?

Body:
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?


答:
ratchet freak's answer is quite a good idea if the sentences are all the same pattern, but with two insets, one each only dependent on gender1 respective gender2.

Phil W.'s answer is probably the most flexible answer as it allows explicit control over the greeting, though he's quite correct it's a radical change. You might not have the data in that form.

Kilian Foth's answer is probably the best for the question as asked, though he depends on switching on a string, which might not be possible or is likely more expensive at least.

A refinement on Kilian's answer is computing a single value from both inputs, and switching on that:

// Using a macro in C for readability. C++ would use a constexpr function
#define COMBINE(a, b) ((a<<CHAR_BIT)+b)

switch( COMBINE(gender1, gender2)) {
  case COMBINE('M', 'M'):
    print "Dear Sirs";
    break;
  case COMBINE('M', 'F'):
  case COMBINE('F', 'M'):
    print "Dear Sir and Madam";
    break;
  ...
#undef COMBINE
```

Of course, as you are getting all four inputs (2 names and 2 genders) from a database, adding another table and joining on that to get the proper salutation is probably more flexible and maybe easier than the above.

Body:
ratchet freak's answer is quite a good idea if the sentences are all the same pattern, but with two insets, one each only dependent on gender1 respective gender2.

Phil W.'s answer is probably the most flexible answer as it allows explicit control over the greeting, though he's quite correct it's a radical change. You might not have the data in that form.

Kilian Foth's answer is probably the best for the question as asked, though he depends on switching on a string, which might not be possible or is likely more expensive at least.

A refinement on Kilian's answer is computing a single value from both inputs, and switching on that:

// Using a macro in C for readability. C++ would use a constexpr function
#define COMBINE(a, b) ((a<<CHAR_BIT)+b)

switch( COMBINE(gender1, gender2)) {
  case COMBINE('M', 'M'):
    print "Dear Sirs";
    break;
  case COMBINE('M', 'F'):
  case COMBINE('F', 'M'):
    print "Dear Sir and Madam";
    break;
  ...
#undef COMBINE

Of course, as you are getting all four inputs (2 names and 2 genders) from a database, adding another table and joining on that to get the proper salutation is probably more flexible and maybe easier than the above.


答:
Titles really belong in the database, but you stated you have no control over this. You have not specified a language tag but the syntax is in the C family, so this will be pseudocode that is almost C++:

map<string, string> titles;
titles.emplace("M", "Sir");
titles.emplace("F", "Madam");

cout << "Dear " << titles[gender1] << " " << name1 << " and "
     << titles[gender2] << " " << name2 << endl;
```

The benefit to this is you bury the selection logic in a data structure rather than a code structure: this is similar to delegating to the database, and is more flexible. If you keep that map as a static constant somewhere, you can almost use it like a database: it becomes a single structure to update which can be used in many places in the code without needing to write more code.

Body:
Titles really belong in the database, but you stated you have no control over this. You have not specified a language tag but the syntax is in the C family, so this will be pseudocode that is almost C++:

map<string, string> titles;
titles.emplace("M", "Sir");
titles.emplace("F", "Madam");

cout << "Dear " << titles[gender1] << " " << name1 << " and "
     << titles[gender2] << " " << name2 << endl;

The benefit to this is you bury the selection logic in a data structure rather than a code structure: this is similar to delegating to the database, and is more flexible. If you keep that map as a static constant somewhere, you can almost use it like a database: it becomes a single structure to update which can be used in many places in the code without needing to write more code.


问:
Are Microsoft fonts like Impact safe to use in Open Source projects?
I made an open source project that requires the use of the Impact.ttf font from Microsoft. I looked around but couldn't find a definite license option for MIT projects.

Do Microsoft's fonts (like Impact.ttf) conflict with the MIT license? If yes, are there different open source licenses that can accept such fonts?

答:
About Impact.ttf

Based on your question, you can find information about Impact.ttf from Microsoft site itself. See Impact.ttf 2.3 and Impact.ttf 5.0. The font isn't a copy right with Microsoft either. It just tells you that following Microsoft products are using this font, and they would have contractually worked out the mutual license to it. The font is owned by Monotype.com which provides many such fonts and customization service. Also, you can find out that the same font is available for sale at $49 from fonts.com. So it is clear that it is definitely not a free for all font. There are numerous sites which allows for download - i think it is clearly piracy!

Now having said that, the reason why I wront this answer is to clarify two important things.

First: Nothing really conflicts any other license. So if you download & bundle Impact.ttf and distribute it, you are clearly violating copyright. Whether you distribute it like pirates or under MIT or other free license or under commercial or binary license.

Distributing anything for which you don't have license to distribute, let alone license to use it, is clear violation of copyright and it has nothing to do with license under which you distribute other parts of your own work

Second - BUT, if you distribute any thing where by you dont have to bundle Impact.ttf in your own distribution, and you can instruct users to download and link with your font, then clearly you are not distributing the font. End user who need to use it, need to pay and use Impact.ttf or they can be directly available in their system by the virtue of the fact that Windows Xp, Vista, 7 & 8 provides to all end users throught Microsoft's own license.

All you need to do is, do not bundle Impact.ttf in your distribution but rely on system dependency and in case it is not available in system there could be system's own fall back. Then it is perfectly legal for your software to utilize it on client's desktop.

Again, MIT license or any other license has nothing to do with license of the font!


问:
Scheme/Design Pattern for allowing a certain outside class to set properties
I came up with a solution (in PHP) to a problem and am wondering if it is a named Design Pattern, and if it is good practice.

I have a collection class and an item class. The collection class is the only one allowed to set the item class's protected data, besides the class itself.

I did that by giving the item class a method that takes the collection object as an argument. The item object then sets its data with the collection objects.

That way, we can say:

```<code>$item_coll = new collection();
$item_coll->load($criterion1, $criterion2);
</code>```

Because the collection implements IteratorAggregate, we can also do this:

```<code>foreach($item_coll as $item) {
  echo 'Item name is ' . $item->getName();
}
</code>```

Even after a collection is loaded, you can get a sub collection using the getBy($property,$value) method:

```<code>$sub_collection = $item_coll->getBy('color','green'); // new collection object with green items
</code>```

And now I have a collection of item objects with all their data set.
Here are the classes (with impertinent methods/properties not shown).

```<code>class item {
  protected $id; // id from database table
  protected $prop1; // properties also from database
  protected $prop2;

  public function setData(collection $coll, $id) {
    $data = $coll->getData($id);
    foreach($data as $key=>$value) {
      $this->$key = $value
    }
    return $this;
  }
  public function getId() {
    return $this->id;
  }
}

class collection implements IteratorAggregate { // interface for foreach access to $collection
    protected $data = array();
    protected $collection = array(); // contains `item` objects
    public function getData($id) {
      if(array_key_exists($id,$this->data) ) {
        return $this->data[$id];
      } else return array();
    }
    public function load(someClass $obj1, someClass2 $obj2) { // arguments not relevant here, they determine the contents of the collection
      // based on arguments, data is loaded from database into $this->data;
      foreach($rows as $row) { // database data
        $this->data[$id] = $row;
        $obj = $this->collection[$id] = new item();
        $obj->setData($this,$id); // collection object passes itself into item object
      }
    }
    public function html() {//
      foreach($this as $obj) {
        // loop through collection to create an html table for display
      }
    }
    public function addItem(item $item) { // add already-existing items to collection
      if(!array_key_exists($id,$this->collection) ) {
        $this->collection[$item->getId()] = $item;
      }
    }
    public function getIterator() { // for IteratorAggregate interface
      return new ArrayIterator($this->collection);
    }
    public function getBy($property,$value) {
      $collection = new static(); // new collection created
      // loop through $this object and fill $collection with matching item objects
      return $collection;
    }
    public function getById($id) { // get a single item object by its id
      if(array_key_exists($id,$this->collection) ) {
        return $this->collection[$id];
      }
    }
}
</code>```

答:
The pattern you are referring to is called Dependency Injection

Basically, in most cases, the application calls the library/object for the information it needs, but in some cases, the object needs to first get configured what should it serve the application with. But if a generic object assumes or gets it from a hard-coded location (say config file etc.) then it is not re-usable in context of other application. Hence, the library object is dependent back on Application to provide this information. Creating API in a library/object where by Application feeds the information back is called Dependency Injection.

There are three main ways to exercise dependency injection:

Constructor method: Where parameters are supplied at the time of calling the constructor.

Setter method: where standard get/set method does the job.

Interface method: where a dedicated method is used by application to pass the information.

The -load() method is essentially the example of interface method which is capable of supplying multiple values and complex objects in one go.

Read this article of Martin Fowler which will give you a great perspective on this subject.


问:
CQRS: Query write model
Context: User wants to edit entity details, say user name.

Assuming the fact that the Read Model is eventually consistent with the Write Model is it conceptually wrong to query write model in order to get the most recent state of  an entity for the page?

If I choose to query the Read Model (typical implementation according to CQRS Journey Book) how can I deal with optimistic concurrency?

Thank you in advance!

答: Read model will not be affected by optimistic concurrency because it is read-only and will get returned to you in whichever state it is at the moment of request. The only thing you have to worry about is making changes to the same write model simultaneously.

Title: CQRS: Query write model


答:
I would say that the command interface isn't supposed support queries, and the write model should not necessarily be exposed to client applications for that purpose.

However, the notion you're looking for in the first question:

is it conceptually wrong to query write model in order to get the most recent state of an entity for the page?

seems to be "read your own writes", which can be very important to some applications.  I suppose one could provide a buffer that remembers one's own session writes.  However, what I do is a bit different.

I return a timestamp (or some other value that supports >= comparison) from the command interface, as well as the query interface.  The timestamps are forwarded from the write model to the read model along with other (changed) content.

Then when necessary to read my own writes, my client queries asking for data of interest as of >= the timestamp returned by the last command it issued.  This way I know the query is reporting content as of the client's latest change.

I don't understand the follow up question:

If I choose to query the Read Model (typical implementation according to CQRS Journey Book) how can I deal with optimistic concurrency?

As @Alexus says, the read model is read only so doesn't have to worry about multiple writers.  However it is not totally read-only as it must be repeatedly updated somehow from the write model.  The optimistic concurrency should be handled internally by the normalized write model SQL store and also by the denormalized read model SQL store.  (If you're using a non-SQL store for the denormalized read model, you should be aware that there is a difference between responding to read model queries with stale values on the way to eventual consistency and responding with inconsistently mixed values on the way to eventual consistency.)

Update:

Sorry for the confusion on my part.  The term optimistic concurrency is overloaded...  This term normally (in my mind) refers to a kind of transaction overlap capability found in the internals of the database.  However, CQRS uses this term to refer to a similar capability between client application and command server (and query server).  You provide the timestamp (as I described above) also with commands, in a form that asks the command to fail/abort if the timestamp is old.  Note that it is recommended that each aggregate have its own timestamp for fine granularity, so we're talking about using the logic I described above for each aggregate.

So this creates a full cycle or loop regarding the timestamps/version numbers.  When your client application does its first query, it omits the timestamp, though it receives timestamps back; when it does a command that is (most likely) based on the query information it has at present, it passes in the query timestamps with a flag to abort on timestamp old.  When the command completes, it provides a timestamp that the next query can use to see if the last command's results are in the read model yet (or to wait until so).  The query returns new timestamps, and the next command is based on those latest timestamps (with abort if old set), and so on.  (Sometimes, if the UI knows it hasn't refreshed in a while it may premptively do so.)

I think you could start with a single global timestamp/version number for the whole system; get that working, and later make the timestamp more granular (e.g. per aggregate instance) for better concurrency.  As @JDT is answering, this is complicated stuff already, and more so if you take it all the way to replicas of command processors for the same aggregate.

Title: CQRS: Query write model

Body:
Context: User wants to edit entity details, say user name.

Assuming the fact that the Read Model is eventually consistent with the Write Model is it conceptually wrong to query write model in order to get the most recent state of  an entity for the page?

If I choose to query the Read Model (typical implementation according to CQRS Journey Book) how can I deal with optimistic concurrency?

Thank you in advance!


问:
Should my application's README be for developers or users
My application is meant to be used by regular everyday users, but may also me modified freely by developers. These two audiences (users and developers) require different information.

Should my README be targeted towards users or is it more proper to target the README towards developers?

答:
"Developer" inherits from "user". If it's good for users, it will probably be good for developers. True, users don't often read documentation. But if you have 100 users to each developer and even 1% of users read READMEs and, say, 50% of developers read them, you'll still have twice as many users looking at the README than developers. So cater for both.

Both non-developer users and developers will want to know two things to begin with:

What does it do?

How do I get started?

At that point, they're going to have more questions like

How do I make it do the thing I want it to do?

What does this thing do?

But the answers they are expecting may be very different (they may be hoping for answers to questions like "which button do I press?" vs "which source file do I need to edit?"). That's when you break it out into different documents. Point to the tutorials for everyone first, and then link to the developer documentation.


问:
Version control practice for Rewrites
We developed a product (prototype) P_OLD in language X and we are now rewriting it from scratch as P_NEW in language Y.

Since P_NEW and P_OLD are the same product:

Should P_NEW just be a brach of P_OLD old or should it be its own repository?

What is the usual way to handle such big changes form a version control perspective?

答:
I always put rewrites in new repositories myself. That way the builds, tests, and deployments can all be done independently.

When you're rewriting a project in another language there's often very little similarity in any of those tasks like building, running tests, and deploying. You'll save yourself pain if you just isolate them in their own repository. Then you'll only need to worry about the pain of how you're going to manage the user and data transition from the old system to the new; that's always a fun thing. :)

Title: Version control practice for Rewrites


问:
How did JavaScript become popular?
In ancient history, Brendan Eich had a language design, and in today's world, JavaScript is a popular language implemented and used in many different places.

What caused the language to become popular? Was it the C-like syntax familiar to previous programmers? Did Netscape have enough control of the market to force it to be used? Or is there some deeper reason that JavaScript is popular and other languages are not?

Particularly, if you had to make a language as popular as JavaScript, what initial conditions would you need to recreate its growth in popularity?

答:
I was commenting on an earlier answer, but it was getting big, so I thought I'd spin this out.

Any new language can only succeed if it capitalizes on an emerging frontier in computing.

Previous examples:

C for Unix

Objective-C for iOS

Perl and PHP for back-end Web 1.0

Python and Ruby for back-end Web 2.0

Java for the back-end Internet-enabled enterprise

To answer your question, JavaScript was the language for Netscape Navigator back when that was the dominant browser. Specifically, it was the language for dynamic front-end development.

The next big language will have to solve another frontier. There still seems to be a land grab in the back-end web development space. Plus, mobile computing isn't totally solved, despite Apple's current dominance. Also, there's the emergence of multi-core and cloud computing, which is something that many languages are attempting to capitalize on (like concurrent languages like Erlang and Go, or functional languages like Haskell and OCaml).

Entrepreneurs have an expression along the lines of, "find a someone on fire and sell him a fire hose". So if you want to introduce a new language, whose fire are you putting out? Every new frontier in computing brings a whole host of headaches; so supply some aspirin and you'll be golden.

Title: How did JavaScript become popular?


问:
Is there a name for this data structure pattern consisting of a list of dictionaries each with one entry, consisting of an object?
There is a data structure idiom that looks something like this:

```<code>[
  {
    obj_1_id:
      {
        key1: value1_1,
        key2: value2_1
      }
  },
  {
    obj_2_id:
      {
        key1: value1_2,
        key2: value2_2
      }
  }
]
</code>```

I've run into this a few times, and I have a number of issues with it. For instance, note that the objects do not actually have their IDs in the object, and that since they are in a list-of-dictionaries rather than a single dictionary, you can't even look them up by ID easily.

So my first question is whether there is a name for this idiom, and the follow-up would be pattern or anti-pattern? If pattern, why would you ever use it?

答:
It's neither a pattern nor an anti-pattern. There's no specific name for it. It is exactly what it appears to be and its quality is determined by the program using it.

Does it make sense? Not to me, not without context. Could the outer array be removed and the IDs moved into a single object? Maybe, depends on the program. Could the nested objects be flattened to include the ID and properties at the same depth? Maybe, depends on the program. Could you do both and have only a single object? See above.

If you're having trouble working with this data, then either hide it behind an interface or copy the data into a structure more suitable for your usage.


答:
You almost certainly want a new repository.

The purpose of the repository is:

to track history and changes so you can compare them easily

to manage branches and merges rather than just emailing patch files around and applying them to working directories manually

If you're totally rewriting a project from scratch then there is no point putting the rewrite in the same repository. You won't be able to apply patches written in the old language to your rewrite. Switching repos won't make the history in the old repo go away, andif you switch you won't have any weird interim stages where you have two languages kicking round in your repo.

The only reason I would even consider keeping the repository when changing languages would be if a) the languages are so similar that code can often be copy-pasted from one to the other without making any changes, or b) you have a project in which the majority of the functional content in version control is something like templates in a templating language you're retaining, and the language of the core which you're changing be translated line-for line into another language (and even then only if you know you're going to need to keep iterating the templates during the migration).

Title: Version control practice for Rewrites

Body:
We developed a product (prototype) P_OLD in language X and we are now rewriting it from scratch as P_NEW in language Y.

Since P_NEW and P_OLD are the same product:

Should P_NEW just be a brach of P_OLD old or should it be its own repository?

What is the usual way to handle such big changes form a version control perspective?


答: The data structure that you're describing is often used in JSON documents where you have a list of objects, each with attributes (keys to dictionaries) and their values (the mapped portion of each dictionary). In the DS that you give, you can think of obj_1_id and obj_2_id as objects and key1 and key2 as those objects' fields. </p>

Title: Is there a name for this data structure pattern consisting of a list of dictionaries each with one entry, consisting of an object?

Body:
There is a data structure idiom that looks something like this:

```<code>[
  {
    obj_1_id:
      {
        key1: value1_1,
        key2: value2_1
      }
  },
  {
    obj_2_id:
      {
        key1: value1_2,
        key2: value2_2
      }
  }
]
</code>```

I've run into this a few times, and I have a number of issues with it. For instance, note that the objects do not actually have their IDs in the object, and that since they are in a list-of-dictionaries rather than a single dictionary, you can't even look them up by ID easily.

So my first question is whether there is a name for this idiom, and the follow-up would be pattern or anti-pattern? If pattern, why would you ever use it?


答:
No, the read model is for reading, the write model for writing

If you have a system that requires you to use CQRS (and it is something that you really should think long and hard about), you cannot use the write model to get the most recent data in the UI. You design your application in such a way that it can handle the delay between the write operation and the eventually consistent read model. If the delay is short (say, two seconds or less), you could work with a page that simply displays a message to the user about the changes having been saved, thereby simply preventing the user from seeing inconsistent data. Longer delays could mean 'faking' the data by persisting it in the session and displaying it from there, hiding fields that have been edited and are not yet consistent, and so on.

Doing 'pure' CQRS with a read and write model has very, very big implications on the way you write your application. Should really should consider if the application is big enough to warrant this approach as a lot of things you take for granted in regular applications become less obvious or outright difficult.

Title: CQRS: Query write model


问:
Hot-patching a server: dynamically loading types from an uploaded assembly
In the current project I'm working on, some of the C# classes are being stored as source code in SQL Server database records, and executed as needed using CSScript.  This is being done so that the server doesn't have to be taken down to replace the assembly in which these classes reside.

While this seemed like a good idea in principle, the costs of this scheme have exceeded the benefits on a number of levels, and I am now pursuing other possible remedies.

In the past, when I've needed this kind of "late binding," I've simply used Activator.CreateInstance() to instantiate and use the types I need.  I will typically hide this functionality behind a factory method which uses an XML configuration file to wire up the proper assemblies.

So in my perfect world, when I want to hot patch the server, I will copy the assembly to the server, edit the XML file to refer to the new assembly, and then the next time instances of those types are requested via the factory method, the server will automagically receive instances from the new assembly instead of the old one.

That said, I've never tried this with a running system.  I've always used it with a program that is not running, as a sort of poor-man's plugin system.  I am aware of things like MEF, but I don't know how MEF applies here, since I've never had to use it.

My question is a simple one: what am I missing?  Is this not as simple as I think it is?  Will this fail because I haven't unloaded the app domain that the original DLL from which the original type was loaded?  Will my algorithm suddenly become Skynet without warning?

In short, is there a better way?

答:
Depending on what you're trying to do, it's simpler.

IIS will automagically restart its app pool when it sees that a file has changed. If all you're looking to do is patch a running server, just push a new dll and let the app pool cycle.

Will this fail because I haven't unloaded the app domain that the original DLL from which the original type was loaded?

If your old DLL and your new DLL have the same version, I am pretty sure they will do very bad things. While I thought that types with the same fully qualified name but different versions would play nice - it looks as though that is not the case.

what am I missing?

One thing to be concerned with is that loading from configuration tends to be an expensive operation - one that is cached, either by your code or by some underlying API. Relying on the factory to see the new target is likely a quick and easy source of subtle bugs. There's also concurrency issues where your code may assume that consecutive calls to Factory.Create returns the same concrete type.

But in the end, it will boil down to Activator.CreateInstance.


问:
Is Haskell's type system an obstacle to understanding functional programming?
I'm studying Haskell for the purpose of understanding functional programming, with the expectation that I'll apply the insight that I gain in other languages (Groovy, Python, JavaScript mainly.)

I choose Haskell because I had the impression that it is very purely functional, and wouldn't allow for any reliance on state.

I did not choose to learn Haskell because I was interested in navigating an extremely rigid type system.

My question is this:  Is a strong type system a necessary by-product of an extremely pure functional language, or is this an unrelated design choice particular to Haskell?

答:
Being a "functional" language, means (apart from other things) that functions are first class objects in the language.

Being a "pure" language means that functions are mathematical functions (as opposed to procedures) -- given the same input, they always produce the same output.

A "pure functional language" is one where both the above hold. I am not aware of a "pure-ly functional language".

A strong type system is one clean way of having a pure yet practical language. The types help the compiler figure out optimisations, apart form further ensuring correctness. (But, that isn't the only way -- clojure is pure, but does not have as strong a type system as Haskell.)

If the type system is bothering you, I would suggest you to try a more dynamic language, like Scheme, or get around to using Haskell's type inference system.


问:
Why should a HashMap be used(in functions) to determine which value to return(for a key) when an if else construct can do the job in better time?
While I was recently working at a big company, I noticed that the programmers there followed this coding style:

Suppose I have a function that returns 12 if the input is A, 21 if the input is B, and 45 if the input is C.

So I can write the function signature as:

```<code>int foo(String s){
    if(s.equals("A"))      return 12;
    else if(s.equals("B")) return 21;
    else if(s.equals("C")) return 45;
    else throw new RuntimeException("Invalid input to function foo");
}
</code>```

But on code review I was asked to change the function to the following:

```<code>int foo(String s){
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("A", 12);
    map.put("B", 21);
    map.put("C", 45);
    return map.get(s);
}
</code>```

I can't convince myself on why the second code is better than the first. The second code would definitely take more time to run.

The only reason to use the second code can be that it offers better readability. But if the function is getting called many times then wouldn't the second function slow down the running time of the utility calling it?

What do you think about this?

答:
There are two speeds in software:  the time it takes to write/read/debug the code; and the time it takes to execute the code.

If you can convince me (and your code reviewers) that the hashmap function is indeed slower than the if/then/else (after refactoring to make a static hashmap) AND you can convince me/reviewers that its called enough times to make an actual difference, then go ahead and replace the hashmap with the if/else.

Otherwise, the hashmap code is eminently readable; and (probably) bugfree; you can determine that quickly just by looking at it.  You can't really say the same thing about the if/else without really studying it; the difference is even more exaggerated when there are hundreds of options.


问:
One table for all transaction VS. Table for each user
I'm making a website which has to do with money transactions. Everything was okay untill I came across the dilemma

Should I have one table to store all transaction history or I should have a seperated table for every user?

I tried to logicaly think the best solution and this is what I thought:

One table for all

Pretty much when every other dev would do

However what if i have 100.000 transactions inside?

That would slow down analytis for each user

MariaDB would have to do much more work

One table for each user

Every user is isolated

MariaDB can query faster

Easy data analysis

However what if 10.000 users have a table?

That would flood the database (not big deal if it can handle it)

I dont find anything wrong with using a table for each user but is it a common tachnique to design a database like that?

I found this post over here: What are the advantages/disadvantages of creating a new set of tables for each user?

which pretty much tells that is a terrible idea to have multiple table but does it really matter since in my case

I will never change the structure

I will never edit the data inside, only add new rows

I will enhance the security (principle of least privilege)

答:
Your arguments in favor table-per-user are wrong:

Every user is isolated

This kind of isolation only makes sense if you create a DB user for each user and let them directly run SQL queries on your database. You usually don't do that, but instead create an API for pre-defined queries. That API should do the isolation, not some separation of tables...

MariaDB can query faster

Not really. If you define the indexes properly, MariaDB can easily and efficiently perform user-specific queries. If you program correctly, table-per-user will actually result in slower queries because:

You won't be able to use query parameters to specify the user.

Therefore you'll have to construct an SQL command string of each query for each user.

Therefore your database connection won't be able to cache the queries.

Easy data analysis

Why? because you don't have to write WHERE user_id = 1234? But now you have to write instead transactions_1234, which might seem a bit easier, but that's only because we are writing SQL directly - in practice the user ID will be stored in a variable, so you'll have to write "... transactions_" + userId + "... instead of WHERE user_id = @user_id(and set the user ID using prepared statement parameters).

And even if you write SQL directly, one-table-for-all-users has other advantages that can help with analysis:

You can create views that'll help you with the analysis. The views can have a user_id field you can filter by, and MariaDB will be able to do that filter efficiently. With table-per-user you'd have to create a view for each user, which is far less maintainable - even if you never change the data structure you will want to modify the views or create new views.

You can create SQL functions that receive the user_id as an argument.

Also, when you open the workbench to perform that analysis, do you really want to see 10,000 tables in the table list?


问:
Authenticate in the Services? Or in an Endpoint that exposes the Services?
When I'm in charge, I typically model services separate from endpoints.  For example: Company.Project.Domain.dll has all of the logic required to complete the services for that domain.  In order to access it you either reference that library or, if I'm exposing the services through an endpoint, you can hit Company.Project.Endpoint at the URL: api.wutevz.com/blog/Message/

I mention the above because I have (seemingly unfortunately, but maybe I'm the wrong one) seen the majority of services/domains created directly inside an endpoint project (like WCF or Web API).  And knowing my setup is key to my question.  Also, if separating the logic from the endpoint is weird, feel free to chime in.  While I think separating them is correct, I'm jaded from many years of consulting and seeing them joined.

The question, if my methodology is sound, is: Where should Authentication Live in the backend?  This is unrelated to other questions asking if it should be in the backend vs the client.  My question is: On the Endpoints, or on the Services?

So my Web API has this Endpoint:

```<code>[HttpPost]
//[AuthenticatePlz]
public HttpResponseMessage Message([FromBody] string contents){
    _service.AddMessage(contents);
}
</code>```

And some domain service has the method that does the real biz:

```<code>//[AuthenticatePlz]
public void AddMessage(string contents) {
    // probably do some content checks or something and save the message
}
</code>```

Don't get too hung up on whether Aspects are being used, or some Owin middleware, or Line 1 of the method is an Auth call, or some other horrible implementation.  The goal is: Should the interception point, where Authentication is required, live on the Endpoint or the service method?

答:
Ideally authentication should happen neither in the end point nor the service. A module in IIS or a proxy server would be best, or a plugin to the application framework. If you must intermingle the two I would put the authentication in the end point. A "service" object should assume you have permissions to use it so it retains maximum reusability.

Really the end point should also assume you have permission to operate on it. Something higher up in the stack should prevent your end point object from executing if authentication fails. This way changes in permissions or authentication schemes don't require changes to your end point or service layer.


问:
Replacing connection strings and app settings during TFS build
A little background first: where I work we maintain about 40 .NET applications of varying size.  These apps share many secrets (account credentials, connection strings, etc.) in configuration files.  We encrypt all of our configuration files during build.  However, our approach still has disadvantages:

Whenever a credential changes (such as a password change), we have to update it in 40+ locations.

Developers have access to all credentials.

What I'd like to do is have some sort of system similar to how Azure allows you to specify app settings and connection string replacements during build/deployment:

We aren't using Azure (this is an internal, intranet environment) but we do have TFS running all of our builds.  I'm looking for recommendations about how I can centralize and secure credential management (ideally locked down to just our security folks) and tie our build system into this new system so that configuration is handled all via the build.

One additional question I have is how this approach would affect local development and debugging - currently, when we are developing locally, we typically are using "development" assets (a development database).  If I end up removing this configuration information from the local environment, how will our developers still be able to run apps locally (i.e., will I need to start providing a local configuration that creates local assets, such as a SQL server database).

答:
The way Team Foundation Server handles this is  through the Release Management tooling. So each deployment to each environment has different variables. This can be updated in a single place and you can have central replacements used in many application.

For build you replace your dev condign data with tokens that RM then replaces per environment as part of the deployment. Developers ben not have access to the values.


问:
How, in Three Tier Architecture is Database Access Achieved
So I am attempting to make an application based on the architecture proposed by this image;

(source: ibm.com)

[1]

However, I am getting very confused with how data access is achieved between the data access layer which is on a seperate tier (from my understanding this means a seperate server/machine) to the database. Say I have my hibernate config file;

```<code>    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">.......</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306</property>
</code>```

...etc

How, if Hibernate etc and the DB are on seperate servers can I possibly extract the data from the DB into my business logic layer using my DAL. Other than setting up JDBC and the MySQL server instance to use a remote connection, but its my understanding that it is bad practice to do this.

What is it that I am missing here?

答:
In an app like this the "tiers" are usually various parts of the same application. You could write it as multiple JARs packaged into a single deployment, but the different tiers are more about separating the different concerns in the code than putting physical distance between them.

If you were to put the data access on a separate machine, you would need some way for the frontend to communicate with it. This could be anything from remote EJBs to RMI or just another REST or SOAP service.

ContentLicense: CC BY-SA 4.0


答: One tactic used initially was the name - "JavaScript" was intended to ride on the popularity of Java, which had then been on the rise for some while.</p>

Title: How did JavaScript become popular?

Body:
In ancient history, Brendan Eich had a language design, and in today's world, JavaScript is a popular language implemented and used in many different places.

What caused the language to become popular? Was it the C-like syntax familiar to previous programmers? Did Netscape have enough control of the market to force it to be used? Or is there some deeper reason that JavaScript is popular and other languages are not?

Particularly, if you had to make a language as popular as JavaScript, what initial conditions would you need to recreate its growth in popularity?


答:
If your systems are sufficiently modular and link compatible, you would benefit from a single repository and build. For example, if C system is being rewritten in C++, the C++ code could call existing functionality and incrementally replace it.

However, even in this case some might argue for starting a new repo in which relevant old code is pulled in as required.

Title: Version control practice for Rewrites


答:
If I'm not mistaken, ASP.NET Web Api handles authentication using the IPrincipal interface.

A principal object represents the security context of the user on whose behalf the code is running, including that user's identity (IIdentity) and any roles to which they belong.

This object is basically a set of Claims which defines and describes the current user. That is, its username, email, and even roles.

Wether you're using a middleware or not, these claims have to be set so the authentication can be integrated in the IIS pipeline.

In a web service example like yours, these claims are commonly decoded from an authentication token. This token is sent along the user request, and therefore should be handled at an endpoint level (Controller).

Your domain service should not have to inspect the current request context, nor it has to know it's being called from a web service, or a desktop client.

Title: Authenticate in the Services? Or in an Endpoint that exposes the Services?

Body:
When I'm in charge, I typically model services separate from endpoints.  For example: Company.Project.Domain.dll has all of the logic required to complete the services for that domain.  In order to access it you either reference that library or, if I'm exposing the services through an endpoint, you can hit Company.Project.Endpoint at the URL: api.wutevz.com/blog/Message/

I mention the above because I have (seemingly unfortunately, but maybe I'm the wrong one) seen the majority of services/domains created directly inside an endpoint project (like WCF or Web API).  And knowing my setup is key to my question.  Also, if separating the logic from the endpoint is weird, feel free to chime in.  While I think separating them is correct, I'm jaded from many years of consulting and seeing them joined.

The question, if my methodology is sound, is: Where should Authentication Live in the backend?  This is unrelated to other questions asking if it should be in the backend vs the client.  My question is: On the Endpoints, or on the Services?

So my Web API has this Endpoint:

```<code>[HttpPost]
//[AuthenticatePlz]
public HttpResponseMessage Message([FromBody] string contents){
    _service.AddMessage(contents);
}
</code>```

And some domain service has the method that does the real biz:

```<code>//[AuthenticatePlz]
public void AddMessage(string contents) {
    // probably do some content checks or something and save the message
}
</code>```

Don't get too hung up on whether Aspects are being used, or some Owin middleware, or Line 1 of the method is an Auth call, or some other horrible implementation.  The goal is: Should the interception point, where Authentication is required, live on the Endpoint or the service method?


问:
Is there a standard way to indicate that a function returns a new pointer?
Sometimes I want to delegate the construction of objects that a class owns to a separate function. Something like

```<code>Vertex* new_vertex(const Options& options) {
  // do stuff...
  return new Vertex(...);
}
</code>```

where the function is only intended to be used to within a class that owns the Vertex. Clearly this function can cause some memory-leaking confusion, so I want to make it as clear as possible. Is there a naming convention for such functions?

答:
Return a unique_ptr:

```<code>std::unique_ptr<Vertex> new_vertex(const Options& options) {
  // do stuff...
  return std::make_unique<Vertex>(...);
}
</code>```

There can only ever be one unique_ptr pointing to a given object (unless you abuse it by casting to a Vertex* and back, anyway). You can't ever copy a unique_ptr, only move it. When a unique_ptr is destroyed (and hasn't been moved out of) it even deletes the object for you.

make_unique creates a new Vertex and wraps it in a unique_ptr; the arguments you pass to make_unique are the arguments it passes to the constructor.

Body:
Return a unique_ptr:

std::unique_ptr<Vertex> new_vertex(const Options& options) {
  // do stuff...
  return std::make_unique<Vertex>(...);
}

There can only ever be one unique_ptr pointing to a given object (unless you abuse it by casting to a Vertex* and back, anyway). You can't ever copy a unique_ptr, only move it. When a unique_ptr is destroyed (and hasn't been moved out of) it even deletes the object for you.

make_unique creates a new Vertex and wraps it in a unique_ptr; the arguments you pass to make_unique are the arguments it passes to the constructor.