答:
I'm in the camp that agrees with you.  If you keep a Gender enum in your code and a tblGender in your database, you may run into trouble come maintenance-time.  You'll need to document that these two entities should have the same values and thus any changes you make to one you must also make to the other.

You'll then need to pass the enum values to your stored procedures like so:

create stored procedure InsertPerson @name varchar, @gender int
    insert into tblPeople (name, gender)
    values (@name, @gender)
```

<p>But think how you'd do this if you kept these values in a database table:</p>

<pre class="lang-sql prettyprint-override"><code>create stored procedure InsertPerson @name varchar, @genderName varchar
    insert into tblPeople (name, gender)
    select @name, fkGender
    from tblGender
    where genderName = @genderName --I hope these are the same
</code>```

Sure relational databases are built with joins in mind, but which query is easier to read?

Here's another example query:

create stored procedure SpGetGenderCounts
    select count(*) as count, gender
    from tblPeople
    group by gender
```

<p>Compare that to this:</p>

<pre class="lang-sql prettyprint-override"><code>create stored procedure SpGetGenderCounts
    select count(*) as count, genderName
    from tblPeople
    inner join tblGender on pkGender = fkGender
    group by genderName --assuming no two genders have the same name
</code>```

Here's yet another example query:

create stored procedure GetAllPeople
    select name, gender
    from tblPeople
```

<p>Note that in this example, you'd have to convert the gender cell in your results from an int to an enum.  These conversions are easy however.  Compare that to this:</p>

<pre class="lang-sql prettyprint-override"><code>create stored procedure GetAllPeople
    select name, genderName
    from tblPeople
    inner join tblGender on pkGender = fkGender
</code>```

All of these queries are smaller and more maintainable when going with your idea of keeping the enum definitions out of the database.

Title: Why would you store an enum in DB?

Body:
I'm in the camp that agrees with you.  If you keep a Gender enum in your code and a tblGender in your database, you may run into trouble come maintenance-time.  You'll need to document that these two entities should have the same values and thus any changes you make to one you must also make to the other.

You'll then need to pass the enum values to your stored procedures like so:

create stored procedure InsertPerson @name varchar, @gender int
    insert into tblPeople (name, gender)
    values (@name, @gender)

But think how you'd do this if you kept these values in a database table:

create stored procedure InsertPerson @name varchar, @genderName varchar
    insert into tblPeople (name, gender)
    select @name, fkGender
    from tblGender
    where genderName = @genderName --I hope these are the same

Sure relational databases are built with joins in mind, but which query is easier to read?

Here's another example query:

create stored procedure SpGetGenderCounts
    select count(*) as count, gender
    from tblPeople
    group by gender

Compare that to this:

create stored procedure SpGetGenderCounts
    select count(*) as count, genderName
    from tblPeople
    inner join tblGender on pkGender = fkGender
    group by genderName --assuming no two genders have the same name

Here's yet another example query:

create stored procedure GetAllPeople
    select name, gender
    from tblPeople

Note that in this example, you'd have to convert the gender cell in your results from an int to an enum.  These conversions are easy however.  Compare that to this:

create stored procedure GetAllPeople
    select name, genderName
    from tblPeople
    inner join tblGender on pkGender = fkGender

All of these queries are smaller and more maintainable when going with your idea of keeping the enum definitions out of the database.


问:
Call base inside overriden method
I know there are questions about calling the base method inside an overridden method such as this. But what if an overridden method only calls the base class? Is this bad/good deign? It just seems odd, why override a method just to call the base anyway?

For example see:

```<code>public class BaseClass
{
    virtual public void Method1()
    {
        //Do stuff
    }
}

public class InheritingClass : BaseClass
{
    override public void Method1()
    {
        base.Method1();
    }
}
</code>```

答:
But what if an overridden method only calls the base class? Is this bad/good design?

Bad design? No, rather bad implementation. It's misleading for the maintenance programmer. When I don't see an override then I know the base is called. An override tells me there is something different, even if the base is called in there as well.

Requiring an override to call the base without a template is Bad Design

Referenced thread - most popular answser

My initial reaction to the Scandinavian override model is: CODING HORROR! It looks like I am forced to read all of that, and then more, to make sure the "sub-behavior" does not break my code and vice versa.

The Template Method Pattern is a good way to express variable code within some larger code flow and ensure correct execution order.

In my experience it so typical for a subclass to have to know what base-declared methods to call, and in order. Take a heaping handful of sub classes all with the same cut-n-paste control structure, add 5 years of maintenance; now you understand why I prefer 101 proof Wild Turkey.

P.S. All that is one big reason why I rail against the over-use of interfaces in lieu of abstract classes.

ContentLicense: CC BY-SA 3.0

Title: Call base inside overriden method


问:
Stubbing Properties with private setters for tests
We have the object

```<code>public class MyObject{
    protected MyObject(){}

    public string Property1 {get;private set;}
    public string Property2 {get;private set;}
    public string Property3 {get;private set;}
    public string Property4 {get;private set;}
    public string Property5 {get;private set;}
    public string Property6 {get;private set;}
    public string Property7 {get;private set;}
    public string Property8 {get;private set;}
    public string Property9 {get;private set;}
    public string Property10 {get;private set;}
}
</code>```

In our production code we populate this object through automapper. It can access the properties and set them correctly.

Now when we want to test this class in a future pipeline it is not possible to populate the properties with dummy values (to be tested against).

There are a few options available.

Custom constructors to accept the parameters required for the tests and set the properties, currently 3 constructors are required. This is not clean since the constructors do not serve any business functionality.

Make the properties virtual so the class can be stubbed. But marking the properties virtual does not provide any business value and pollute my class.

Add an object builder to the class to internally construct the object. Again no added business value. Perhaps a bit cleaner but still a lot of non relevant code in the domain objects.

Any suggestions, advice or alternative options here?

答:
I don't hesitate to use reflection for things like this in tests.

I dislike making things virtual for mocking as it changes the code for the wrong reason.

I don't know automapper but I agree with @Mike that including it in the tests can be a good idea.
The distinction unit test / integration test is not very interesting imo.
Sure if the test suite is getting big and slow you will need to filter and classify things to run only a sensible subset of all tests at the highest frequency.

Sample hack using reflection, using nameof() will have better perf but then  you loose types.:

```<code>public static class TestExtensions
{
    public static void SetProperty<TSource, TProperty>(
        this TSource source,
        Expression<Func<TSource, TProperty>> prop,
        TProperty value)
    {
        var propertyInfo = (PropertyInfo)((MemberExpression)prop.Body).Member;
        propertyInfo.SetValue(source, value);
    }
}
</code>```

Body:
I don't hesitate to use reflection for things like this in tests.

I dislike making things virtual for mocking as it changes the code for the wrong reason.

I don't know automapper but I agree with @Mike that including it in the tests can be a good idea.
The distinction unit test / integration test is not very interesting imo.
Sure if the test suite is getting big and slow you will need to filter and classify things to run only a sensible subset of all tests at the highest frequency.

Sample hack using reflection, using nameof() will have better perf but then  you loose types.:

public static class TestExtensions
{
    public static void SetProperty<TSource, TProperty>(
        this TSource source,
        Expression<Func<TSource, TProperty>> prop,
        TProperty value)
    {
        var propertyInfo = (PropertyInfo)((MemberExpression)prop.Body).Member;
        propertyInfo.SetValue(source, value);
    }
}


问:
Object with Customized Properties and Methods
A project I am working on currently models Order information. Right now, there is one class with a bunch of properties and functions that all of orders have in common. In addition, some of our users have customized properties and/or functions on top of the base order. Some of those customized properties are shared between multiple users and some are unique to a given user. The class has nearly 50 different properties, but a given user might only be using 20 or so of those properties.

I'd like to redesign it so that the base properties/functions are separate from the customized properties/functions, but I don't know how to approach this. I thought about inheriting the base class, but a user might have 3 or 4 different customized properties. There is no clear inheritance among the customized properties. I looked into the decorator pattern, but the interface is changing, so that doesn't seem to fit.

Is there any way to accomplish this without having the monolithic class?

Examples:

```<code>Base Properties - OrderID, OrderDate, AccountId, etc.
Customized Properties - BackOrdered, PONumber, ContactPerson
Base Functions - PlaceOrder, CancelOrder
Customized Functions - AddContact, DiscountPriceByPercent
</code>```

So, some users might only have the base, one user might have the base + BackOrdered, and another user might have base + BackOrdered + PONumber.

This problem isn't unique to orders, I have the same problem with other objects in the project. I'm looking more for an architecture/pattern to solve the general case than for a way to handle orders.

答:
For order fulfilment processes where differnt types of order can have different things happen to them I suggest that you take a service orientated approach. Moving the domain logic out of the object into services and add an event history to the object to store its variable state.

Ie. Instead of AdvanceOrder and SendNowOrder with overridden Buy() methods have BuyNowService and PlaceAdvanceOrderService both of which have a Buy(Order order) method.

You can then send orders to one or other service as required.

Instead of AdvanceOrder.DateToPlace and BuyNowOrder.IsInStock Have DelayUntillEvent and OutOfStockEvent inheriting from a base Event and stored in Order.Events Only services which know how to handle these events need reference them.


问:
Is using Runnable outside of the context of multithreading valid?
Inspired by this SO question, I'd like to better understand the contract defined by Runnable, along with when it is and is not acceptable to use the Runnable interface. We know that Runnable's most common use-case is to be implemented by a class that is intended to be executed on a separate thread:

```<code>Runnable task = () -> {
    // Code to be executed on another thread
};
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(task);
</code>```

This yields two questions:

Is this the only acceptable pattern for its usage?

If not, what are other acceptable usage patterns for Runnable that do not revolve around multithreading?

The use-case in the original SO question is to create a generic way to execute code before and after a method's execution without repetition, such as:

```<code>public void example1() {
    before();
    method1();
    after();
}

public void example2() {
    before();
    method2();
    after();
}
</code>```

Eran's answer proposes using Runnable to allow encapsulation of the logic for each method, along with a single method that accepts the Runnable as an argument and invokes Runnable#run at the appropriate time:

```<code>public void call(Runnable method){
    before();
    method.run();
    after();
}

call( () -> { method1(); });
call( () -> { method2(); });
</code>```

However, using Runnable in this fashion was met with some disagreement, stating that this is not an acceptable use of Runnable. Is this is a valid concern, or a matter of stylistic opinion?

From my own research, the Javadoc for Runnable states the following contract, which seems to still be upheld with this usage of Runnable:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Further, if usage outside of the context of multithreading were discouraged or disallowed, I would expect either:

The Javadoc to mention it somewhere, or

Runnable to be in a concurrency-specific package, e.g. java.util.concurrent, however it is available in java.util.

答:
Streams and lambda expressions invite the use of single-method interfaces. It's easy enough to write a new interface, but also tempting to simply re-purpose one that the system provides instead of littering the code base with tiny interfaces.

However, when an interface is strongly associated with something, remapping its semantics sets the stage for a future maintainer of the code to waste time looking for things that aren't there. In the case of Runnable, the future maintainer might waste time by hunting for the elusive concurrency they think is subtly embedded in the code.

Although you could add comments everywhere, it would be neater to just create your own interface, establishing your own semantics explicitly.


答: I would argue that using Runnable outside the context of multi threading would be misleading as to the intent of your code. Sure you can use it outside that context because after all it's just an interface with a no arg run method. But it might be better to create your own interface that is more specific as to the intent of what the code does.</p>

Title: Is using Runnable outside of the context of multithreading valid?

Body:
Inspired by this SO question, I'd like to better understand the contract defined by Runnable, along with when it is and is not acceptable to use the Runnable interface. We know that Runnable's most common use-case is to be implemented by a class that is intended to be executed on a separate thread:

```<code>Runnable task = () -> {
    // Code to be executed on another thread
};
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(task);
</code>```

This yields two questions:

Is this the only acceptable pattern for its usage?

If not, what are other acceptable usage patterns for Runnable that do not revolve around multithreading?

The use-case in the original SO question is to create a generic way to execute code before and after a method's execution without repetition, such as:

```<code>public void example1() {
    before();
    method1();
    after();
}

public void example2() {
    before();
    method2();
    after();
}
</code>```

Eran's answer proposes using Runnable to allow encapsulation of the logic for each method, along with a single method that accepts the Runnable as an argument and invokes Runnable#run at the appropriate time:

```<code>public void call(Runnable method){
    before();
    method.run();
    after();
}

call( () -> { method1(); });
call( () -> { method2(); });
</code>```

However, using Runnable in this fashion was met with some disagreement, stating that this is not an acceptable use of Runnable. Is this is a valid concern, or a matter of stylistic opinion?

From my own research, the Javadoc for Runnable states the following contract, which seems to still be upheld with this usage of Runnable:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Further, if usage outside of the context of multithreading were discouraged or disallowed, I would expect either:

The Javadoc to mention it somewhere, or

Runnable to be in a concurrency-specific package, e.g. java.util.concurrent, however it is available in java.util.


问:
What is the most efficient way to store this data?
I am in charge of rewriting some old VB code. I understand how it works, but I feel like there is a far-more efficient way to do what they did. I just can't figure out what it is. Here is a contrived example that in terms of data requirements is really similar to what I need to do.

The user has to pick out the manufacturer, make, model and color of their car in a GUI. I have a large text file that looks something like this:

```<code>Ford Truck F150 red
Ford Truck F150 blue
Ford Truck F150 black
Ford Truck F150 silver
Ford Truck F250 red
Ford Truck F250 green
Ford Sedan Taurus red
Ford Sedan Taurus green
Ford Sedan Taurus white
Ford...
...

Subaru SUV Forester blue
Subaru SUV Forester red
Subaru SUV Outback Black
Subaru SUV Outback Green
Subaru SUV Outback Blue
Subaru SUV Outback Red
Subaru...
...

etc.
</code>```

So if the first selection is Subaru, the second box (make) should not have an option to select Truck because none of the Subarus are trucks. Similarly, if they select Ford, Sedan and Taurus, then the last box (color) should not show an option to select blue. Or Black. Or anything other than red, green or white.

The people who wrote the code before me came up with this (in python-y psuedocode):

```<code>def getValidOptions():
    items = []
    for i from 0 to numRows:
        options = getLine().split()
        if selectingManufacturer:
            if options[0] not in items:
                items.append(options[0])
        else if selectingMake:
            if selectedManufacturer == options[0] and options[1] not in items:
               items.append(options[1])
        else if selectingModel:
            if selectedManufacturer == options[0] and selectedMake == options[1] and options[2] not in items:
                items.append(options[2])
        else if selectingColor:
            if selectedManufacturer == options[0] and selectedMake == options[1] and selectedModel == options[2] and options[3] not in items:
                items.append(options[3])
    return items
</code>```

I think that is just hideous, both on an algorithm level, and on a syntax level. For one, it parses through the entire file, when it only needs to read through a couple of lines if done right. To make this even more inefficient, my real data has 6 options to select through, rather than just 4. This is also storing more data then it needs to, given the amount of data duplication.

I'm looking for either a different way of storing the data in the file, or a different way of parsing it to make the getValidOptions function both more pretty and more efficient. Are there any ways I could do this?

答:
Well, the data you have has a tree-like structure, where for each manufacturer you have a tree of models, and for each model you have a color (and so on).

So, you could separate the process of this data in a two step way:

After any update to the text file, you must process that file file and convert it to a tree structure.

When loading the application, you only load the tree structure.

The tree structure can be implemented with what is called a hash, an associative array or a dictionary in languages like Java, PHP, Javascript or Python. With this structure, you have:

The first keys are the manufacturers.

Their values are just another hashes or dictionaries where each key is the model.

Their values are the colors. Or another structure keeping in their keys the third level and as value the fourth level.

And so on...

Depending on your programming language, this can be implemented faster or slower. For example:

C#: You can implement a Tree structure1, and then mark it as serializable.

VB.Net: you can generate the tree structure in one application, and serialize it in a file.

For this, something like Runtime.Serialization.Formatters.Binary.BinaryFormatter could be useful, but I'm no expert in serializing with VB.Net.

Javascript: you can generate the tree structure in a JSON file, that must be loaded every time the app is loaded.

PHP: you can generate a serialized version of the tree data structure, or you can load a JSON as well.

Java: you can serialize that data structure, creating a Class that implements the interface java.io.Serializable.

References:

1: https://dvanderboom.wordpress.com/2008/03/15/treet-implementing-a-non-binary-tree-in-c/

- A complete explanation on implementing a tree in C#.

- Look for a comment where someone asks about serializing that object, and the answer for that comment.


问:
Why does the Lisp community prefer to accumulate all the parentheses at the end of the function?
Why does the Lisp community prefer to accumulate all the parentheses at the end of the function:

```<code>(defn defer-expensive [cheap expensive]
  (if-let [good-enough (force cheap)]
    good-enough
    (force expensive)))
</code>```

Why not employ a convention like C or Java?

Well ok, Lisp is much more older than those languages, but I'm talking about the contemporary Lispers.

```<code>(defn defer-expensive [cheap expensive]
  (if-let [good-enough (force cheap)]
    good-enough
    (force expensive)
  )
)
</code>```

Note: Code snippet is from the book "The Joy of Clojure".

答:
Lispers, you know, hatefully bletcherous as it may be, there is a certain je ne sais quoi to the second example:

```<code>(defn defer-expensive [cheap expensive]
  (if-let [good-enough (force cheap)]
    good-enough
    (force expensive)
  )
)
</code>```

At first I couldn't put a finger on the source of the allure, so to speak, and then I realized it is just missing a trigger:

```<code>(defn defer-expensive [cheap expensive]
  (if-let [good-enough (force cheap)]
    good-enough   ;   )
    (force expensive)
  )
)
</code>```

Voilà!

I'm going to practice my Lisp gangster grip now!

Body:
Lispers, you know, hatefully bletcherous as it may be, there is a certain je ne sais quoi to the second example:

(defn defer-expensive [cheap expensive]
  (if-let [good-enough (force cheap)]
    good-enough
    (force expensive)
  )
)

At first I couldn't put a finger on the source of the allure, so to speak, and then I realized it is just missing a trigger:

(defn defer-expensive [cheap expensive]
  (if-let [good-enough (force cheap)]
    good-enough   ;   )
    (force expensive)
  )
)

Voilà!

I'm going to practice my Lisp gangster grip now!


问:
Why use plus equals += for event registration?
In C#, you register an event like:

```<code>window.onClick += myHandler;
</code>```

But why use this instead of a "register" method that takes your handler and registers it. E.g.:

```<code>window.registerOnClick(myHandler);
</code>```

The += counters my intuition for at least two reasons:

Couldn't somebody use = to eliminate past registrations? But more generally:

My OOP classes always told me to use getters and setters, not public members.

This came up because I'm writing events in Python and my first thought was to use a register_handler_on_click(handler) rather than public member variables.

答:
If you ever try to write something like:

```<code>window.onClick = myHandler;
</code>```

You will get a compiler error about event handlers only allowed on the right side of a += or -=. The C# compiler team was smart enough to recognize that possibility and make it a compiler error.

Events are special types of multi-cast delegates, so therefore you are adding to its invocation list when you += a handler to the event. In this case I think it makes more sense to have += and -= to add or subtract event handlers.

I'm not sure who taught your OOP classes, but not everything needs to be reduced to a get/set method. .NET has made get/set type access a lot easier with properties, which include get/set methods in a single construct.

VB.NET uses a slightly different syntax for adding and removing events that are more inline with what you want. They use AddHandler and RemoveHandler methods for adding or removing from the event invocation list, although being a C# programmer I find the VB style "long winded".

Body:
If you ever try to write something like:

window.onClick = myHandler;

You will get a compiler error about event handlers only allowed on the right side of a += or -=. The C# compiler team was smart enough to recognize that possibility and make it a compiler error.

Events are special types of multi-cast delegates, so therefore you are adding to its invocation list when you += a handler to the event. In this case I think it makes more sense to have += and -= to add or subtract event handlers.

I'm not sure who taught your OOP classes, but not everything needs to be reduced to a get/set method. .NET has made get/set type access a lot easier with properties, which include get/set methods in a single construct.

VB.NET uses a slightly different syntax for adding and removing events that are more inline with what you want. They use AddHandler and RemoveHandler methods for adding or removing from the event invocation list, although being a C# programmer I find the VB style "long winded".


答:
Events are just specialized delegates. For delegates, = does eliminate past registrations. Likewise + performs functional composition, like many other languages. So += combines those operations into functional append.

Events just happen to limit the other operations, making it a little less intuitive since you don't see where they came from.

Title: Why use plus equals += for event registration?

Body:
In C#, you register an event like:

```<code>window.onClick += myHandler;
</code>```

But why use this instead of a "register" method that takes your handler and registers it. E.g.:

```<code>window.registerOnClick(myHandler);
</code>```

The += counters my intuition for at least two reasons:

Couldn't somebody use = to eliminate past registrations? But more generally:

My OOP classes always told me to use getters and setters, not public members.

This came up because I'm writing events in Python and my first thought was to use a register_handler_on_click(handler) rather than public member variables.


答:
I assume you can randomly access lines in the file, and thus can treat the file as an array of records.  If you can't randomly access the lines, then the algorithm you have is the best you can do.

For speediest access, store the data in 6 files, where each file is an index into the next.

There are mny ways to create flatfile indices.  I usually use a subscript range.  As the user makes each selection, use the range to limit the reading of the next file.

Here is how I would create the indices for the sample data you provided.

Of course the file must be sorted.  I've numbered the lines for illustration; the line numbers should not appear in the file.

```<code>--| file3.dat |--
 0 Ford Truck F150 red
 1 Ford Truck F150 blue
 2 Ford Truck F150 black
 3 Ford Truck F150 silver
 4 Ford Truck F250 red
 5 Ford Truck F250 green
 6 Ford Sedan Taurus red
 7 Ford Sedan Taurus green
 8 Ford Sedan Taurus white
 9 Subaru SUV Forester blue
10 Subaru SUV Forester red
11 Subaru SUV Outback Black
12 Subaru SUV Outback Green
13 Subaru SUV Outback Blue
14 Subaru SUV Outback Red
</code>```

To create the first index, make a record for each unique combination of the first three fields in the file.  In each record, store the first and last line numbers in which that combination appears.

```<code>--| file2.dat |--
 0 Ford Truck F150       0   3
 1 Ford Truck F250       4   5
 2 Ford Sedan Taurus     6   8
 3 Subaru SUV Forester   9  10
 4 Subaru SUV Outback   11  14
</code>```

The second index is constructed similarly, using the first two fields of the first index.

```<code>--| file1.dat |--
 0 Ford Truck        0   1
 1 Ford Sedan        2   2
 2 Subaru SUV        3   4
</code>```

And the third, the top level in this case, index.

```<code>--| file0.dat |--
 0 Ford          0   1
 1 Subaru        2   2
</code>```

I think I'm overexplaining the concept, but in general you create an index by dropping the last field and eliminating duplicate records.

You can further reduce the file storage requirement by eliminating some redundant data.

For example, the "first" subscript in each index record is always one more than the "last" subscript of the prior record, or zero if there is no prior record.  So you don't need to store the "first" subscripts.  I'm leaving them in place below for illustration.

Also, since you will use only the last field in each record to fill the selection list, you don't need to store the other fields.

The minimum rendition of the index cascade ends up looking like this, where the tick ' indicates a number not actually stored in the file.

```<code>--| file0.dat |--
 0' Ford         0'   1
 1' Subaru       2'   2

--| file1.dat |--
 0' Truck        0'   1
 1' Sedan        2'   2
 2' SUV          3'   4

--| file2.dat |--
 0' F150         0'   3
 1' F250         4'   5
 2' Taurus       6'   8
 3' Forester     9'  10
 4' Outback     11'  14

--| file3.dat |--
 0' red
 1' blue
 2' black
 3' silver
 4' red
 5' green
 6' red
 7' green
 8' white
 9' blue
10' red
11' Black
12' Green
13' Blue
14' Red
</code>```

When you fill a selection list from an index, you use the "first" and "last" subscripts from the user's selection in the previous index to limit the lines read.

Example:

You fill the first selection list from all of file0.dat. (Ford, Subaru)

The user selects "Ford".  The corresponding subscripts are 0 and 1.

You fill the second selection list from lines 0 thru 1 of file1.dat. (Truck, Sedan)

The user selects "Sedan".  The corresponding subscripts are 2 and 2.

As you can see, by the time the user has selected, eg, "Ford" "Sedan" "Taurus" you will find that you need read only lines 6 thru 8 of file3.dat to fill the fourth selection list.

I apologize for the rather long description but it's very late here and I don't have time to write a short one.

ADDED: On further thought, the files can be concatenated into one.

```<code>--| file.dat |--
 0' -            1'   2
 1' Ford         3'   4
 2' Subaru       5'   5
 3' Truck        6'   7
 4' Sedan        8'   8
 5' SUV          9'  10
 6' F150        11'  14
 7' F250        15'  16
 8' Taurus      17'  19
 9' Forester    20'  21
10' Outback     22'  25
11' red          -'   -
12' blue         -'   -
13' black        -'   -
14' silver       -'   -
15' red          -'   -
16' green        -'   -
17' red          -'   -
18' green        -'   -
19' white        -'   -
20' blue         -'   -
21' red          -'   -
22' Black        -'   -
23' Green        -'   -
24' Blue         -'   -
25' Red          -'   -
</code>```

This is used exactly like the multiple file version, except you need the dummy first line to contain the first subscript range.

Title: What is the most efficient way to store this data?

Body:
I am in charge of rewriting some old VB code. I understand how it works, but I feel like there is a far-more efficient way to do what they did. I just can't figure out what it is. Here is a contrived example that in terms of data requirements is really similar to what I need to do.

The user has to pick out the manufacturer, make, model and color of their car in a GUI. I have a large text file that looks something like this:

```<code>Ford Truck F150 red
Ford Truck F150 blue
Ford Truck F150 black
Ford Truck F150 silver
Ford Truck F250 red
Ford Truck F250 green
Ford Sedan Taurus red
Ford Sedan Taurus green
Ford Sedan Taurus white
Ford...
...

Subaru SUV Forester blue
Subaru SUV Forester red
Subaru SUV Outback Black
Subaru SUV Outback Green
Subaru SUV Outback Blue
Subaru SUV Outback Red
Subaru...
...

etc.
</code>```

So if the first selection is Subaru, the second box (make) should not have an option to select Truck because none of the Subarus are trucks. Similarly, if they select Ford, Sedan and Taurus, then the last box (color) should not show an option to select blue. Or Black. Or anything other than red, green or white.

The people who wrote the code before me came up with this (in python-y psuedocode):

```<code>def getValidOptions():
    items = []
    for i from 0 to numRows:
        options = getLine().split()
        if selectingManufacturer:
            if options[0] not in items:
                items.append(options[0])
        else if selectingMake:
            if selectedManufacturer == options[0] and options[1] not in items:
               items.append(options[1])
        else if selectingModel:
            if selectedManufacturer == options[0] and selectedMake == options[1] and options[2] not in items:
                items.append(options[2])
        else if selectingColor:
            if selectedManufacturer == options[0] and selectedMake == options[1] and selectedModel == options[2] and options[3] not in items:
                items.append(options[3])
    return items
</code>```

I think that is just hideous, both on an algorithm level, and on a syntax level. For one, it parses through the entire file, when it only needs to read through a couple of lines if done right. To make this even more inefficient, my real data has 6 options to select through, rather than just 4. This is also storing more data then it needs to, given the amount of data duplication.

I'm looking for either a different way of storing the data in the file, or a different way of parsing it to make the getValidOptions function both more pretty and more efficient. Are there any ways I could do this?

Body:
I assume you can randomly access lines in the file, and thus can treat the file as an array of records.  If you can't randomly access the lines, then the algorithm you have is the best you can do.

For speediest access, store the data in 6 files, where each file is an index into the next.

There are mny ways to create flatfile indices.  I usually use a subscript range.  As the user makes each selection, use the range to limit the reading of the next file.

Here is how I would create the indices for the sample data you provided.

Of course the file must be sorted.  I've numbered the lines for illustration; the line numbers should not appear in the file.

--| file3.dat |--
 0 Ford Truck F150 red
 1 Ford Truck F150 blue
 2 Ford Truck F150 black
 3 Ford Truck F150 silver
 4 Ford Truck F250 red
 5 Ford Truck F250 green
 6 Ford Sedan Taurus red
 7 Ford Sedan Taurus green
 8 Ford Sedan Taurus white
 9 Subaru SUV Forester blue
10 Subaru SUV Forester red
11 Subaru SUV Outback Black
12 Subaru SUV Outback Green
13 Subaru SUV Outback Blue
14 Subaru SUV Outback Red

To create the first index, make a record for each unique combination of the first three fields in the file.  In each record, store the first and last line numbers in which that combination appears.

--| file2.dat |--
 0 Ford Truck F150       0   3
 1 Ford Truck F250       4   5
 2 Ford Sedan Taurus     6   8
 3 Subaru SUV Forester   9  10
 4 Subaru SUV Outback   11  14

The second index is constructed similarly, using the first two fields of the first index.

--| file1.dat |--
 0 Ford Truck        0   1
 1 Ford Sedan        2   2
 2 Subaru SUV        3   4

And the third, the top level in this case, index.

--| file0.dat |--
 0 Ford          0   1
 1 Subaru        2   2

I think I'm overexplaining the concept, but in general you create an index by dropping the last field and eliminating duplicate records.

You can further reduce the file storage requirement by eliminating some redundant data.

For example, the "first" subscript in each index record is always one more than the "last" subscript of the prior record, or zero if there is no prior record.  So you don't need to store the "first" subscripts.  I'm leaving them in place below for illustration.

Also, since you will use only the last field in each record to fill the selection list, you don't need to store the other fields.

The minimum rendition of the index cascade ends up looking like this, where the tick ' indicates a number not actually stored in the file.

--| file0.dat |--
 0' Ford         0'   1
 1' Subaru       2'   2

--| file1.dat |--
 0' Truck        0'   1
 1' Sedan        2'   2
 2' SUV          3'   4

--| file2.dat |--
 0' F150         0'   3
 1' F250         4'   5
 2' Taurus       6'   8
 3' Forester     9'  10
 4' Outback     11'  14

--| file3.dat |--
 0' red
 1' blue
 2' black
 3' silver
 4' red
 5' green
 6' red
 7' green
 8' white
 9' blue
10' red
11' Black
12' Green
13' Blue
14' Red

When you fill a selection list from an index, you use the "first" and "last" subscripts from the user's selection in the previous index to limit the lines read.

Example:

You fill the first selection list from all of file0.dat. (Ford, Subaru)

The user selects "Ford".  The corresponding subscripts are 0 and 1.

You fill the second selection list from lines 0 thru 1 of file1.dat. (Truck, Sedan)

The user selects "Sedan".  The corresponding subscripts are 2 and 2.

As you can see, by the time the user has selected, eg, "Ford" "Sedan" "Taurus" you will find that you need read only lines 6 thru 8 of file3.dat to fill the fourth selection list.

I apologize for the rather long description but it's very late here and I don't have time to write a short one.

ADDED: On further thought, the files can be concatenated into one.

--| file.dat |--
 0' -            1'   2
 1' Ford         3'   4
 2' Subaru       5'   5
 3' Truck        6'   7
 4' Sedan        8'   8
 5' SUV          9'  10
 6' F150        11'  14
 7' F250        15'  16
 8' Taurus      17'  19
 9' Forester    20'  21
10' Outback     22'  25
11' red          -'   -
12' blue         -'   -
13' black        -'   -
14' silver       -'   -
15' red          -'   -
16' green        -'   -
17' red          -'   -
18' green        -'   -
19' white        -'   -
20' blue         -'   -
21' red          -'   -
22' Black        -'   -
23' Green        -'   -
24' Blue         -'   -
25' Red          -'   -

This is used exactly like the multiple file version, except you need the dummy first line to contain the first subscript range.


答:
One simple way to store the data is to just stuff it into a SQLite database.  SQLite, unlike most SQL databases, is well-suited for use as an application file format.  This approach has several benefits:

No need to code a serializer or a deserializer.

File is editable and queryable by numerous existing programs.

The conditional messiness you mention in the question is avoided.  To limit dropdowns, generate a simple where clause against each column (e.g., select distinct model where manufacturer='ford' and color = 'red').

This does force you to learn SQL, but avoids the need to learn a custom file format.


问:
Daily standups- yea or nay?
How valuable (or not) do you think daily stand-up meetings are?

If you're not familiar with it, this refers to a daily meeting that is part of Scrum adherents (and some other agile methodologies).  The idea is that you hold a daily meeting, timeboxed to 15 minutes, and in which everyone must stand (to encourage people to be to-the-point).

In the meeting, you go around the room and each say:
- What you did yesterday
- What you plan to do today
- Any blockers or impediments to your progress.

Do you think this practice has value?  Has anyone worked at a place that's done it, and what did you think?

答:
I find these meetings very valuable. They offer the following benefits—in return of spending just 15 minutes!

Keeps everyone on-topic.  It's easy to dig into your own problems and forget about what others do, or to repeat work being done by someone else.  Daily meetings prevent this from happening.

Doesn't allow people to slack.  At these meetings you make promises.  Then you just have to try to keep them.

Makes people interact.  Programmers usually don't like talking to people.  However, in such meetings they get encouragement (and reprimands) from their colleagues, which has positive effect on morale.

Gathers everyone in one place.  You get a bonus of knowing that everyone will come there.  This can be used to arrange other meetings, make announcements and to continue this daily meeting in smaller groups to discuss specific problems.  Usually, organizing such meetings takes a lot of attention and requires skills that programmers don't like to use.

Title: Daily standups- yea or nay?

ContentLicense: CC BY-SA 2.5


答:
All the other answers I read seem to ignore two very basic rules of software development:

clarify the requirements first (especially the performance and storage requirements)

Keep It Simple, Stupid (see KISS)

You wrote "the text file is large", but did not write too large, so I assume there is actually nothing wrong with its size except your gut feeling. So if loading the file does actually not take too long, and your IT department or someone else does not complain about the wasted disk space, and nobody complains about having problems maintaining the file, let the file format as it is - do not underestimate the value of simplicity.

You are also complaining about the efficiency of the algorithm, which is actually not as efficient as it could be, but it has one very big advantage: it is brain-dead simple and works. So as long as it is efficient enough, do not apply any premature optimization.

So lets assume the program works fast enough, what you should ask first is how can you improve the code in terms of simplicity and the DRY principle? And that is indeed a point which should be improved, since the current code is not DRY. In your example, there appears four times the almost same code block testing if the options on the "higher levels" match the current line, which results in four times the same kind of "append" call (in your real code, the repetition occurs at least six times, as you wrote). You can easily avoid that by introducing a numeric selection level, or passing the already selected options in an ordered list. Using your pseudo-code, this leads to something along the lines of

```<code># selectedOptions is a list, containing either nothing, or "selectedManufacturer"
# or [selectedManufacturer, selectedMake], ..., and so on
def getValidOptions(selectedOptions):
    items = []
    level = selectedOptions.size()
    for i from 0 to numRows:
        options = getLine().split()
        if selectedOptions == options[0:level-1] and options[level] not in item:
            items.append(options[level])
    return items
</code>```

So this is essentially the same algorithm with no repeated code any more.

Since it is obvious getValidOptions has to be called more than once (at least once per level), I suggest to apply only one optimization (if this is not already the case): make sure the getLine function pulls its data from main memory, and does not read the file from disk again and again.

Body:
All the other answers I read seem to ignore two very basic rules of software development:

clarify the requirements first (especially the performance and storage requirements)

Keep It Simple, Stupid (see KISS)

You wrote "the text file is large", but did not write too large, so I assume there is actually nothing wrong with its size except your gut feeling. So if loading the file does actually not take too long, and your IT department or someone else does not complain about the wasted disk space, and nobody complains about having problems maintaining the file, let the file format as it is - do not underestimate the value of simplicity.

You are also complaining about the efficiency of the algorithm, which is actually not as efficient as it could be, but it has one very big advantage: it is brain-dead simple and works. So as long as it is efficient enough, do not apply any premature optimization.

So lets assume the program works fast enough, what you should ask first is how can you improve the code in terms of simplicity and the DRY principle? And that is indeed a point which should be improved, since the current code is not DRY. In your example, there appears four times the almost same code block testing if the options on the "higher levels" match the current line, which results in four times the same kind of "append" call (in your real code, the repetition occurs at least six times, as you wrote). You can easily avoid that by introducing a numeric selection level, or passing the already selected options in an ordered list. Using your pseudo-code, this leads to something along the lines of

# selectedOptions is a list, containing either nothing, or "selectedManufacturer"
# or [selectedManufacturer, selectedMake], ..., and so on
def getValidOptions(selectedOptions):
    items = []
    level = selectedOptions.size()
    for i from 0 to numRows:
        options = getLine().split()
        if selectedOptions == options[0:level-1] and options[level] not in item:
            items.append(options[level])
    return items

So this is essentially the same algorithm with no repeated code any more.

Since it is obvious getValidOptions has to be called more than once (at least once per level), I suggest to apply only one optimization (if this is not already the case): make sure the getLine function pulls its data from main memory, and does not read the file from disk again and again.


答:
For unit testing purpose, make use of mocking frameworks like Microsoft Fakes, TypeMock and JustMock which provides support for mocking private members.

Please have a look at Smocks (avaiable @nuget packages) also. Limitation of Smocks is, it will not provide access to private members. But it has ability to mock static and non-virtual members. Also it is available for free of cost.

Another simplest way is to use, PrivateObject / PrivateType.

Title: Stubbing Properties with private setters for tests

Body:
We have the object

```<code>public class MyObject{
    protected MyObject(){}

    public string Property1 {get;private set;}
    public string Property2 {get;private set;}
    public string Property3 {get;private set;}
    public string Property4 {get;private set;}
    public string Property5 {get;private set;}
    public string Property6 {get;private set;}
    public string Property7 {get;private set;}
    public string Property8 {get;private set;}
    public string Property9 {get;private set;}
    public string Property10 {get;private set;}
}
</code>```

In our production code we populate this object through automapper. It can access the properties and set them correctly.

Now when we want to test this class in a future pipeline it is not possible to populate the properties with dummy values (to be tested against).

There are a few options available.

Custom constructors to accept the parameters required for the tests and set the properties, currently 3 constructors are required. This is not clean since the constructors do not serve any business functionality.

Make the properties virtual so the class can be stubbed. But marking the properties virtual does not provide any business value and pollute my class.

Add an object builder to the class to internally construct the object. Again no added business value. Perhaps a bit cleaner but still a lot of non relevant code in the domain objects.

Any suggestions, advice or alternative options here?


问:
A simple approach for data synchronisation
I want to synchronise the local database of mobile devices with the server's database. This synchronisation will happen for example when user comes online, to update the local as well as the remote database with possible changes.

I thought about 2 approaches and already implemented 1 of them, but it's quite complicated and I fear a bit about its performance and error-proneness.

Approach 1.

The approach I implemented does all the synchronisation in the server. I'll store in the client's database the last server update timestamp for each item and a flag for items that are marked for removal. I send all my items - with their timestamps and flags - to the server, and the server then decides which items have to be inserted, updated - only if the last update timestamp of the client is equal to the last update timestamp stored in the server (meaning the client has the latest version of the item) and what has to be deleted. Then I do a fresh query to the database and send everything back to the client. The client overwrites it's local database with the result. In detail:

Client sends all its items to server (this could be refined by filtering items that need create/update/delete, but for now it sends everything). Items have a server last update timestamp and flag if it's marked to be deleted.

Server queries all the items for the user

Programmatic algorithm that goes through all the items checking timestamps in order to determine if the item can be updated/deleted or not. If the last server update timestamp in the client's item is different than the one stored in the server (meaning, someone else updated the item in between) the update/delete is rejected. I build many lists here, one of items that have to be inserted (items are not in the server's query result), items that are to be updated, items that are to be deleted, items that can't be updated because the timestamp is different, items that can't be deleted because the timestamp is different.

Transaction for inserts/updates/deletes, for which I use lists constructed in 3.

Query to get again all the items for the user.

Send result of this query to client, together with the lists of items that couldn't be updated or deleted built in 3., so client knows what failed.

The problem with this approach is the multiple queries and programmatic processing, another client (some items can have multiple users) could update something in between these queries and updates can get lost. I assume I have to compact my queries (try to somehow do everything in a single transaction, maybe use stored procedures?) and lock rows to avoid synchronisation issues. My knowledge of SQL doesn't go much further than select...where and join so I may me missing a better way to do this.

Approach 2.

Because of these complications I was thinking if there's maybe a simpler way. The other idea I had, was to do the synchronisation in the client. So I'd do first query all my data and do an update (for which I still need the last update timestamp and delete flags - only this time the sync logic is in the client and I don't have to worry about multiple users here), and then send the sync result to the server which will just do an overwrite. In detail:

Download items for user

Do sync alhorithm in the client, similar to what I do in the server in 3. (Approach 1).

Upload items to the server, server overwrites user's items with this.

The problem here, of course, is that another client can update items in the server while this client is doing sync, and when it uploads the results, the updates of former client will be lost. I thought maybe I can work around this with a hash, so the downloaded data has a hash and when the database is to be overwritten with the sync result I do a query first and check it's the same hash, if not return an error. But then again I'm with multiple queries in the server and not sure this a recommended way.

I'd appreciate thoughts on this matter. Is my current approach the best? Or should I rather go with the client sync (this would also reduce workload in the server, which is good), but then how do I avoid possible overwrites, is the hash a good idea?  Note that my app doesn't have super strict requirements, it's something like shared todo lists with a few additional features, nothing generic (like a file sharing service) or for health, science etc. so if once in a (long) while an update is lost it's not the end of the world. I care a little more about performance and implementation easiness than 100% correctness. Of course the less error prone, the better.

P.S. would also appreciate reading recommendations about this (maybe as a comment), any good resource about sync strategies. I'm using Scala, Play 2.4 and Akka in some parts so a recommendation in this direction would also be very useful.

答:
There may be another approach depending on whether it's ok for your use case. Instead of trying to synchronise between different versions from different clients, lock them out for the duration of the update.

For example, you could do something like the following:

update locktable set current_user='user61852' where current_user=''

where of course locktable is a single row (single column) table. On failure (current_user is still not your id), sleep for a bit and try again.

On success, (re)query the data as necessary and do your inserts etc. Then make absolutely sure that in every eventuality, current_user is set back to '' (so you're probably want to handle a timeout as well).

It has some disadvantages of course, especially when everyone wants to do it at 9 am in the morning, and there's a lot of things to transfer.


问:
Access rights through database table
I made a login system with access rights (ASP.NET WebForm) and I store the info's in a database table. I don't use the built in feature of asp.net like Forms authentication and webconfig. My question is, am I doing good?

I check from the database table if a certain user has access to a certain web page and if not I redirect him to another page/ error page informing him/her access denied.

Please let me hear your opinion/advise suggestion if I am doing alright or I should use the built in feature of ASP.NET Forms Authentication.

答:
It's better to use the Built-in feature if you're a new to ASP.NET, but if you're familiar with it, you can write your own authentication procedures. But do understand that those built-in features were tested by many people and they have fixed all(atleast 90%) of the possible vulnerabilities and exploits.

I'm not discouraging you. Just be careful when you're developing on your own.

Hope this helps :)

Title: Access rights through database table


问:
Thread-safe events -- locking on privately held references
I was reading about delegates and events on this webpage to get a better understanding of them and how they relate to each other. While reading, I came across this statement:

That goes against the principle of locking on privately held
  references to avoid accidental deadlocks.

The author was referring to a lock with a reference to this object in the add and remove operations of an event.

Further details weren't provided about the principle he was referring to, maybe because it's supposed to be obvious. In any case, it wasn't obvious to me. Can someone enlighten me on this and provide some more detail?

答:
Well, if you read a few lines further, it seems that certain methods perform a locking operation, but you don't know which object is used for the locking. And that is a very different problem, because you can't lock on the same object if that is what you want to do. All code trying to protect the same data must obviously use the same lock.

As far as the deadlock concerns, yes, that could be a problem. Thread 1 locks on object A, then on object B. Thread 2 locks on object B, then performs an innocent looking operation. That should be fine, right? But if the innocent looking operation locks on object A, you have a deadlock.

What does "privately held" to do with anything? Thread 1 and Thread 2 can only deadlock if the lock the same variable. If "harmless looking operation" locks a variable that is privately held and not accessible to other code, then you won't get into a deadlock.


问:
Using SMS as transaction in offline situations
Currently, I have this hybrid mobile application which talks to my C# web service to do CRUD transactions. As the mobile application is always on the go, and there might not have internet connectivity in all situations.

Therefore, I'm thinking of using SMS transactions in offline mode.

For Login:

Using sms, communicate to server to request for access token.

Token generated and sent using SMS to registered user phone number

User then enter the OTP within 5mins of validity

App will then communicate with server with the OTP, once verified, user will go into a special user interface for offline access instead.

For Transactions:

Phone sends a sms to the 3G Dongle (Unique Session Token, UserID, Type Of Transaction, Transaction Details)

SMS server received sms message

Application which handles sms message, stores message received in a message queue

Application will dequeue message queue and process the oldest message first

There are a few questions in which I would love to have some pointers in:

How do I maintain a unique session using SMS? (Token?)

How do I maintain security? (As in the text message is of course, unreadable by humans, yet can't be duplicated and workable for that transaction only)

I would be doing all of the above by own codes/libraries without using external cloud/web services as it's more for an internal corporation project.

Update:

I'm thinking of using 'counters', where my text message body would have a counter inside it.

For example:
App Counter: 1 Server Counter: 0

1.App sends a transaction request.(App counter: 1)

2.Server decrypts and checks counter. (Since 1 > 0, allow request and increment server counter to 1)

In this case, even there is an duplicate text message sent by user, the message will not process as the counter is now 1. (1 > 1 will return false).

Apart from multiple users accessing the same account and messing up the counters, what concerns should I take note of?

答: Wow! It's good to read your scenario. Hmmm If I may suggest, I aggree with 1.) Unique session via token, a token from your c# app with the mobile number tagged on it. For number 2.) Yes it's achievable based from 1.) checked the mobile number who requested your c# app who's already tagged with token. Even if someone has duplicated token or whatever , you already tagged the original mobile number requested the app. </p>


问:
Angular JS style guide when declaring variables
I'm new to Angular JS and working on a project with "legacy" Angular JS code. The code is about a year or half a year old. I often see stuff like this:

```<code>var _link;
_link = "http://localhost";
</code>```

Or:

```<code>var setup,
    _link;
_link = "http://localhost";
// ...
setup = {
    link: _link
};
return setup;
</code>```

This looks super verbose to me, but the guy who made this did it consistently  through the complete application. Is there any style guide or JavaScript convention for doing this?

I'm a Java developer and one of the first rules I learned was to always declare a variable where it is needed. No idea why it should be different here...

答:
The examples you gave seem unnecessarily verbose to me too.

However there is an important difference between javascript and Java.

In javascript, declarations are hoisted to the beginning of a function regardless of where in the function you place them. Scoping of symbols is different from Java.

```<code>function atest() {
    console.log(a);
    var a = 1;
}
</code>```

Produces 'undefined' in the javascript console, in a browser. a is declared but not initialized.

But

```<code>function atest2() {
    console.log(a);
}
</code>```

Produces an "Uncaught Reference Error" unless there is a property a on the default object, e.g. window.a in a browser.

Maybe your predecessor wanted to remind himself that the declarations are valid from the beginning of the function or script unit / file.

The idea of 'declare it where it is needed' does not work the same as in Java. Curly braces don't, on their own, control scope. A variable declared inside a for loop is visible outside the for loop, for example.

Yet it is still very common to see declarations where a variable is first used, in javascript.

You asked about conventions. There is a coding convention promoted by Crockford to put all declarations at the beginning of the function or file.

"JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function."

From Crockford's Code Conventions

Crockford changed some of his views after he really came to terms with Javascript (see his evolving views on inheritance, for example). I don't know if he changed his views on declarations.

I can say from reading a lot of popular library code that it's not all that common to follow Crockford's advice about declaring at the beginning of a function. I see a lot of declarations at first use, and I think that's mainstream for Javascript today.

Body:
The examples you gave seem unnecessarily verbose to me too.

However there is an important difference between javascript and Java.

In javascript, declarations are hoisted to the beginning of a function regardless of where in the function you place them. Scoping of symbols is different from Java.

function atest() {
    console.log(a);
    var a = 1;
}

Produces 'undefined' in the javascript console, in a browser. a is declared but not initialized.

But

function atest2() {
    console.log(a);
}

Produces an "Uncaught Reference Error" unless there is a property a on the default object, e.g. window.a in a browser.

Maybe your predecessor wanted to remind himself that the declarations are valid from the beginning of the function or script unit / file.

The idea of 'declare it where it is needed' does not work the same as in Java. Curly braces don't, on their own, control scope. A variable declared inside a for loop is visible outside the for loop, for example.

Yet it is still very common to see declarations where a variable is first used, in javascript.

You asked about conventions. There is a coding convention promoted by Crockford to put all declarations at the beginning of the function or file.

"JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function."

From Crockford's Code Conventions

Crockford changed some of his views after he really came to terms with Javascript (see his evolving views on inheritance, for example). I don't know if he changed his views on declarations.

I can say from reading a lot of popular library code that it's not all that common to follow Crockford's advice about declaring at the beginning of a function. I see a lot of declarations at first use, and I think that's mainstream for Javascript today.


答:
Simple answer: why not?

If you subscribe to the concept that there can be multiple handlers for the same event, then why wouldn't you want the least verbose option?

I know I'm on extremely thin ice disagreeing with C# god Eric Lippert, but it has always seemed very natural syntax to me. If your usual language of choice is Python or another language I can see how this might be less so.

However, I do take his point that it does kind of stick out. I can't think of anywhere else in the language where you're forced to use this syntax.


问:
Switch form paragraph mode to line break mode in WYSIWYG editor because of client request?
I'm building a website fro a client which uses TinyMCE as the main WYSIWYG editor. Now my client asked if it is possible to write a line and make a line break and then continue without leaving  a space between the text before and after the line break (e.g. just like in word).

I told him that the web uses paragraph for formatting and not line breaks. Still he'd like to use line breaks for formatting. Should I convince him not to use line breaks for formatting or should I just switch TinyMCE to line break mode (which the is not recommended in the TinyMCE documentation).

答:
Why not just set the CSS for
 tags for the areas of the site you are concerned with so that they have no margin or padding?

```<code>.mycontent p{
    margin:0;
    padding:0;
}
</code>```

Body:
Why not just set the CSS for <p> tags for the areas of the site you are concerned with so that they have no margin or padding?

.mycontent p{
    margin:0;
    padding:0;
}


问:
Why would you store an enum in DB?
I've seen a number of questions, like this, asking for advice on how to store enums in DB. But I wonder why would you do that. So let's say that I have an entity Person with a gender field, and a Gender enum. Then, my person table has a column gender.

Besides the obvious reason of enforcing correctness, I don't see why I would create an extra table gender to map what I already have in my application. And I don't really like having that duplication.

答:
Depends also on who access the data. If you just have one application that might be fine. If you add in a data warehouse or a reporting system. They will need to know what that code means, what is the human redable version of the code.

Usually, the type table wouldn't be duplicated as an enum in the code. You could load the type table in a list that is cached.

```<code>Class GenderList

   Public Shared Property UnfilteredList
   Public Shared Property Male = GetItem("M")
   Public Shared Property Female = GetItem("F")

End Class
</code>```

Often, type come and goes. You would need a date for when the new type was added. Know when a specific type was removed. Display it only when needed. What if a client want "transgender" as a gender but other clients don't? All of this information is best stored in the database.

Title: Why would you store an enum in DB?

Body:
Depends also on who access the data. If you just have one application that might be fine. If you add in a data warehouse or a reporting system. They will need to know what that code means, what is the human redable version of the code.

Usually, the type table wouldn't be duplicated as an enum in the code. You could load the type table in a list that is cached.

Class GenderList

   Public Shared Property UnfilteredList
   Public Shared Property Male = GetItem("M")
   Public Shared Property Female = GetItem("F")

End Class

Often, type come and goes. You would need a date for when the new type was added. Know when a specific type was removed. Display it only when needed. What if a client want "transgender" as a gender but other clients don't? All of this information is best stored in the database.


答: I would create a Genders table for the reason that it can be used in data analysis.  I could look up all the Male or Female Persons in the database to generate a report.   The more ways you can view your data, the easier it will be to discover trending information.  Obviously, this is very simple enumeration, but for complex enumerations (like the countries of the world, or states), it makes it easier to generate specialized reports.</p>

Title: Why would you store an enum in DB?

Body:
I've seen a number of questions, like this, asking for advice on how to store enums in DB. But I wonder why would you do that. So let's say that I have an entity Person with a gender field, and a Gender enum. Then, my person table has a column gender.

Besides the obvious reason of enforcing correctness, I don't see why I would create an extra table gender to map what I already have in my application. And I don't really like having that duplication.


答:
In C#, you have fields and you also have properties, which are basically encapsulated fields. Properties are commonly implemented using fields (and the language has a shortcut to do it succinctly), but they don't have to be.

So, you can write both:

```<code>o.Field = 42;
o.Property = 42;
</code>```

But the latter actually compiles to a call to a setter method:

```<code>o.set_Property(42);
</code>```

Another difference between fields and properties is that properties don't allow some operations, like using ref.

It's similar with delegates and events: events are encapsulated delegate fields. Events are commonly implemented using delegate fields (and the language has a shortcut to do it succinctly), but they don't have to be.

Also, you can write both:

```<code>o.DelegateField += Handler;
o.Event += Handler;
</code>```

But the latter actually compiles to a call to an adder method:

```<code>o.add_Event(Handler);
</code>```

Another difference is that events don't allow you most operations, like assigning or invoking them (with the exception of invoking field-like events from within the declaring class itself).

So, now the question is: why can you use += with delegate fields? It's because you can use + to combine delegates. This means that o.DelegateField += Handler; is just a shorthand for o.DelegateField = o.DelegateField + Handler;.

With events, you can't read or assign to them, so the shorthand += syntax is the only option.

Body:
In C#, you have fields and you also have properties, which are basically encapsulated fields. Properties are commonly implemented using fields (and the language has a shortcut to do it succinctly), but they don't have to be.

So, you can write both:

o.Field = 42;
o.Property = 42;

But the latter actually compiles to a call to a setter method:

o.set_Property(42);

Another difference between fields and properties is that properties don't allow some operations, like using ref.

It's similar with delegates and events: events are encapsulated delegate fields. Events are commonly implemented using delegate fields (and the language has a shortcut to do it succinctly), but they don't have to be.

Also, you can write both:

o.DelegateField += Handler;
o.Event += Handler;

But the latter actually compiles to a call to an adder method:

o.add_Event(Handler);

Another difference is that events don't allow you most operations, like assigning or invoking them (with the exception of invoking field-like events from within the declaring class itself).

So, now the question is: why can you use += with delegate fields? It's because you can use + to combine delegates. This means that o.DelegateField += Handler; is just a shorthand for o.DelegateField = o.DelegateField + Handler;.

With events, you can't read or assign to them, so the shorthand += syntax is the only option.


答:
It's almost certain that your colleague was bitten by a hoisting bug and decided to over-compensate.

My mom always cut off the ends of her pot roast before she seasoned it and put it in the oven. When I asked her why, she said that's the way her mom did it. So I asked my grandma what trimming the roast adds to the dish. She wasn't sure, but said it was important to do before you rubbed it down with spices. That's what her mother did, she said. The next time I saw my great grandma I asked her. She explained, "Yes. I had a small pot when your PawPaw and I were first married. I had to cut off the ends of the roast so that it would fit."

This code is your roast. Good thing you saw fit to ask questions and stop cutting off the ends for no good reason.

To my mind, no variable declarations at all is preferable:

```<code>// Forget all the setup and _link nonsense.
return {
    link: "http://localhost"
};
</code>```

Be sure to compare style guides. Then pick and choose what works best for your team:

Google

Airbnb

jQuery

While you're at it, consider John Papa's and Todd Motto's Angular style guides.

John Papa (Angular Team Endorsed)

Todd Motto

Just remember, nothing beats common sense when it comes to coding styles.

Title: Angular JS style guide when declaring variables

Body:
I'm new to Angular JS and working on a project with "legacy" Angular JS code. The code is about a year or half a year old. I often see stuff like this:

```<code>var _link;
_link = "http://localhost";
</code>```

Or:

```<code>var setup,
    _link;
_link = "http://localhost";
// ...
setup = {
    link: _link
};
return setup;
</code>```

This looks super verbose to me, but the guy who made this did it consistently  through the complete application. Is there any style guide or JavaScript convention for doing this?

I'm a Java developer and one of the first rules I learned was to always declare a variable where it is needed. No idea why it should be different here...

Body:
It's almost certain that your colleague was bitten by a hoisting bug and decided to over-compensate.

My mom always cut off the ends of her pot roast before she seasoned it and put it in the oven. When I asked her why, she said that's the way her mom did it. So I asked my grandma what trimming the roast adds to the dish. She wasn't sure, but said it was important to do before you rubbed it down with spices. That's what her mother did, she said. The next time I saw my great grandma I asked her. She explained, "Yes. I had a small pot when your PawPaw and I were first married. I had to cut off the ends of the roast so that it would fit."

This code is your roast. Good thing you saw fit to ask questions and stop cutting off the ends for no good reason.

To my mind, no variable declarations at all is preferable:

// Forget all the setup and _link nonsense.
return {
    link: "http://localhost"
};

Be sure to compare style guides. Then pick and choose what works best for your team:

Google

Airbnb

jQuery

While you're at it, consider John Papa's and Todd Motto's Angular style guides.

John Papa (Angular Team Endorsed)

Todd Motto

Just remember, nothing beats common sense when it comes to coding styles.


答:
While it is still clearly a matter for debate among the community, Alex revealed a comment left by Brian Goetz, Java Language Architect at Oracle, which I believe is the definitive canonical answer to this question. I've copied his comments below, emphasis mine:

The EG discussed this in some detail and concluded that it was better
  to coopt Runnable than to create the opportunity for confusion
  because there were two competing abstractions. In a perfect world, we
  might have rewritten the Javadoc to reflect that its use had (long
  ago) become broader than was imagined in 1995, but the reality is that
  well before 2014 it became broadly understood that Runnable was the
  JDK's primary "task" abstraction, regardless of its connection with
  threads.


问:
How can one demonstrate client site website content after the sites have been updated?
I currently work for a web design and development company and for the past couple of months I have developed over 10 websites and about 2/3s are live on the web. now most of these websites were for clients who were getting and update to their original website which were already developed by my employer in previous years and in my previous job before I was made redundant there was talk about the company's website (which I worked on) being replaced.

Now I want to show these sites off as apart of my portfolio and I have already taken screenshots of the sites. but the problem is that there is some Client Side content like JavaScript and CSS effects I want to show off which can't be captured with a single image (ie. transitions, mobile responsive menus, JavaScript slideshows, etc.) and since the sites are bound to change a screenshot and a description may not be enough.

I did think of the Wayback Machine and using a link from there but one of the sites I worked on hasn't been crawled since April it has clearly been up updated and I don't know when it'll next be crawled with the new design and ideally I would like some sort of way to preserve my work. So is there a reliable way to preserve a website's client site content for the purpose of a portfolio?

答:
Screenshots are great for an overall impression, like you mention. If you want to show off your JavaScript and CSS chops, do the hard work and distill each difficult/interesting piece into its own stand-alone example and present it on your portfolio site. Examples:

a CSS-only menu

an interesting drag-drop mechanism

lavish responsive behavior

It's a lot of work to do something you've already done again, but I assure you it's worth it. Why? Well, there are a few reasons:

Extracting an example demonstrates your absolute mastery over the technique. If you do it once, it may only work because of many hours of frustration and resolve (and help from teammates). If you do it twice, the second time effortlessly, it shows you're a master.

It's easier for clients to understand some things in isolation. Did you build a complicated widget using <canvas> and localStorage? It's likely the client won't even notice among all of the other distractions on a production-quality site. People are easily distracted. When you extract key features, it helps them focus on what you find important.

Showing a client another client's site is a mixed bag. On one hand, the new client is fairly sure you can do what they want because it seems like you've done it before. Unless you're taking credit for other people's work... and oh, look at this... Sarah, did you see this?... we haven't even considered that...

So yeah, the downside of sharing client work is that it sometimes creates a premature "solution". The new client immediately starts viewing their problems through the lens of an existing site. That can end very badly if it's not what they need. Help them understand what you're truly capable of without showing a complete solution that isn't their solution.

Anyway, it's a lot of work. No doubt about it. But if you're serious about being taken seriously and being in demand, you owe it to yourself. Badasses do the hard work.


答:
I can't believe people didn't mention this yet.

Foreign Keys

By keeping the enum in your database, and adding a foreign key on the table that contains an enum value you ensure that no code ever enters incorrect values for that column. This helps your data integrity and is the most obvious reason IMO you should have tables for enums.

Title: Why would you store an enum in DB?


问:
Falsy values vs null, undefined, or empty string
I've worked with jQuery over the years. However, recently, I've found myself getting deeper into the JavaScript language. Recently, I've heard about "truthy" and falsey values. However, I don't fully understand them. Currently, I have some code that looks like this:

```<code>var fields = options.fields || ['id', 'query'];
</code>```

I need to identify if fields is null, undefined, or has a length of 0. I know the long way is to do:

```<code>if ((fields === null) || (fields === undefined) || (fields.length === 0)) {
 ...
}
</code>```

My question is, is the following the same:

```<code>if (!fields)  {
 ...
}
</code>```

答:
You can try (!! fields) if the fields element is null, undefined or has a length of 0 it would return true. Or (!!! fields) then this would return true.

the double ! or !! will force true or false.
I wish I can find a good definition for this but I don't seem to be able to find it again.


问:
Better way of storing key-value pairs in the database?
I have a C#/SQL Server program that sometimes needs to store data. The data could be a response from a web service, a result of a database query, or any number of other things. There's no way of knowing before the data is stored how many fields it might have or what the data structure might be. We have this kind of painful table we're using for this... four columns and lots of rows. An example of the data might be easier than an explanation.

```<code>InstanceID RowID PropertyName PropertyValue
1          1     Property1    Value1
1          1     Property2    Value2
1          1     Property3    Value3
1          2     Property1    Value1
1          2     Property2    Value2
1          2     Property3    Value3
2          1     OtherProp1   Value1
2          1     OtherProp2   Value2
2          2     OtherProp1   Value1
2          2     OtherProp2   Value2
</code>```

These values will then be pulled back and fed into a dictionary object, which can be updated, then the fields will be fed back into the database. This can be painful to code against, and also requires a lot of inserts which can make it very slow.

I can't think of a better way of doing this, but I feel like there must be one. Any advice?

答:
I have a number of applications that use/store data in a similar manner.  I'm not sure exactly where your "pain" is coming from in this instance as it's usually a fairly simple model to follow.

One thing that may help is creating a custom table datatype in SQL that has Name and Value fields.  Then calling your stored proc you can simply pass something like InstanceID, RowID, and a table of your custom type containing x number of name-value pairs.

This makes the interface for your calls consistent regardless of what is actually getting passed.

Something else to potentially look at may be creating static objects in a class to cache that.  Manage it through methods in that class, and provide async calls to SQL to keep it updated if need be.


问:
Workaround for implementing operations on doubly linked or circular data structures in languages with immutable data
I would like to learn how to make graphs and perform some local operations on them in Haskell, but the question is not specific to Haskell, and instead of graphs we may consider doubly linked lists.

Question: What would be an idiomatic or recommended way to implement a doubly linked list (or other doubly linked or circular data structure) and operations on it in a language that mainly supports and advocates for immutable data structures (Haskell, Clojure, etc.)?  In particular, how to use in-place updates, which are formally forbidden by the language?

I can easily imagine that if some local operation is performed on a doubly linked list (if an item is inserted, for example), there may be no need to copy the entire list immediately due to the laziness of the language.  However, since the list is doubly linked, if it is modified in one place, none of the old nodes can be used in the new version of the list, and they would need to be somehow marked, copied, garbage-collected sooner or later.  Obviously these are redundant operations if only the updated copy of the list shall be used, but they would add an "overhead" proportional to the size of the list.

Does this mean that for such tasks immutable data is simply inappropriate, and functional declarative languages without "native" support for mutable data are not as good as imperative ones?  Or, is there some tricky workaround?

P.S. I have found some articles and presentations on this subject in the Internet but had hard time following them, while i think that the answer to this question should not take more than one paragraph and maybe a diagram...  I mean, if there is no "functional" solution to this problem, the answer probably is "use C".  If there is one, then how complicated can it be?

Related questions

"Data structures in functional programming".
My specific question about using in-place updates instead of inefficient alternatives is not discussed there.

"Internal Mutation of Persistent Data Structures".
There the emphasis seems to be on low-level implementation in an unspecified language, while my question is about the right choice of a language (functional or otherwise) and about possible idiomatic solutions in functional languages.

Relevant quotations

Purely functional programming languages allow many algorithms to be expressed very concisely, but there are a few algorithms in which in-place updatable state seems to play a crucial role.  For these algorithms, purely-functional languages, which lack updatable state, appear to be inherently inefficient ([Ponder, McGeer and Ng, 1988]).

-- John Launchbury and Simon Peyton Jones, Lazy functional state threads (1994), also John Launchbury and Simon Peyton Jones, State in Haskell (1995).  These papers introduce ST monadic type constructor in Haskell.

答:
There could be other efficient immutable data structures that fit your particular task, but are not as general as a doubly-linked list (which is unfortunately prone to concurrent modification bugs due to its mutability). If you specify your problem more narrowly, such a structure can probably be found.

The general answer for (relatively) economic traversing of immutable structures is lenses.  The idea is that you can keep just enough information to reconstruct a modified immutable structure from its unmodified parts and the currently modified piece, and navigate over it to a neighboring node.

Another useful structure is a zipper. (The funny part is that the type signature for a <s>lens</s> zipper is a school-math derivative of a type signature of the structure.)

Here are a few links.

A simple explanation of zippers

A chapter on zippers from from "Learn you a Haskell"

Introduction to lenses in Scala (slides)

Basic Lensing

Lenses in Functional Programming


问:
What makes a language Turing-complete?
What is the minimal set of language features/structures that make it Turing-complete?</p>

答:
A system can only be considered to be Turing complete if it can do anything a universal Turing machine can. Since the universal Turing machine is said to be able to solve any computable function given time, Turing complete systems can, by extension, also do so.

To check to see if something is Turing complete, see if you can implement a Turing machine inside it. In other words, check to see if it can simulate the following:

The ability to read and write "variables" (or arbitrary data): Pretty much self explanatory.

The ability to simulate moving the read/write head: It isn't enough to just be able to retrieve and store variables. It must also be possible to simulate the ability to move the tape's head in order to reference other variables. This can often be simulated within programming languages with the usage of array data structures (or equivalent) or, in the case of certain languages such as machine code, the ability to reference other variables through the use of "pointers" (or equivalent).

The ability to simulate a finite state machine: Although not mentioned often, Turing machines are actually a variation of the finite state machines often used within AI development. Alan Turing said the purpose of the states is to simulate a person's "various modes of problem solving".

A "halt" state: Although it's often mentioned a set of rules must be able to repeat itself in order to count as being Turing complete, that isn't really a good criteria since the formal definition of what an algorithm is state algorithms must always eventually conclude. If they can't conclude in some way, either it isn't Turing complete, or said algorithm isn't a computable function. Turing complete systems that technically can't conclude due to the way they work (like game consoles, for example) get around this limitation by being able to "simulate" a halting state in some fashion. Not to be confused with the "halting problem", an undecidable function that proves it's impossible to build a system that could detect with 100% reliability if a given input will cause another system to not conclude.

These are the true minimum requirements for a system to be considered Turing complete. Nothing more, nothing less. If it can't simulate any of these in some fashion, it's not Turing complete. The methods other people proposed are only means to the end as there's several Turing complete systems that doesn't have those features.

Note that there's no known way to actually build a true Turing complete system. This is because there's no known way to genuinely simulate the limitlessness of the Turing machine's tape within physical space.

Title: What makes a language Turing-complete?


问:
Should I use HTTP status codes to describe application level events
Several servers I have dealt with will return HTTP 200 for requests that the client ought to consider a failure, with something like 'success : false' in the body.

This does not seem like a proper implementation of HTTP codes to me, particularly in cases of failed authentication. I have read HTTP error codes pretty succinctly summed up as, '4xx' indicates that the request should not be made again until changed, while '5xx' indicates that the request may or may not be valid and can be retried, but was unsuccessful. In this case 200: login failed, or 200: couldn't find that file, or 200: missing parameter x, definitely seem wrong.

On the other hand, I could see the argument being made that '4xx' should only indicate a structural issue with the request. So that is proper to return 200: bad user/password rather than 401 unauthorized because the client is permitted to make the request, but it happens to be incorrect. This argument could be summarized as, if the server was able to process the request and make a determination at all, the response code ought to be 200, and it's up to the client to check the body for further information.

Basically, this seems to be a matter of preference. But that is unsatisfying, so if anyone has a reason why either one of these paradigms is more correct, I would like to know.

答:
This question is a bit opinion based, but either way.

The way i see it, 200 can serve "soft errors". When it comes to building API's i try to distinguish between these and "hard errors".

"Soft errors" will be served with a status code of 200, but will contain an error description and a success status of false. "Soft errors" will only occur when the result is "as expected", but not a success in the strictest sense.

It's important to note that "soft errors" are more of a hint to the implementer. Therefor it is important to also provide more information about the error such as a human-readable error message and/or some sort of code that can be used to provide the end-user with feedback. These errors provide the implementer (and end-user) with more information about what happened on the server side of things.

For instance say you have an API with a search function but during a search, no results are yielded. This is not erroneous, but it's not a "success" either, not in the strictest sense of the definition.

Example formatted as JSON:

```<code>{
    "meta" {
        "success": false,
        "message": "Search yielded no results",
        "code": "NORESULTS"
    }
    "data": []
}
</code>```

"Hard errors" on the other hand, will be served with a status code which is recommended for the error. User not logged in? – 403 / 401. Malformed input? – 400. Server error? – 50X. And so on.

Again, it's a bit opinion-based. Some people want to treat all errors equally, "hard error" everything. No search results? That's a 404! On the other side of the coin, no search results? – This is as expected, no error.

Another important factor to take into consideration is your architecture, for instance; if you interact with your API using JavaScript XHR requests and jQuery or AngularJS. These "hard errors" will have to be handled with a separate callback, whereas the "soft errors" can be handled with the "success"-callback. Not breaking anything, the result is still "as expected". The client-side code may then look at the success-status and code (or message). And print that to the end-user.

Body:
This question is a bit opinion based, but either way.

The way i see it, 200 can serve "soft errors". When it comes to building API's i try to distinguish between these and "hard errors".

"Soft errors" will be served with a status code of 200, but will contain an error description and a success status of false. "Soft errors" will only occur when the result is "as expected", but not a success in the strictest sense.

It's important to note that "soft errors" are more of a hint to the implementer. Therefor it is important to also provide more information about the error such as a human-readable error message and/or some sort of code that can be used to provide the end-user with feedback. These errors provide the implementer (and end-user) with more information about what happened on the server side of things.

For instance say you have an API with a search function but during a search, no results are yielded. This is not erroneous, but it's not a "success" either, not in the strictest sense of the definition.

Example formatted as JSON:

{
    "meta" {
        "success": false,
        "message": "Search yielded no results",
        "code": "NORESULTS"
    }
    "data": []
}

"Hard errors" on the other hand, will be served with a status code which is recommended for the error. User not logged in? – 403 / 401. Malformed input? – 400. Server error? – 50X. And so on.

Again, it's a bit opinion-based. Some people want to treat all errors equally, "hard error" everything. No search results? That's a 404! On the other side of the coin, no search results? – This is as expected, no error.

Another important factor to take into consideration is your architecture, for instance; if you interact with your API using JavaScript XHR requests and jQuery or AngularJS. These "hard errors" will have to be handled with a separate callback, whereas the "soft errors" can be handled with the "success"-callback. Not breaking anything, the result is still "as expected". The client-side code may then look at the success-status and code (or message). And print that to the end-user.


答:
First - deadlocks. This is when you have one thread inside a lock, trying to lock something else, and that something else is locked by another thread waiting for the lock that the original thread had. They just sit there waiting for the other thread to finish, but neither can. Bad times.

The issue is that each instance of an object can serve as the context of a lock. By locking on private instances, you're (reasonably) assured that only code in that class can lock on that instance, so you can limit your analysis to see if that code can deadlock.

By locking on this, code outside of the class could also lock on that instance, making it much more difficult to figure out potential deadlock scenarios in your codebase, and impossible once you consider external consumers of your code.

That said, I find this best practice to be a bit of a cargo cult. Manual locking of variables is decreasingly common, and very often the need to lock is around a class scope. Making a new object just to lock on it is unintuitive and very often overkill.

Still, it is very important to understand why this sort of thing is done for those times when it is not overkill.

Title: Thread-safe events -- locking on privately held references

Body:
I was reading about delegates and events on this webpage to get a better understanding of them and how they relate to each other. While reading, I came across this statement:

That goes against the principle of locking on privately held
  references to avoid accidental deadlocks.

The author was referring to a lock with a reference to this object in the add and remove operations of an event.

Further details weren't provided about the principle he was referring to, maybe because it's supposed to be obvious. In any case, it wasn't obvious to me. Can someone enlighten me on this and provide some more detail?


问:
Handling Value Unit data
We have some data that is strongly bound to each other and we are using it for calculations. Its a value with a unit type and an optional relation.
E.g. 1500 meter above sea level.
The unit type should be replaceable (meter to foot). But the value should be converted accordingly.

I am currently thinking of two approaches:

Approach 1 saves the value in a fixed unit to the database without an conversion. The conversion would be made on the fly after loading the value with its prefered unit type.
e.g. always saved in meter, but will be displayed in foot if the unit was changed
+ This prohibits problems from converting the value back and forth while causing rounding errors.
+ Calculations with the data can be done without converting it, since the saved value is always in meter
- If you enter a value in foot but save it as meter and reload it, it could show not the value you entered because of a rounding error.

Approach 2 saves the value in the selected unit. But that switches the advantages with the disadvantages. And it would make it probably hard to choose a good databasetype for saving it since the unit is not always the same.

I tried to find how other people work with this kind of relation but since "unit" is a pretty strong word i can't find anything related to my problem.
But I think this value/unit data structure is not so rare.

How should I approach this kind of data?

How should I save and load it?

When should I convert the data?

Am I missing some problems that could influence my decision?

答:
Store the unit and the value separately, do not perform conversion unless it is necessary (eg. calculating weight for shipping, the user requests it, etc.).

Not all units can be converted from one to another

Consider an database for a grocery store.  All of the products they sell have a specific measurement, but not the same type of measurement.

Most goods are labeled by weight (2 lb)

Liquids are labeled by volume (500 ml)

Cookware is labeled in length (9x9x3 inches for a jellyroll pan, but 9 inches in diameter for a skillet)

Google won't even try to convert between weight and volume units (at least not in a general way, you'd need a conversion table for every type of product).

Users may prefer one type of unit over another in specific contexts

Even in cases where all of your units can be converted from one to another, there are plenty of cases where specific units are customary for certain types of data.  For smaller quantities, a smaller unit is usually preferred.  The same is true for larger quantities and larger units.

At the fabric store, I'll buy fabric by the yard (Imperial) or meter (Metric), but I expect my buttons to be labeled in fractions of an inch or millimeters (the same is true for lumber and nails at the hardware store)

Even in countries that are fully metric or fully Imperial, you'll find edge cases like 2L bottles of pop in the U.S. or recipes in Canada that use cups and tablespoons

The deli counters here in Canada usually label their products by 100 grams (I guess the hectogram never caught on?) while other products within the same store that are measured by weight will use kilograms

Title: Handling Value Unit data