答:
I think the problem is that you are a bit unclear on what is meant by a side effect. In a pure function with no side effects, the function gives a result that is a direct result of the input and nothing else. In a function with side effects, the function depends on or changes the state of the outside world. So if you have a function like square(x), then that is a pure function. On the other hand, if you have function like launch_the_missiles(), then that has a very real side effect (or for a more mundane example, print a page).

So doing IO changes the state of the world, that is the side effect

Title: How can IO cause side effects in Functional Programming?

Body:
Whenever I read about Haskell, I find that IO can cause side effects.

But I do not understand how it would do it?

Do we mean that we are writing to a file from one lazy sequence and another lazy sequence is reading from same file?

Is that the only possibility or is there something fundamentally deep?


问:
How can IO cause side effects in Functional Programming?
Whenever I read about Haskell, I find that IO can cause side effects.

But I do not understand how it would do it?

Do we mean that we are writing to a file from one lazy sequence and another lazy sequence is reading from same file?

Is that the only possibility or is there something fundamentally deep?

答:
The Haskell optimizer is allowed to freely manipulate calls to pure functions as long as the result remains the same. For example, if it can see that you are calling sqrt on the same number 100 times, it can cache the returned value and only call it once. If it can see that you never actually use the result of that function, it can choose to not call it at all.

These things can't be done with IO. If you read from stdin 100 times, you wouldn't want to optimizer to cache the first read and reuse that value 99 more times. If you write to the console and discard the return value (because you don't actually care about the return value of putStrLn) you wouldn't want the optimizer to remove the function call altogether.

That's the meaning of side effects - not from the programmer's point of view (the programmer clearly meant for these things to happen) but from the optimizer's point of view.

ContentLicense: CC BY-SA 3.0


问:
Exceptions: What to handle, what to throw
I have a custom configuration reader which performs various functions on top of .NET's CloudConfigurationManager and ConfigurationManager implementations, such as caching, type conversion, etc.

The following method is used to retrieve a configuration item:

```<code>public T GetSetting<T>(string key)
{
    string value = GetSetting(key);

    return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
</code>```

There are a few failure points for which I want to add the correct exception handling.

GetSetting<T> with exception handling:

```<code>public T GetSetting<T>(string key)
{
    // If the key is null or empty
    if (String.IsNullOrWhiteSpace(key))
    {
        throw new ArgumentNullException(String.Format("Configuration value with key '{0}' cannot be null or empty", key));
    }

    string value = GetSetting(key);

    // If the value does not exist in the underlying configs
    if(value == null)
    {
        throw new ArgumentOutOfRangeExcetion(String.Format("Configuration value with key '{0}' does not exist", key));
    }

    try
    {
        return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
    }
    catch(InvalidCastException ex)
    {
        throw new ArgumentOutOfRangeException(String.Format("Configuration value with key '{0}' could not be converted: Conversion not supported.", key), ex);
    }
    catch (FormatException ex)
    {
        throw new ArgumentOutOfRangeException(String.Format("Configuration value with key '{0}' could not be converted: Format error.", key), ex);
    }
}
</code>```

My questions and concerns:

If the key is null or empty:

Is it acceptable to throw an ArgumentNullException when the string parameter is not only null, but also empty?  Perhaps a ArgumentException is better as this is more general issue than just null checking.

If the value does not exist in the underlying configs:

An ArgumentOutOfRangeException is generally used for a index which doesn't exist in list- or dictionary-based collection.  Does it apply here?  The configs are essentially key value pair dictionaries.

An idea is that the method can just return null, but I have provided a HasSetting(string) method for this reason.  In my opinion, the more explicit the better.  Checking for null in client code requires implicit understanding of the encapsulated functionality, which can often be misused, misread and misunderstood.

If parsing to T fails for whatever reason:

This is the tricky one.  Which is the best exception type to encapsulate the 'conversion' exceptions?  Should I let the underlying exceptions from Convert.ChangeType() bubble up?

Convert.ChangeType() overflow exception:

I see no reason to handle the OverflowException in Convert.ChangeType().  I will just let this throw.

For reference reasons, these are the exceptions thrown from Convert.ChangeType():

```<code>// Exceptions:
//   System.InvalidCastException:
//     This conversion is not supported. -or-value is null and conversionType is
//     a value type.-or-value does not implement the System.IConvertible interface.
//
//   System.FormatException:
//     value is not in a format for conversionType recognized by provider.
//
//   System.OverflowException:
//     value represents a number that is out of the range of conversionType.
//
//   System.ArgumentNullException:
//     conversionType is null.
</code>```

答:
Is it acceptable to throw an ArgumentNullException when the string parameter is not only null, but also empty? Perhaps a ArgumentException is better as this is more general issue than just null checking.

Yes, I think that ArgumentException fits best here. I guess the "proper" solution would be to throw ArgumentNullException for null and ArgumentException for empty, but I don't think that's worth it.

An ArgumentOutOfRangeException is generally used for a index which doesn't exist in list- or dictionary-based collection. Does it apply here? The configs are essentially key value pair dictionaries.

ArgumentOutOfRangeException is not used for dictionaries. For example, the indexer of Dictionary throws KeyNotFoundException. I think you should use that, especially since you don't really have any range here.

An idea is that the method can just return null, but I have provided a HasSetting(string) method for this reason.

Can the configuration change between the call to HasSetting() and GetSetting()? If it can, consider adding something like bool TryGetSetting<T>(string key, out T item), so that an item that may not be present can be retrieved safely without exception handling.

But I agree that checking for null is usually not a good idea.

If parsing to T fails for whatever reason

ArgumentOutOfRangeException is even less appropriate here. If you don't find any built-in exception that fits, create a custom exception class and throw that.


答:
Side effects mean that, after every IO operation, the state of the system may be changed. Haskell provides a clear divide pure Haskell code and IO code.

See : http://learnyouahaskell.com/input-and-output#hello-world ;

from the book: "In Haskell, a function can't change some state, like changing the contents of a variable (when a function changes state, we say that the function has side-effects). "


问:
Domain Model, validation, and pushing errors to the model
Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags.  That said how do you handle pieces of validation that require a trip to the database?

For example, you have an domain object that represent categories for a blogging engine.

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```

<p>From a developer's perspective, you could create an empty category, but this isn't valid in the business world.  A <code>Category</code> <strong>requires</strong> a Name to be a valid category, therefore we end up with:</p>

<pre class="lang-cs prettyprint-override"><code>public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Category(string name)
    {
        Name = name;
    }
}
</code>```

Now, a Category can't be created without a name.  But, we can't have duplicate Category names either, that would just cause confusing and redundancy.  I don't want the entity to handle it themselves because this would end up more of an Active Record Pattern and I don't want the model to be "self-aware/persisting" so to speak.

So to this point, where should this validation take place.  It is important that if the user types an duplicate Category, we would notify the user of this.  Should there be a "service" layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?

Someone please set me straight because I really like where DDD is going, I just can't make all the connections to get there myself.

答:
Q:How do we create objects?
A: Using Domain Factories!

Since the creation of a category contains complex logic (we need to validate uniqueness), we will utilize a domain factory to create the object for us.

Inside that factory I'll use a UniqueCategoryNameValidator service that calls into the data-store (a DB in ur case) and check if the category is unique. Some people might refer to this approach as using the specification pattern as follows:

```<code>UniqueCategoryNameSpecification.isSatisfiedBy(category);
</code>```

Using a specification makes the check for uniqueness explicit in your domain. The specification would use an infrastructure service to query the database.

Body:
Q:How do we create objects?
A: Using Domain Factories!

Since the creation of a category contains complex logic (we need to validate uniqueness), we will utilize a domain factory to create the object for us.

Inside that factory I'll use a UniqueCategoryNameValidator service that calls into the data-store (a DB in ur case) and check if the category is unique. Some people might refer to this approach as using the specification pattern as follows:

UniqueCategoryNameSpecification.isSatisfiedBy(category);

Using a specification makes the check for uniqueness explicit in your domain. The specification would use an infrastructure service to query the database.


问:
OOD: Java inheritance and access to child methods via casting
I have several classes Parent and Child1 ... Child9 implemented in Java. Parent is an abstract class, containing all the common variables of the child classes (a lot, which is the main reason why I made Parent an abstract class and not an interface), some abstract and some implemented methods.

Some of the child classes have custom methods which are specific to them. So often I find myself calling a child method using downcasting:

```<code>Parent p = new Child1();
((Child1) p).child1SpecificMethod();
</code>```

Somehow I have the feeling that this is bad OOD practice, but I am not quite sure if that really is the case respectively how to improve the design.

- Edit -
What I probably should change anyway is the fact that I use the Parent class for organizing many (for now) common variables, making them (or a container object) members of the concrete classes.

答:
This is not only bad practice, this is unnecessary complicated.

Why do you use inheritance in general?

When you use inheritance, you have a common set of behaviour, which you want to make available for many different carriers. This includes class inheritance as well als interface inheritance. The heir, so to speak, is oftentimes a specialization of the class from whom it inherits; which is mainly true for class inheritance.

Think of a class car and a subclass porsche (the typical is a-relationship). You have general behaviour like starting/stopping engine, steering and so on. If you treat a porsche like a car, you are bound to this aspect of its behaviour. If you know, that you only want a porsche and only deal with it as a porsche, it is redundant to instantiiate a porsche as a car and get porsche-behaviour via casting.

Polymorphism makes sense the other way around:

You have a porsche and need to treat it from the aspect of a car; e.g. driving

As long as your porsche accepts steer left, steer right, shift up, shift down, etc. you could make use of polymorphism/substitution one for the other.

It is better, to instantiate your objects in their specialized form. Then you could make the most of polymorphism and use it only when you need it.

That said: Parent p = new Child1(); makes no sense for me.

Edit: I would implement porsche different (via composition), but for the sake of the example, it is a car.


答:
business logic should be in the model, otherwise you just have property bags

What is business logic?

Business logic is, that your object knows it's state and could answer questions like order.IsDistributed or order.IsQualityAssuranceDone or the like.
It is no business logic, if you ask the question is this order already in the database. That is a different responsibility: It belongs not to the order itself, since it isn't a state of the order, it is the state of the database. Therefore you should ask the database for that answer.

From a developer's perspective, you could create an empty category, but this isn't valid in the business world

To maintain a clean state, you should use properties (in C#) / getter and setter, where you implement validation-logic, to keep the object's state clean and tidy.

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Category(string name)
    {
        Name = name;
    }
}
```

This design has a big flaw: It mirrors not your requirement exactly of having a name, since the constructor could be called with null, which is not in every sense a valid name. On the other hand, you could use the builder pattern and do the construction via a builder-interface.

Now, a Category can't be created without a name. But, we can't have duplicate Category names either, that would just cause confusing and redundancy.

These are two different concerns. One belongs to the object's state the other to the database's state.

Should there be a "service" layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?

Whether you use a service-layer is up to you. Sometimes it is drowning little puppies to make the indirection. It depends on how much logic is there.

Title: Domain Model, validation, and pushing errors to the model

Body:
Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags.  That said how do you handle pieces of validation that require a trip to the database?

For example, you have an domain object that represent categories for a blogging engine.

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```

<p>From a developer's perspective, you could create an empty category, but this isn't valid in the business world.  A <code>Category</code> <strong>requires</strong> a Name to be a valid category, therefore we end up with:</p>

<pre class="lang-cs prettyprint-override"><code>public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Category(string name)
    {
        Name = name;
    }
}
</code>```

Now, a Category can't be created without a name.  But, we can't have duplicate Category names either, that would just cause confusing and redundancy.  I don't want the entity to handle it themselves because this would end up more of an Active Record Pattern and I don't want the model to be "self-aware/persisting" so to speak.

So to this point, where should this validation take place.  It is important that if the user types an duplicate Category, we would notify the user of this.  Should there be a "service" layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?

Someone please set me straight because I really like where DDD is going, I just can't make all the connections to get there myself.

Body:
business logic should be in the model, otherwise you just have property bags

What is business logic?

Business logic is, that your object knows it's state and could answer questions like order.IsDistributed or order.IsQualityAssuranceDone or the like.
It is no business logic, if you ask the question is this order already in the database. That is a different responsibility: It belongs not to the order itself, since it isn't a state of the order, it is the state of the database. Therefore you should ask the database for that answer.

From a developer's perspective, you could create an empty category, but this isn't valid in the business world

To maintain a clean state, you should use properties (in C#) / getter and setter, where you implement validation-logic, to keep the object's state clean and tidy.

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Category(string name)
    {
        Name = name;
    }
}

This design has a big flaw: It mirrors not your requirement exactly of having a name, since the constructor could be called with null, which is not in every sense a valid name. On the other hand, you could use the builder pattern and do the construction via a builder-interface.

Now, a Category can't be created without a name. But, we can't have duplicate Category names either, that would just cause confusing and redundancy.

These are two different concerns. One belongs to the object's state the other to the database's state.

Should there be a "service" layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?

Whether you use a service-layer is up to you. Sometimes it is drowning little puppies to make the indirection. It depends on how much logic is there.


问:
Order of Operations Annoyance
In most programming languages (C#, JavaScript, Java) the order of operations precedence has that equality comparison come BEFORE bitwise comparisons.

This means that if you have a bit operation and an equality comparison on the same line (as in this javascript code):

```<code>if(2 & 15 === 2){
    //do something
}
</code>```

You will get an unexpected result (it evaluates to 0 in JavaScript).
C# throws an error if you try to do this and won't compile.
Java, presumably, throws an error as well (didn't fire it up to check).

It seems to me that the errors and the confusion in JavaScript could be removed completely by simply putting the Equality operators at a lower precedence than the Bitwise operators.

I can't think of an instance where I want to have both a bitwise and an equality operation on the same line AND want to have the equality evaluated first.

Yet every programming language that I've checked shares the same order of operations.

What is the reason for this? Is there a common, legitimate, use that I am missing that makes it easier to have the precedence as designed?

答:
Legacy,

It used to be that in C the non-short circuiting logical operators were the only ones available and then it was logical for them to be after equality.

Later the short circuiting were created and the old precedence rule was never changed in the name of backwards compatibility.

Title: Order of Operations Annoyance


问:
Why do people fork repositories on GitHub?
I noticed that a lot of GitHub accounts only have repositories which are forked from other accounts. In addition the people who do this usually don't make any contributions to the forked repositories.

I've heard of people collecting stamps and seashells, but why would anybody want to collect repositories? Personally I would only fork a repository if I wanted to make some changes to it.

答: I fork a lot of repos that I might want to use the code, or if it's a project I'm interested in. When I want to come back and have another look at the code later, it's easier to find if it's listed under my repositories. I don't have to google, or bumble around trying to remember what the name was exactly or thinking "where did I see that repo about foo again?" If it's among my repos it's easier to be reminded of these things. </p>


问:
Check word density within a document
Here is the situation:
I have a Document(d) and a set of keywords (Set<String> keywords). I like to check the density of each words from set keywords with d.
I have few solution but not really good. for example:
(NOTE the implementation is in java.)

```<code>Map<String,Integer> map
for each word in keywords do :
 d1 = d;
 int count=0;
 while(d1!=null) do:
    int next=firstOccurrenceOF word;
    if(next==-1){
      d1=null;
      continue;
    }
    d1=substring(firstOccurentOf word + word.length, d1.length())
    count++;
 od
 map.put(word,count);
od;
</code>```

This solution works but its very slow if document is big and lots of keywords are needed to be checked.

NOTE: keywords set may contain keywords with multiple words

This is more algorithmic problem rather than programming.

答:
For maximum efficiency, use your set of keywords to create a Pattern, e.g.

```<code>Pattern p = Pattern.compile("circle|ellipse|parabola|hyperbola|conic\s*section");
Matcher m = p.matcher(text)
while (m.find()) { ... }
</code>```

This is about as fast as you can go in Java.

Title: Check word density within a document

Body:
For maximum efficiency, use your set of keywords to create a Pattern, e.g.

Pattern p = Pattern.compile("circle|ellipse|parabola|hyperbola|conic\s*section");
Matcher m = p.matcher(text)
while (m.find()) { ... }

This is about as fast as you can go in Java.


问:
I/O bound or CPU-bound
I have a telephony application, there is a windows service(third party product) running on a remote server. The application runs against the server. To connect the server, we have the code.

```<code>public static TelephonyServer ts;
ts = new TelephonyServer(sIpaddress, "username", "password");
</code>```

TelephonyServer is very complicated.

After getting TelephonyServer instance, now we can get the resource from it in the application. Say:

```<code> m_ChannelResource = m_TelephonyServer.GetChannel();
 m_VoiceResource = m_ChannelResource.VoiceResource; // VoiceResource
</code>```

Remember each telephone call will have its own VoiceResource. Then in the code, I used a thread to make a call. If there are N calls, it will have N threads.

Now in each thread, we dial a number by Dial method then play a string by PlayTTS code.

```<code>public DialResult Dial(string phonenumber)
{
    int num = 1024;
    num += phonenumber.Length * 2;
    byte[] array = this.SerializePropertiesForInvocation();
    num += array.Length;
    VPacket vPacket = new VPacket(this.TelephonyLinkInfo.Guid, num, "ChannelResource.Dial.string.Invoke", 1);
    vPacket.WriteNullableString(phonenumber);
    vPacket.Serialize(array);
    vPacket.DoneWriting();
    byte[] buffer = base.TelephonyServer.ExecuteCommandHelperAsync(vPacket.Buffer, "ChannelResource::Dial()");
    vPacket = VPacket.FromByteArray(buffer, "ChannelResource.Dial.string.Reply");
    int version = vPacket.Version;
    if (version == 1)
    {
           this.DeSerializePropertiesFromReply(VPacket.FromByteArray((byte[])vPacket.Deserialize()));
        vPacket.DoneReading();
        return this.m_DialResult;
    }
    vPacket.DoneReading();
    throw new Exception("ChannelResource::Dial() Wrong Packet Version Received From Invocation.");
}
</code>```

And.

```<code>public PlayTTS(string ttsString, string voice)
{
    int num = 1024;

    this.StopPlayAsync();
    if (ttsString != null && ttsString.Length > 0)
    {
        num += ttsString.Length * 2;
    }
    if (voice != null && voice.Length > 0)
    {
        num += voice.Length * 2;
    }
    byte[] array = this.SerializePropertiesForInvocation();
    num += array.Length;
    VPacket vPacket = new VPacket(this.TelephonyLinkInfo.Guid, num, "VoiceResource.PlayTTS.string.string.Invoke", 1);
    vPacket.WriteNullableString(ttsString);
    vPacket.WriteNullableString(voice);
    vPacket.Serialize(array);
    vPacket.DoneWriting();
    byte[] buffer = base.TelephonyServer.ExecuteCommandHelperAsync(vPacket.Buffer, "VoiceResource::PlayTTS()");
    vPacket = VPacket.FromByteArray(buffer, "VoiceResource.PlayTTS.string.string.Reply");
    int version = vPacket.Version;
    if (version == 1)
    {
        this.DeSerializePropertiesFromReply(VPacket.FromByteArray((byte[])vPacket.Deserialize()));
    vPacket.DoneReading();

    }
    vPacket.DoneReading();
    throw new Exception("VoiceResource::PlayTTS() Wrong Packet Version Received From Invocation.");
}
</code>```

Now I have to face a question that using C# Task or async/await choice in my application. From this article, I heard that using Task or async/await is depend on whether the application is I/O bound or CPU bound.

I am not quite sure the application is I/O bound or CPU bound or some kind of hybrid. Can you give me some advice based on my information?

EDIT: Remove TelephonyServer detail image based on comment.  10/10/2014 12:54pm

答: The only portions of code that are CPU bound in a program are those that contain loops performing lots of calculations on large amounts of data. If you are not writing a game, graphics program, image processing program, or doing complex data analysis or modeling, you are unlikely to have CPU bound code. Any code that uses a network or file system to transfer data frequently is almost surely IO bound.</p>

Title: I/O bound or CPU-bound


问:
Folder structure or database structure for creating/editing 'files'?
As a hobby experiment I am creating a on-line tool for creating web sites with the ability to create custom HTML and CSS using a template engine for safe-use of functionality.

Now I am in the dilemma if I should save the template files in a "customers" folder, and create a tree view of this file structure - or if I should go for adding a new row in the database containing the mark-up and build a tree view from the table?

I will be doing revisions of the file changes, so i am moving more and more towards having the "files" (meta-data) stored in the database, instead of real files on the server, and just glue the pieces together in the presentation layer.

答:
I always prefer files for this purpose, simply because it makes the design easier for others to reuse and test:

There is no need to install or maintain a database.

You can clone or move your "database" simply by cloning or moving the file system.


问:
Using Statement lambda in exception handling
Following is a code snippet from MVP Win Forms application and this explanation would be helpful when answering the questions.

My DAL doesn't handle exceptions and it will be propagated up to the calling method in the presenter classes where the exception will be handled.

I'm using a single handler called ExecutAction(Action action) so I'm catching exceptions in one place rather than repeating code in every method.

At the moment, I'm not logging errors. Just alert the user for an action and try to keep the system alive if possible.

When showing messages to users, Presenters will use a static class called MessagingService. (ShowErrorMessage()). So that I can customize all massage boxes in one place.

```<code>        private void Search()
        {
            ExecutAction(() =>
            {
                var info = _DataService.GetByACNo(_model.AccountNumber);

                    if (info != null)
                    {
                        _Model = info ;
                        this.SetViewPropertiesFromModel(_Model, _View);
                    }
                    else
                    {
                        MessageBox.Show ("Bank account not found");
                    }
                });
            }

            private void ExecutAction(Action action)
            {
                try
                {
                    action();
                }

                catch (NullReferenceException e) { MessagingService.ShowErrorMessage(e.Message); }
                catch (System.Data.SqlTypes.SqlTypeException e) { MessagingService.ShowErrorMessage(e.Message); }
                catch (System.Data.SqlClient.SqlException e) { MessagingService.ShowErrorMessage(e.Message); }
            }
        }
</code>```

Should I include general exception handler to this, to be able to handle any unforeseen exceptions?

Also could you show me a better way to handle showing messages than using a static?

Does use of lambda statements in every method call (ExecutAction(() =>) degrade code readability?

When showing user messages how to show a custom message like "Check the server connection" etc. first and then if the user wants more information (like StackTrace / technical details) he /she could press a button like More Info which is in the MessageBox dialog?

答:
Should I include general exception handler to this, to be able to handle any unforeseen exceptions?

Unfortunately, yes, you must do this.

Does use of lambda statements in every method call (ExecutAction(()
  =>) degrade code readability?

Some people say yes. You don't have to use lambdas. You can use ordinary static or instance methods.

To avoid delegates, you could change the design. When a user interface event occurs, you can use a general purpose code with a an "action" identifier, such as a Command object with a unique type or name, to execute code elsewhere (command processors) that uses try/catch blocks in a generic way, instead of putting such blocks within all event handlers.


问:
What is the simplest translation file format for a user to edit and for a program to parse?
I have just started developing a small web app for Arabic speakers, and I will need to ask a co-worker (not a programmer) to help me translate all of the labels and documentation into Arabic at some point. Ideally, labels would allow arbitrary punctuation and line breaks, but we can set some rules to keep things practical.

My first thought is to have a translations directory, where each label is a set of text files that are named after the label string's parameter name, with a suffix to represent the language. Is there a standard way of doing this that is roughly as flexible and user-friendly as what I have in mind?

Example:

```<code>translations/
    submit.en-ca
    submit.ar
    cancel.en-ca
    cancel.ar
    instructions.en-ca
    instructions.ar
</code>```

答:
I have used CSV. It works well because:

Translators can conveniently edit short phrases using a spreadsheet app such as Excel or Google Drive

CSV is easy to translate back and forth into whatever format I must use or decide to use internally in the application

I have no idea if CSV is the simplest format to use. Also, I suspect that the simplest format to use for editing and the simplest format to use in the application might not be the same.

You have some flexibility in how you structure your CSV file, but a basic approach is to use three columns with

Column 1 == the label name / key

Column 2 == the English phrase

Column 3 == an empty cell where the translator will put their translated phrase


问:
How can DB and UI agree on default values?
I created a table in a Postgres database. I would like to create a form in a Java application to insert rows into that table. Certain fields have default values. What is the best way for the database and UI to agree on what the default values are? Also, what is the best way for the form to communicate the user's intent regarding defaults to the database?</p>

答:
Preferably, you should construct your workflow so that new records are initialized in the GUI only and not from the database. That will ensure that front-end and back-end don't need to agree about the default values, because the DB defaults never become visible to the user.

If you must process adding just like editing, i.e. the front-end is loaded with default values read from the server, then you should look into auto-generating one of the two sides - either auto-generate the SQL creation script from the front-end code or vice versa, or auto-generate both from a separate data description document.


答:
You should probably learn from a successful example, like Microsoft ResX, the .NET way. It is XML, so its easy to manage with code, or by hand. The XML schema is very simple, not crazy at all.

http://msdn.microsoft.com/en-us/library/xbx3z216.aspx

I'd also avoid editing them by hand (especially if they require encoding) and provide your co-worker a friendly editor for whatever format you decide on, so I'd stick with a standard format like this and reuse one of the editors out there.

For me, .resx is workable, but you can also use the more traditional format, .resource.

A quick Google shows some free resx editors. Lutz (Roeder) has something I would expect to be of decent quality (given he wrote Reflector)

http://www.lutzroeder.com/dotnet/

Or this one, looks oriented towards translation end-user

http://sourceforge.net/projects/resx/

Or use Visual Studio Express (free for your co-worker), or hack one up yourself using the schema (Microsoft ResX Schema v2.0)

The main thing you'll be manipulating will be data elements. You can store text or images or other objects in a resx.

```<code><data name="navbarImageList.ImageStream"
             mimetype="application/x-microsoft.net.object.binary.base64">
  <value>
    AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w
    ...
  </value>
</data>
</code>```

Secondly, I recommend you create less granular resource files, like one per form or screen or page, or even one per app if not that large. It'll be friendlier to manage.

Title: What is the simplest translation file format for a user to edit and for a program to parse?

Body:
I have just started developing a small web app for Arabic speakers, and I will need to ask a co-worker (not a programmer) to help me translate all of the labels and documentation into Arabic at some point. Ideally, labels would allow arbitrary punctuation and line breaks, but we can set some rules to keep things practical.

My first thought is to have a translations directory, where each label is a set of text files that are named after the label string's parameter name, with a suffix to represent the language. Is there a standard way of doing this that is roughly as flexible and user-friendly as what I have in mind?

Example:

```<code>translations/
    submit.en-ca
    submit.ar
    cancel.en-ca
    cancel.ar
    instructions.en-ca
    instructions.ar
</code>```

Body:
You should probably learn from a successful example, like Microsoft ResX, the .NET way. It is XML, so its easy to manage with code, or by hand. The XML schema is very simple, not crazy at all.

http://msdn.microsoft.com/en-us/library/xbx3z216.aspx

I'd also avoid editing them by hand (especially if they require encoding) and provide your co-worker a friendly editor for whatever format you decide on, so I'd stick with a standard format like this and reuse one of the editors out there.

For me, .resx is workable, but you can also use the more traditional format, .resource.

A quick Google shows some free resx editors. Lutz (Roeder) has something I would expect to be of decent quality (given he wrote Reflector)

http://www.lutzroeder.com/dotnet/

Or this one, looks oriented towards translation end-user

http://sourceforge.net/projects/resx/

Or use Visual Studio Express (free for your co-worker), or hack one up yourself using the schema (Microsoft ResX Schema v2.0)

The main thing you'll be manipulating will be data elements. You can store text or images or other objects in a resx.

<data name="navbarImageList.ImageStream"
             mimetype="application/x-microsoft.net.object.binary.base64">
  <value>
    AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w
    ...
  </value>
</data>

Secondly, I recommend you create less granular resource files, like one per form or screen or page, or even one per app if not that large. It'll be friendlier to manage.


答:
Doing both should be considered an option. There are instances where the logic is too complex and relies on data from so many other tables, that the database code is just a bad place to handle it. If the goal is to consistently put them in the same place(s), you may not want to violate this, so keep it all on the form.

On the form, you can prepopulate default values, so the user knows what they are and can potentially change them or if it is some value unimportant to the user and/or you don't want them to change it, you have the flexibility to leave it off the form and let the db handle it.

This way, if you do any type of date import/transfer, you know the rules will still be upheld.

Of course the downside is the duplication of effort and keeping things coordinated and supported down the road. There are two potential places to determine, "Where did that value come from?"

Title: How can DB and UI agree on default values?

Body: I created a table in a Postgres database. I would like to create a form in a Java application to insert rows into that table. Certain fields have default values. What is the best way for the database and UI to agree on what the default values are? Also, what is the best way for the form to communicate the user's intent regarding defaults to the database?</p>


答:
It turns out that translation is a fair bit more complex than I realized. Plurals don't work quite the same way in Arabic as they do in English, every noun has a gender, and some translations are supposed to be different depending on whether the speaker is male or female. What a mess.

After a bit more research, I have discovered Gnu gettext and what appears to be a de-facto standard file type: .po files. The cross platform poeditor looks like a tool that I can expect professional translators to be familiar with, and my hopefully helpful co-worker should be able to run it on her Mac.

There are Javascript parsers, jed for example, and a gulp module (gulp-po-json) to convert .po files to json at build time.


问:
What's the best method for ignoring the BBCode between  tags in a full-post BBCode parser?
To clarify on the title a bit more, this is for a plugin for my forum.

I'm doing this:

```<code>div.html( parser( div.html() ) )
</code>```

When sending the html string to the parser, of course I get something like:

```<code>"[BBC][/BBC]\n<code>[BBC][/BBC]</code>"
</code>```

What's the best method I could use to prevent the parsing of the BBC tag inside the code tag?

答:
A workaround would be to save each code block before the plugin parses the post, then restore the blocks afterwards.

EDIT:
So I've changed things around and am working on a slightly more efficient method rather than text replacement (mentioned in the OP), which will still be considered here.

Here's what I'm using now:

```<code>function parse( node ) {

    // backup code blocks
    var codes = []; node.find('code').each(function() { codes.push($(this).html()); });

    // Do whatever you need to here

    // restore the code blocks
    var i=0; node.find('code').each(function() { $(this).html(codes[i]); i = i+1; });

};
</code>```

^ applies the changes to the element directly

For the old method mentioned in the OP:

```<code>function parse( post ) {
    var node = $('<div>'+post+'</div>');

    // backup the code blocks
    var codes = []; node.find('code').each(function() { codes.push($(this).html()); });

    post = ''; // <-- Do whatever you need to here

    node.html( post ); // update the node

    // restore the code blocks
    var i=0; node.find('code').each(function() { $(this).html(codes[i]); i = i+1; });

    return node.html();
};
</code>```

I don't recommend this method, it's just a workaround until I'm able to just ignore code blocks altogether.

Title: What's the best method for ignoring the BBCode between <code> tags in a full-post BBCode parser?

Body:
A workaround would be to save each code block before the plugin parses the post, then restore the blocks afterwards.

EDIT:
So I've changed things around and am working on a slightly more efficient method rather than text replacement (mentioned in the OP), which will still be considered here.

Here's what I'm using now:

function parse( node ) {

    // backup code blocks
    var codes = []; node.find('code').each(function() { codes.push($(this).html()); });

    // Do whatever you need to here

    // restore the code blocks
    var i=0; node.find('code').each(function() { $(this).html(codes[i]); i = i+1; });

};

^ applies the changes to the element directly

For the old method mentioned in the OP:

function parse( post ) {
    var node = $('<div>'+post+'</div>');

    // backup the code blocks
    var codes = []; node.find('code').each(function() { codes.push($(this).html()); });

    post = ''; // <-- Do whatever you need to here

    node.html( post ); // update the node

    // restore the code blocks
    var i=0; node.find('code').each(function() { $(this).html(codes[i]); i = i+1; });

    return node.html();
};

I don't recommend this method, it's just a workaround until I'm able to just ignore code blocks altogether.


答:
Referential integrity and other constraints should be managed by the database and not the application that uses it.

In the case of default constraints, I would have the UI pass in NULL for those fields or simply do not specify them at all in the INSERT query. The database will then supply the default value.

The benefit to this is that SQL is designed for the task of managing data, so manage the data (including defaults) in the tier that handles it best. If you have multiple application using it, data will be consistent. If someone opens a query window to manipulate data, data will be consistent. If someone uses a bulk insert or other data load method, data will be consistent.

The key here is everything funnels into the database: it is a data chokepoint. That makes it the ideal place to manage constraints consistently.


答: It sounds like you don't know the CS definition of a side effect.  A function has a side effect if it has any observable interaction with the system outside of that function.  Therefore output is always a side effect, you can observe a change in the hard drive, network, console where ever your output went.  Input is similarly a side effect, because it has an effect on the computation happening in the function, and may cause an effect in the external system i.e. reading from a console or socket.</p>


问:
Is it possible to have Ad-Hoc polymorphism with runtime dispatch?
As I did understand, and as it's described here, ad-hoc polymorphism is limited to compile-time dispatch. That is, if we have a function that expects an argument that belongs to a typeclass, we must know the concrete type of the argument at compile time to be able to use this function.

So the following (in Haskell-like pseudocode) will be invalid:

```<code>// C-style comments

typeclass Num(X) where:
    add :: X -> X -> X
    one :: X

implementation Num for Int:
    add x y = x + y
    one = 1

implementation Num for Rational:
    // analogous thing…

veryCleverFunction :: Num a -> a -> a
veryCleverFunction x = add x one

tooCleverFunction :: Int -> Num(?)
tooCleverFunction x = {
    y =
        if (x > 0)
            x
        else
            Rational(x, 2) // `y` has a value of unknown type,
                           // but we know it's under `Num` typeclass
    veryCleverFunction y // can work with any `Num`s, but here the concrete type is unknown…
}
</code>```

(I hope it's clear what I want to depict in this snippet)

At least in Scala I'm almost sure there's no way to express this. Or I'm wrong?
And is it possible in theory? Are there any languages which allow this?

答:
Your example already shows why it's not possible. Consider one. If you encountered one at runtime, should it evaluate to Int or Rational? There is no way how to decide.

A related reading resource is OOP vs type classes at Haskell Wiki.


问:
What drawbacks are there to condition-based scope?
In the pseudo code below, the variable key must be declared and initialized outside of the context which it is used/relevant because there are two disparate if-blocks with the exact same condition.

I was thinking it might be cool if a language could consider two if blocks like that to have the same scope.  What are the drawbacks, if any, to this approach?

Before:

```<code>class Foo
  static bool CacheEnabled = true
  static Foo Get(string name)
    Foo result
    string key = "cache_" + name
    if(CacheEnabled)
      if(Cache.GetFoo(key, out result))
        return result
    result = new Foo()
    //
    // rest of initialization here..
    //
    if(CacheEnabled)
      Cache.PutFoo(key, result)
    return result
</code>```

After

```<code>class Foo
  static bool CacheEnabled = true
  static Foo Get(string name)
    Foo result
    if(CacheEnabled)
      string key = "cache_" + name
      if(Cache.GetFoo(key, out result))
        return result
    result = new Foo()
    //
    // rest of initialization here..
    //
    if(CacheEnabled)
      Cache.PutFoo(key, result) // key is available since the condition is the same
    return result
</code>```

答:
I would vote no, because its availability would tend to encourage duplication and mixing abstraction levels.  For your example, you are mixing the caching concern with the calculation concern, and duplicating the conditional.  Both of these problems could be mitigated by moving the conditional and the key to the Cache class.  There are other language constructs, like first-class functions and decorators, that can handle this kind of use case much more cleanly.

There may be other use cases that would fit better, but I can't think of any that wouldn't involve duplicating of the conditional, and therefore couldn't be handled more cleanly with some refactoring.


答:
Lexical scope is a compile-time (actually, even a parse time) property. "Same condition" is a runtime property. Figuring out runtime properties at compile time is hard. In fact, it is almost always impossible. Even the simplest, stupidest possible runtime property, namely, "will this run forever" (aka the Halting Problem) is impossible to figure out at compile-time.

As it turns out, your "same condition" is basically the Function Equivalence Problem, which, just like the Halting Problem is known to be undecidable. IOW: it is impossible for the compiler to figure out that the two blocks have the same condition.

Note, however, that all of this only applies for Turing-complete languages. If you restrict what your programmers are allowed to put into a condition enough, then you might be able to prove at compile time that the two conditions are the same. Note also, that it takes very little to make a language Turing-complete, or put another way: you have to take an awful lot of features away from a language to make Function Equivalence decidable.

Whether or not it is worth it to basically disallow powerful if statements just to save some variable initialization is a matter of taste, I guess.

Title: What drawbacks are there to condition-based scope?

Body:
In the pseudo code below, the variable key must be declared and initialized outside of the context which it is used/relevant because there are two disparate if-blocks with the exact same condition.

I was thinking it might be cool if a language could consider two if blocks like that to have the same scope.  What are the drawbacks, if any, to this approach?

Before:

```<code>class Foo
  static bool CacheEnabled = true
  static Foo Get(string name)
    Foo result
    string key = "cache_" + name
    if(CacheEnabled)
      if(Cache.GetFoo(key, out result))
        return result
    result = new Foo()
    //
    // rest of initialization here..
    //
    if(CacheEnabled)
      Cache.PutFoo(key, result)
    return result
</code>```

After

```<code>class Foo
  static bool CacheEnabled = true
  static Foo Get(string name)
    Foo result
    if(CacheEnabled)
      string key = "cache_" + name
      if(Cache.GetFoo(key, out result))
        return result
    result = new Foo()
    //
    // rest of initialization here..
    //
    if(CacheEnabled)
      Cache.PutFoo(key, result) // key is available since the condition is the same
    return result
</code>```


问:
Trying to get a better understanding of Interfaces
Im working on a small program and I thought i would use it as a chance to get a better understanding of things I haven't really used before, mainly Interfaces and Inheritance from base classes.

Basically it is a facility use request program and after a request is made it needs to email the requester all the information they filled out.  The form breaks down into main request information(contact, group name, etc..), facility rooms, facility & room equipment, requested dates, optional external document.  I've separated each section of the form into their own custom class so I can easily pass information between layers but when putting information into email template I ran into an issue.  Request information and external document information will only appear once per request so I can easily just find and replace the placeholders I setup.  The other classes however can have multiple instances per request.  The way I set up to get around this was this

I created 2 interfaces

```<code>Public Interface SingleInstance
   Public function PlaceHolderReplace() as Hashtable
End Interface
Public Interface MultipleInstances
   Public function PlaceHolderReplace(mi as string 'multiple instance place holder to replace) as string
end Interface
</code>```

With these setup I realized the replace function for each class would be the same based on how many instances of the class there were per request so I decided to create 2 base classes that implement the interface from above.

```<code>Public Class SInstance
Implements SingleInstance
   Public function PlaceHolderReplace() as Hashtable Implements SingleInstance.PlaceHolderReplace
      (code adding placeholder names and class property values to hashtable)
   End Function
End Class
Public Class MInstance
Implements MultipleInstances
   Public function PlaceHolderReplace(strPlcHolder as String) as string Implements MultipleInstances.PlaceHolderReplace
      (code to loop through all properties of current class and make changes to supplied string and return string with replacements)
   End Function
End Class
</code>```

So far this is working out I can combine each set of single or mutliple instance type classes into 2 lists of interfaces and pass them through to the necessary replacement procedures I have.  The single instances just loops through each returned hash table and make the replacements.  The procedure to replace all multiple instance isolates all repeating data placeholders and loops through all classes in the interface returning a combined string for all instances of the specific class.  As I was building the this I came across several questions that I couldn't really answer.

Is this really the best use of Interfaces?  It makes sense for inheritance because each class can run one of two functions so creating two base classes and just using inheritance to determine which one to run makes sense.  The issue is the interfaces are only implemented in one class each so really they only exist so that I can put classes that aren't related into one list.

Is this affecting performance?  With the multiple instance classes because they are unrelated putting them in a single list causes me to have to check the current class and match the property placeholders against what is in the repeating data place holders to make sure they exist before replacing them.  Alternatively if I just call each classes function explicitly I would still have to check the repeating data place holder anyway to find out which one to run.  They way I have it set seems like it would take longer because each repeating data place holder has to loop through every class in the list even if they are unrelated.

Is this the best way for me to test how interfaces work? It would really be nice to have something to refer back to if I have a brain fart.  Since all I get is the ability to put unrelated classes into a single list and that might be affecting performance.

I could see how this setup would help when this program needs to expand which I have been told is almost guaranteed to happen but if it is going to expand I don't want performance to suffer due to the way I set it up.  Any help with these questions would be great thanks.

答:
In my opinion you picked a fairly interesting, but less typical example to understand "how interfaces work". Nevertheless it is a valid use case.

An interface serves multiple purposes. First, they act as an contract between two parties on how they can interact together, or how some kind of exposed functionality is to be used. Ok, for a fully complete and valid contract we would need some more things, but let's just focus on the code part. The interface describes what methods are available, and what their args and return values are. It's not only for documentation, also tools like the compiler get the information how to set up things properly when an interface method gets called.

Interfaces are also commonly used to decouple things, this is an important and inherent part of their nature. The interface designed above can be implemented by, say, three different classes. These classes do not have to have an common ancestor, as it would be necessary with normal inheritance. They can be completely different in nature, they may even be implemented using different programming languages (the latter has become less important with .NET but was an important point with COM).

A third aspect is, that a given class may implement multiple interfaces, but does not necessarily have to implement all of them. This is quite useful, for example:

A newer version of an (published) interface becomes available. Older clients can still use the old servers, newer clients ask whether or not a particular interface is supported or not an react appropriately.

A particular implementation only supports certain aspects of a feature set (for whatever reason). Same here, the client asks for the interfaces he may need and reacts appropriately, depending on the support provided by the server.

Often different interfaces serve completely different purposes, thus are separated into smaller logical pieces. Smaller interfaces help to stay more focused on a certain task, they are also typically much easier to handle and implement.

The support of a particular interface signals a specific trait. For example, with C# the IDisposable interface is used to indicate the needs for a special cleanup treatment to release a certain critical resource properly.

What you did above is more or less a variant of the latter. You basically have lists of elements who either implement the one or the other interface, providing you with the information about the appropriate treatment of that instance. In your case there is no need for the common feature set to be exposed via interface,  you already express this via inheritance.

That's fine, however you could improve the approach by putting all instances into only one single List (Of Object) or  List (Of IMyBaseInterface). To query all elements, you would have to iterate through that list, check which of the two interfaces is supported by each entry, and react appropriately.

Regarding the performance aspect: Im not an VB specialist, but I would doubt that even in VB querying interfaces and calling interface methods will be a performance bottleneck, unless you do a really large number of such operations quickly, e.g. in a loop.


问:
Calling another program from a Windows Service
Problem:
I am working on a service which will do some automated processing at a configurable time each night. It does some communication over the internet, formats some information, and creates a file. This file will be used by another program. I don't want to specify what program it is, because I've signed NDAs and I really don't think it's important to the question. My issue is that I cannot get this program to be run by the service. If I run my program as a regular console application, it works fine. I am calling the external program by sending a shell command with the path to the executable and several parameters (for configuration of how it will run and the path to the file I create with my program). My command is correct, as it will run being pasted into a command shell or if my program is run as a console application.

What I've tried:
Calling the external program directly from my service (I'm using C# and the Process.Start method, but that's here nor there. I feel my question is more conceptual than my specific implementation). This does nothing. The program I am calling is set to run in an unattended mode (this makes it have no UI or anything). I have tried running a .bat file with the proper command and arguments from my service as well, with no luck (I tested the .bat independently). My service is set to be allowed to interact with the desktop.

My question:
How can I get a Windows Service to run an external program? More generically, what is the preferred solution or pattern to use when one must call another process from a Service (Daemon in *nix-land)? If I should be able to call the program and my issue is implementation-specific, I will open a question on StackOverflow. But I would like to know what the standard approach for this problem is.

I know this is supposedly a bad design, because there's a chance there's no user logged in. But the program to be run shouldn't need any special permissions or care about which user it was ran as.

I cannot use the Task Scheduler as this was specifically forbidden in the requirements due to reliability issues. This is actually why the program runs as a service in the first place instead of as a scheduled task.

答: I remember having a similar problem, and it ended up being related to what user is the service running as.  It only worked if it was running as a logged in user, as opposed to default Local System.  You can specify the user credentials in Services control panel (Log On As), and programmatically as well.  The problem with that approach is, that you essentially need to know the user ahead of time and hardcode it.  In our case, we ended up forgetting about a service, and replacing it with a regular desktop application, that had no window in taskbar, but an icon in the notification area instead.</p>


答:
As Jörg W Mittag has said, trying to get the compiler to prove that two conditions are equivalent is undecidable.  The user would have to annotate which conditions are equivalent, and what happens if they annotate incorrectly?

This would also make scopes a lot more complicated to reason about (and certainly even more daunting for new programmers).  Mysterious variables popping in and out of scope can also be another source of bugs.

Furthermore, what you want could be done entirely using first-class functions:

```<code>class Foo
  static bool CacheEnabled = true

  static Foo Get(string name)
    Foo initializer() = () =>
      // the variable "key" is inaccessible here
      Foo result = new Foo()
      //
      // rest of initialization here..
      //
      return result

    Foo result
    string key = "cache_" + name
    if(CacheEnabled)
      if(Cache.GetFoo(key, out result))
        return result

    // call initializer
    result = initializer()

    if(CacheEnabled)
      Cache.PutFoo(key, result)
    return result
</code>```

Body:
As Jörg W Mittag has said, trying to get the compiler to prove that two conditions are equivalent is undecidable.  The user would have to annotate which conditions are equivalent, and what happens if they annotate incorrectly?

This would also make scopes a lot more complicated to reason about (and certainly even more daunting for new programmers).  Mysterious variables popping in and out of scope can also be another source of bugs.

Furthermore, what you want could be done entirely using first-class functions:

class Foo
  static bool CacheEnabled = true

  static Foo Get(string name)
    Foo initializer() = () =>
      // the variable "key" is inaccessible here
      Foo result = new Foo()
      //
      // rest of initialization here..
      //
      return result

    Foo result
    string key = "cache_" + name
    if(CacheEnabled)
      if(Cache.GetFoo(key, out result))
        return result

    // call initializer
    result = initializer()

    if(CacheEnabled)
      Cache.PutFoo(key, result)
    return result


问:
How can IO cause side effects in Functional Programming?
Whenever I read about Haskell, I find that IO can cause side effects.

But I do not understand how it would do it?

Do we mean that we are writing to a file from one lazy sequence and another lazy sequence is reading from same file?

Is that the only possibility or is there something fundamentally deep?

答:
Did you ever hear this aphorism?

No man can step in the same river twice. For the second time, it is not the same river, and he is not the same man.

Imagine one of your functions writes a 1 to /dev/ttyusb0. In UNIX, this is "just a file", but in real life, this is actually the name of a microcontroller, and by writing a 1 it activates a bread-slicing machine and slices 500 loaves of pumpernickel. Writing a 1 the first time caused 500 loaves of pumpernickel to go from the "unsliced" state to the "sliced" state. Sending another 1 does not have this effect (because you can't go back to "unsliced"!). It's not the same river.

Imagine another of your functions reads some data from a stream. If it was a static file perhaps you could read it twice and get the same results, but if instead your stream is a data buffer from (yet another) microcontroller (this one is monitoring the baking temperature), then reading the value over and over again will give different results as the oven heats up or cools down. He's not the same man.


问:
Managing shared code in source control
Projects A and B both use library project L:

Judging by what people have written about it on the web, managing this situation appears to be a headache:

http://codingkilledthecat.wordpress.com/2012/04/28/why-your-company-shouldnt-use-git-submodules/
why you shouldn't use Mercurial subrepos

Are there any solutions out there that avoid difficulties such as:

• Losing work because the VCS did something unexpected

• Hellish subrepo merges

• Screwups caused by the VCS pointing to an unexpected version of the submodule,

   frequently made worse because the user didn't realize that had happened

答:
There is absolutely no reason to avoid git submodule; it works far better than most of the alternative "solutions". Just have your build script assert (but not modify; to solve problem 1) that the submodule is present and up-to-date (solves problem 3), and only make changes to the submodule as its own repo, not as if it's part of the main repo (solves problem 2). I'll repeat that: only make changes to the submodule as its own repo.

Additionally, recent versions of git supply git submodule update --remote to automatically pull the latest version from the branched you're tracking.

Assuming you are not completely ignoring the most important git command of all time, git status (whose output is also included in the editor when you run git commit), you won't have any problems.

Of course, if you're using some GUI frontend, it's probably crap, but that's true whether you're using submodules or not.

Title: Managing shared code in source control


问:
Disallow non-local storage of an object
I need to write a class in C++ that acquires a hardware resource and releases it again when it is destroyed. Basically that can be done in the constructor and destructor of the class. The difficulty I'm having is that I want this class to be usable as a local object only.

So basically:

```<code>struct Magic
{
  Magic(const Settings& settings)
  {
    acquireHardware(settings);
  }
  ~Magic()
  {
    releaseHardware();
  }
  // Magic does not need to store the settings or a reference to them
};
</code>```

This should be allowed:

```<code>void useAllTheHardware(const Settings& settings)
{
  Magic useHardwareWith(settings);
  ...
  // destructor releases the hardware
}
</code>```

This should fail:

```<code>struct badIdea
{
  badIdea(const Settings& settings)
    : settings_(settings),
    useHardwareWith_(settings)
  {
  }
  Settings settings_;
  Magic useHardwareWith_;
};
badIdea mustFail(settings); // <-- not allowed
</code>```

My environment is exception-free (embedded, and compiled with gcc -fno-exceptions), and if things go terribly wrong there's usually no way of handling that except fixing the bug that caused the crash.

How can I do that?

答:
You can't quite do it, but you can come close:

```<code>#include <cstddef>

#include <new>

struct Magic
{
    enum promise
    {
        i_promise_not_to_put_this_in_another_class
    };

    void *operator new(size_t) = delete;
    void *operator new[](size_t) = delete;
    void operator delete(void *) = delete;
    void operator delete[](void *) = delete;

    Magic(promise) {}
    Magic(Magic&&) = delete;
    Magic(const Magic&) = delete;
    Magic& operator = (Magic&&) = delete;
    Magic& operator = (const Magic&) = delete;
    ~Magic() {}
};

struct WhyIsThisABadIdea
{
    Magic m;

    WhyIsThisABadIdea() : m(Magic::i_promise_not_to_put_this_in_another_class) {} // obvious lies
};

int main()
{
    Magic m(Magic::i_promise_not_to_put_this_in_another_class); // okay
    //new Magic(Magic::i_promise_not_to_put_this_in_another_class); // error
    WhyIsThisABadIdea bad; // okay
}
</code>```

Title: Disallow non-local storage of an object

Body:
You can't quite do it, but you can come close:

#include <cstddef>

#include <new>

struct Magic
{
    enum promise
    {
        i_promise_not_to_put_this_in_another_class
    };

    void *operator new(size_t) = delete;
    void *operator new[](size_t) = delete;
    void operator delete(void *) = delete;
    void operator delete[](void *) = delete;

    Magic(promise) {}
    Magic(Magic&&) = delete;
    Magic(const Magic&) = delete;
    Magic& operator = (Magic&&) = delete;
    Magic& operator = (const Magic&) = delete;
    ~Magic() {}
};

struct WhyIsThisABadIdea
{
    Magic m;

    WhyIsThisABadIdea() : m(Magic::i_promise_not_to_put_this_in_another_class) {} // obvious lies
};

int main()
{
    Magic m(Magic::i_promise_not_to_put_this_in_another_class); // okay
    //new Magic(Magic::i_promise_not_to_put_this_in_another_class); // error
    WhyIsThisABadIdea bad; // okay
}


问:
How dangerous is it to take shortcuts when coding Web based applications?
I started working as a Web developer few months back. Previously, I had no prior professional experience in programming besides school classes and fun-side projects I did on my own.

I am the only person there that really know how to code. I'm a fast learner and I know I can make a lot of stuff from PHP and JavaScript/jQuery. This was my background, and now I want to explain what I do at the company.

I work on a number of projects, and as I can tell from my company's portfolio, which they have never had experience working with. Such as modifying their basic CMS to the extreme where it exhaust its functionality or working with vast amounts of data given to us in form of XML or JSON. So this was my practice, and I learned much and was awesome. But here are my problems...

As their main Web developer I'm constantly being under a time constraint which the boss isn't bad about; he knows I'm learning... The problem is that when I'm under a time constraint, and I'm constantly asked to create custom modules or code that I had little knowledge before. I tend to make shortcuts, such as not following proper coding practices. I'm not talking about security, but common OOP, or structure code. I make the code work in as little time as I got.

How bad is this? I know it's very bad practice to rush, but I don't have much choice... How do I avoid this? I have little time to study on my own time, and I never know what next project might require, so I can't prepare myself...

Any idea and tips on this topic are really appreciated...

答:
This is basically long-term vs. short-term choice.

You may implement a feature in an hour doing dirty hacks,

Or you may spend the next week studying the actual needs of the users/your boss, translate them into requirements, refactor the code to accommodate the code base for the new change, write tests, implement the changes and document the new code.

The week minus one hour you gain immediately has a long-term cost. It costs money every time somebody (or you in six months) has to read the code. It costs money when something breaks, and nobody can find the reason of the issue. It costs money when you need to implement new changes, but you can't, because the code base became too legacy to work with.

How to deal with it?

By telling your boss the actual time needed to do the change. No, you can't do it in a hour, because the only thing you can do in an hour is a quick hack, and you're a professional programmer, not a quick hacks guy.

You'll often encounter pressure from your superiors. Remember that the duration you give is not negotiable. If the boss wants the feature to be implemented for tomorrow, tell him that there is no way you can do it. Imagine if your boss tells to Boeing that he needs to travel from Seattle to Hong Kong in twenty minutes. Asking you to implement one-week feature in one hour is similar.

Remember that you are a professional programmer, and your boss probably isn't. This creates an interesting situation where it might look like your boss has a choice, but in fact, you're the one who takes the technical choices—which also means that it's your responsibility to take smart choices which makes your company competitive. It's easy: what your boss wants is high quality, low price and short schedule, all three at the same time. Since what he wants is not possible, it's up to you to find the right balance.

Always be aware that your boss may not know things you know, so don't talk to him in technical terms. If you explain that you can do something in a week, or the same thing in two days but this will increment the technical debt, for most non-technical people it means: "I can do this in a week, or in two days if I make an effort." They don't know what technical debt is, so they interpret the part they understood. Your boss doesn't know what testing is, or why common coding style is important, so don't bother him with those aspects. He shouldn't need to chose between 95% targeted code coverage or 40% targeted code coverage: again, this is your responsibility as a lead (or sole) programmer of the company.

In the same way, your boss doesn't know if a feature should take an hour or a week. I stopped counting the cases where my customers were truly convinced that six man-months project can be done by one person in less than a week, and the cases where they were convinced that a change should take weeks of development, while it simply consisted of changing a value of a constant and recompile.

Negotiate and suggest solutions. If your boss wants shorter schedules, suggest to remove this feature or that one, or make this thing more basic. Or find a creative way to fulfill the needs of the customers while reducing custom development to a minimum. Some problems can even be solved without writing any code at all. Your boss is not expected to know that; likely, he doesn't even know precisely what programming is about.


问:
How to decide in which language to write an algorithm that iterates through large amounts of data?
I am attempting to implement an algorithm that takes in a massive array of data, and iterates through each element in this array. For each element, it will either create an new array and put the element inside it or insert it in some existing array based on qualities of the element.

How to decide which language is the best for implementing this algorithm that will iterate through an extremely large array of data?

My initial guess would be a high level language such as Java or Python but I am interested if there are advantages to using other languages to implement this algorithm.

答:
Don't get hung up on this. It is paralysis by analysis. What if I told you Haskell was the best language? Would that help you? What if you don't know Haskell?

That is why this is subjective and off-topic, but it is still an issue that beginners struggle with ("Which language is better...")

The best language for you, right now, is the language you are most comfortable with, assuming it is compatible with the problem environment. Worrying about language before you start implies you are worried about performance, but since you've written nothing to measure, yet, you don't have a performance problem, so this is a form of premature optimization. Don't optimize prematurely.

However, in interest of pragmatism, I cannot honestly think of a top-20 language that is not a good language for what you describe. That is, until you observe a performance problem. And any language has the potential to exhibit a performance problem.


答:
I don't think you can prevent the creation of objects with static storage duration (e.g. C++ - Prevent global instantiation?)

You could run a check at runtime:

```<code>bool ALLOW = false;

struct Magic
{
  // ...

  ~Magic()
  {
    if (!ALLOW)
      std::cerr << "Some diagnostic message\n";
    releaseHardware();
  }
};

int main()
{
  ALLOW = true;

  // ...

  ALLOW = false;  // reset before main() ends
  return 0;
}
</code>```

The destructor of variables with static storage duration

is called after main() ends and

for this reason it will print an error message

Of course this is only a check, but can be quite useful to correct the code.

Consider that it doesn't prevent something like:

```<code>int main()
{
   Magic useHardwareWith(settings);

   // ...
}
</code>```

Title: Disallow non-local storage of an object

Body:
I need to write a class in C++ that acquires a hardware resource and releases it again when it is destroyed. Basically that can be done in the constructor and destructor of the class. The difficulty I'm having is that I want this class to be usable as a local object only.

So basically:

```<code>struct Magic
{
  Magic(const Settings& settings)
  {
    acquireHardware(settings);
  }
  ~Magic()
  {
    releaseHardware();
  }
  // Magic does not need to store the settings or a reference to them
};
</code>```

This should be allowed:

```<code>void useAllTheHardware(const Settings& settings)
{
  Magic useHardwareWith(settings);
  ...
  // destructor releases the hardware
}
</code>```

This should fail:

```<code>struct badIdea
{
  badIdea(const Settings& settings)
    : settings_(settings),
    useHardwareWith_(settings)
  {
  }
  Settings settings_;
  Magic useHardwareWith_;
};
badIdea mustFail(settings); // <-- not allowed
</code>```

My environment is exception-free (embedded, and compiled with gcc -fno-exceptions), and if things go terribly wrong there's usually no way of handling that except fixing the bug that caused the crash.

How can I do that?

Body:
I don't think you can prevent the creation of objects with static storage duration (e.g. C++ - Prevent global instantiation?)

You could run a check at runtime:

bool ALLOW = false;

struct Magic
{
  // ...

  ~Magic()
  {
    if (!ALLOW)
      std::cerr << "Some diagnostic message\n";
    releaseHardware();
  }
};

int main()
{
  ALLOW = true;

  // ...

  ALLOW = false;  // reset before main() ends
  return 0;
}

The destructor of variables with static storage duration

is called after main() ends and

for this reason it will print an error message

Of course this is only a check, but can be quite useful to correct the code.

Consider that it doesn't prevent something like:

int main()
{
   Magic useHardwareWith(settings);

   // ...
}


问:
User story - design constraint
How can I put in the design constraint into a user story?

The system to be developed will generate a invoice when a payment is made, and will send the invoice to xMail (an emailing tool) which will then email the invoice to the customer.

How should I put the information where the system will send the invoice to xMail?

Note: xMail is just a random name as I could not reveal the actual name

答:
User stories are great for capturing functional requirements, but they don't work that well for design constraints and non-functional requirements.

For design constraints and non-functional requirements, a more traditional formulation still works best.

As user stories tend to get more attention, it is a good idea to reference the relevant constraints and non-functional requirements in the description of the story and possibly in the acceptance criteria.

Title: User story - design constraint


答:
I really don't like answering my own question here, especially because I realized that I asked the wrong question. I was too much focused on OO terms and habits, but the reality is that what I wanted was a prodedure, not a class or anything that can actually store a state. Sorry for that.

Here's my (not quite working) solution (improved solution below):

I remembered that there are macros that manage "atomic blocks" by clearing an interrupt enable flag when the block is entered, and restoring it after the block was run. I had a look at those and they are basically just a for loop.

Together with an anonymous struct definition in the for loop initialization (https://stackoverflow.com/a/11255852) this grew to a solution that works for me:

```<code>#include <iostream>

struct Settings
{
    Settings(int v_) : v(v_) {}
    int v;
};

//https://stackoverflow.com/a/11255852
#define useHardwareWith(settings)                   \
acquireHardware(settings);                          \
for(                                                \
  struct                                            \
  {                                                 \
    bool done()                                     \
    {                                               \
      return done_;                                 \
    }                                               \
    bool run()                                      \
    {                                               \
      releaseHardware();                            \
      done_ = true;                                 \
    }                                               \
    bool done_;                                     \
  } magic = {false}; !magic.done() ; magic.run())

void acquireHardware(const Settings& settings)
{
  std::cout << "acquire(" << settings.v << ")\n";
}

void releaseHardware()
{
  std::cout << "release()\n";
}

int main()
{
  Settings settings(1);
  useHardwareWith(settings)
  {
    std::cout << "Doing important hardware stuff\n";
  }
}
</code>```

Output:

```<code>acquire(1)
Doing important hardware stuff
release()
</code>```

Online demo: http://ideone.com/eT91hD

The for macro cannot be stored, so it's not disallowing non-local storage, but simply doing something in a specific order.

This is better

Above solution has a major problem: release() is not called when break or return is called in the loop, because release() is in the "increment" part, and not in a destructor. Unfortunately, a destructor for the anonymous cannot be defined. So I added a named inner struct to do that:

```<code>#include <iostream>

struct Settings
{
    Settings(int v_) : v(v_) {}
    int v;
};

//https://stackoverflow.com/a/11255852
#define useHardwareWith(settings)                   \
acquireHardware(settings);                          \
for(                                                \
  struct                                            \
  {                                                 \
    struct inner                                    \
    {                                               \
      inner() : done_(false)                        \
      {                                             \
      }                                             \
      ~inner()                                      \
      {                                             \
        releaseHardware();                          \
      }                                             \
      bool done_;                                   \
    };                                              \
    bool done() const                               \
    {                                               \
      return inner_.done_;                          \
    }                                               \
    bool run()                                      \
    {                                               \
      inner_.done_ = true;                          \
    }                                               \
    inner inner_;                                   \
  } magic; !magic.done() ; magic.run())

void acquireHardware(const Settings& settings)
{
  std::cout << "acquire(" << settings.v << ")\n";
}

void releaseHardware()
{
  std::cout << "release()\n";
}

void doHardwareStuff(const Settings& settings)
{
  useHardwareWith(settings)
  {
    if (settings.v == 0)
    {
        std::cout << "side-exit\n";
        return;
    }
    std::cout << "Doing important hardware stuff\n";
  }
}

int main()
{
  Settings settings(0);
  doHardwareStuff(settings);
  doHardwareStuff(Settings(1));
}
</code>```

Online demo: http://ideone.com/z3Qm8a

Title: Disallow non-local storage of an object

Body:
I really don't like answering my own question here, especially because I realized that I asked the wrong question. I was too much focused on OO terms and habits, but the reality is that what I wanted was a prodedure, not a class or anything that can actually store a state. Sorry for that.

Here's my (not quite working) solution (improved solution below):

I remembered that there are macros that manage "atomic blocks" by clearing an interrupt enable flag when the block is entered, and restoring it after the block was run. I had a look at those and they are basically just a for loop.

Together with an anonymous struct definition in the for loop initialization (https://stackoverflow.com/a/11255852) this grew to a solution that works for me:

#include <iostream>

struct Settings
{
    Settings(int v_) : v(v_) {}
    int v;
};

//https://stackoverflow.com/a/11255852
#define useHardwareWith(settings)                   \
acquireHardware(settings);                          \
for(                                                \
  struct                                            \
  {                                                 \
    bool done()                                     \
    {                                               \
      return done_;                                 \
    }                                               \
    bool run()                                      \
    {                                               \
      releaseHardware();                            \
      done_ = true;                                 \
    }                                               \
    bool done_;                                     \
  } magic = {false}; !magic.done() ; magic.run())

void acquireHardware(const Settings& settings)
{
  std::cout << "acquire(" << settings.v << ")\n";
}

void releaseHardware()
{
  std::cout << "release()\n";
}

int main()
{
  Settings settings(1);
  useHardwareWith(settings)
  {
    std::cout << "Doing important hardware stuff\n";
  }
}

Output:

acquire(1)
Doing important hardware stuff
release()

Online demo: http://ideone.com/eT91hD

The for macro cannot be stored, so it's not disallowing non-local storage, but simply doing something in a specific order.

This is better

Above solution has a major problem: release() is not called when break or return is called in the loop, because release() is in the "increment" part, and not in a destructor. Unfortunately, a destructor for the anonymous cannot be defined. So I added a named inner struct to do that:

#include <iostream>

struct Settings
{
    Settings(int v_) : v(v_) {}
    int v;
};

//https://stackoverflow.com/a/11255852
#define useHardwareWith(settings)                   \
acquireHardware(settings);                          \
for(                                                \
  struct                                            \
  {                                                 \
    struct inner                                    \
    {                                               \
      inner() : done_(false)                        \
      {                                             \
      }                                             \
      ~inner()                                      \
      {                                             \
        releaseHardware();                          \
      }                                             \
      bool done_;                                   \
    };                                              \
    bool done() const                               \
    {                                               \
      return inner_.done_;                          \
    }                                               \
    bool run()                                      \
    {                                               \
      inner_.done_ = true;                          \
    }                                               \
    inner inner_;                                   \
  } magic; !magic.done() ; magic.run())

void acquireHardware(const Settings& settings)
{
  std::cout << "acquire(" << settings.v << ")\n";
}

void releaseHardware()
{
  std::cout << "release()\n";
}

void doHardwareStuff(const Settings& settings)
{
  useHardwareWith(settings)
  {
    if (settings.v == 0)
    {
        std::cout << "side-exit\n";
        return;
    }
    std::cout << "Doing important hardware stuff\n";
  }
}

int main()
{
  Settings settings(0);
  doHardwareStuff(settings);
  doHardwareStuff(Settings(1));
}

Online demo: http://ideone.com/z3Qm8a


问:
What list of database features/elements are necessary for a programmer to understand?
What database features/elements are necessary for a programmer to understand in order to create non-trivial applications?

I was once asked in a job interview (by a DBA) to rate my understanding of database concepts -- I thought it would be interesting to get opinions.

I'm looking for basic and advanced skills, also any opinions on where developers are typically the weakest (what lack of skills or knowledge creates the most problems).  Also, is it better that developers are need-to-know, and pass more advanced work onto a DBA -- where does that "line in the sand" exist?

答:
What database features/elements are
necessary for a programmer to
understand in order to create
non-trivial applications?

The more experience with database design and normalization the better. Too little (e.g. tables failing to be 1NF)  can be just as bad a too much (EVA).

Basic SQL can solve most problems anything beyond can be handled by asking questions on SO.

Developers should also at least know what ACID stands for, with some idea of what it means.

The other thing developers should know is that bad things sometimes happen to transactions and your application should expect every transaction to always work. Here's a quote from an article by Rico Mariani

One Last Warning

If you consider what I said, about the
natural occurrence of failures in a
database, then you’ll soon realize
that it is normal, using Linq
parlance, for db.SubmitChanges() to
throw an exception from time to time.
If you are trying to write a robust
application with high reliability you
need to think about that.

In addition to obvious things like,
“the network went down”, “the database
went down”, there are less obvious
things like, “there was a deadlock”,
“there was an optimistic lock
conflict” that can and do happen.
Those latter two things should be
appropriately retried because nothing
bad has happened. The strategy you
choose, especially for cases where the
optimistic lock failed, can have a
profound impact on your performance
and certainly you can’t just let those
exceptions flow to the user. I think I
can safely say that my mom doesn’t
want to hear about how table X on
connection A deadlocked with table Y
on connection B.

If you’ve been reading carefully then
you’ll see that it’s also “normal” for
a foreach operation over a Linq query
to fail from time to time – you need a
retry strategy for those too to be
fully robust.

Don’t get down on Linq though, those
problems exist with all data
solutions, the productivity benefits
you get from Linq will go a long way
to helping you to add the robustness
you need in the areas you need it.

Don’t read “too much” at once. Don’t
write “too much” at once. Handle
deadlocks, they’re normal. Handle
optimistic lock failures, they’re also
normal. You should land in the Pit of
Success.

As for that line in the sand? I would say Developers don't need to know anything about the physical operation,  sizing, partitioning, monitoring, (backup/restore), security, High Availability, Disaster recovery, initial setup, etc

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


答:
There are different mechanisms of polymorphism. Except for parametric polymorphism, these dispatch control flow depending on the type of function arguments. In other words: they are some kind of function overloading. The arguments can either be considered for their static type or for their dynamic type. If we dispatch a call on a static type, we call this ad-hoc polymorphism. If we dispatch on the dynamic type, this is either single dispatch if we only consider the dynamic type of one argument (typically an object on which a method is called), or multiple dispatch if we consider the dynamic type of all arguments.

All OOP languages must at least offer single dispatch. The Visitor Pattern can be used to fake multiple dispatch by using additional levels of indirection, but is impractical for more than two arguments. Multi-dispatch in general solves the same kind of problems that ad-hoc polymorphism does, except that it happens at runtime and can therefore be more expressive. Noteworthy examples of languages with multi-dispatch (sometimes called multi-methods) are the Common Lisp Object System (CLOS) and the Julia language.

The blog post you linked to does demonstrate ad-hoc polymorphism, but in an overly complicated fashion. The simplest example might be:

```<code>abstract class Pet
class Cat extends Pet
class Dog extends Pet

object Owner {
    def pet(cat: Cat) = "You can haz cuddles!"
    def pet(dog: Dog) = "Who's a good boy?"
}

val cat: Cat = new Cat()
val dog: Dog = new Dog()
val pet: Pet = new Cat()

Owner pet cat // works
Owner pet dog // works
Owner pet pet // fails, because implementation is chosen *statically*
</code>```

It's the same story in Java and C++. The blog post then goes on a tangent on how using implicit parameters can be used to implement extension methods, and how they can be used to hide the visitor pattern. None of this is really relevant to ad-hoc polymorphism.

Your code example runs into problems because the return types of tooCleverFunction but more importantly of the conditional assigned to the variable y are not well defined. As y can either be Int or Rational, the type checker must reject your code. To safely allow this ambiguity, we could introduce a Union type. But if we have y :: Union Int Rational, then veryCleverFunction can't be applied to y (except of course if Union is a functor so we can do fmap veryCleverFunction y, which returns another Union for you to deal with). If we use such an Union, no static type information is lost. Instead, you have to deal with the mess you created throughout the remaining program.

You would like y to have the type Num a instead. But Num a is not a type, but a type class, i.e. a restriction on the type a.

Title: Is it possible to have Ad-Hoc polymorphism with runtime dispatch?

Body:
As I did understand, and as it's described here, ad-hoc polymorphism is limited to compile-time dispatch. That is, if we have a function that expects an argument that belongs to a typeclass, we must know the concrete type of the argument at compile time to be able to use this function.

So the following (in Haskell-like pseudocode) will be invalid:

```<code>// C-style comments

typeclass Num(X) where:
    add :: X -> X -> X
    one :: X

implementation Num for Int:
    add x y = x + y
    one = 1

implementation Num for Rational:
    // analogous thing…

veryCleverFunction :: Num a -> a -> a
veryCleverFunction x = add x one

tooCleverFunction :: Int -> Num(?)
tooCleverFunction x = {
    y =
        if (x > 0)
            x
        else
            Rational(x, 2) // `y` has a value of unknown type,
                           // but we know it's under `Num` typeclass
    veryCleverFunction y // can work with any `Num`s, but here the concrete type is unknown…
}
</code>```

(I hope it's clear what I want to depict in this snippet)

At least in Scala I'm almost sure there's no way to express this. Or I'm wrong?
And is it possible in theory? Are there any languages which allow this?

Body:
There are different mechanisms of polymorphism. Except for parametric polymorphism, these dispatch control flow depending on the type of function arguments. In other words: they are some kind of function overloading. The arguments can either be considered for their static type or for their dynamic type. If we dispatch a call on a static type, we call this ad-hoc polymorphism. If we dispatch on the dynamic type, this is either single dispatch if we only consider the dynamic type of one argument (typically an object on which a method is called), or multiple dispatch if we consider the dynamic type of all arguments.

All OOP languages must at least offer single dispatch. The Visitor Pattern can be used to fake multiple dispatch by using additional levels of indirection, but is impractical for more than two arguments. Multi-dispatch in general solves the same kind of problems that ad-hoc polymorphism does, except that it happens at runtime and can therefore be more expressive. Noteworthy examples of languages with multi-dispatch (sometimes called multi-methods) are the Common Lisp Object System (CLOS) and the Julia language.

The blog post you linked to does demonstrate ad-hoc polymorphism, but in an overly complicated fashion. The simplest example might be:

abstract class Pet
class Cat extends Pet
class Dog extends Pet

object Owner {
    def pet(cat: Cat) = "You can haz cuddles!"
    def pet(dog: Dog) = "Who's a good boy?"
}

val cat: Cat = new Cat()
val dog: Dog = new Dog()
val pet: Pet = new Cat()

Owner pet cat // works
Owner pet dog // works
Owner pet pet // fails, because implementation is chosen *statically*

It's the same story in Java and C++. The blog post then goes on a tangent on how using implicit parameters can be used to implement extension methods, and how they can be used to hide the visitor pattern. None of this is really relevant to ad-hoc polymorphism.

Your code example runs into problems because the return types of tooCleverFunction but more importantly of the conditional assigned to the variable y are not well defined. As y can either be Int or Rational, the type checker must reject your code. To safely allow this ambiguity, we could introduce a Union type. But if we have y :: Union Int Rational, then veryCleverFunction can't be applied to y (except of course if Union is a functor so we can do fmap veryCleverFunction y, which returns another Union for you to deal with). If we use such an Union, no static type information is lost. Instead, you have to deal with the mess you created throughout the remaining program.

You would like y to have the type Num a instead. But Num a is not a type, but a type class, i.e. a restriction on the type a.


问:
License Type of Software with Free Functionality and Trial Additional Functionality
I'm developing open source software for about ten years. Now I rebuild my main product into a professional version. I think for it as a successor of the freeware version which is more or less legacy now.

I want to implement the following licensing model:

After downloading the software to work in Trial Mode with full functionality for a limited period of time (30 days)

After the trial period has expired, the program will switch to Free Mode with reduced functionality.

After a purchasing of a license, all features will be unlocked

There will be one program (not separate freeware and a professional).

My questions and doubts are:

What is the licensing type (for the download servers) Freeware or Shareware or...

How to announce the program on my website? Can I announce it as a Freeware?

Do you have any advises or recommendations on that business model?

答:
There isn't a nice clean, rigorous definition of Freeware and/or Shareware.

Freeware means that the software is at least distributed free of charge, but there may be restrictions on re-distribution, availability of the sources (as in closed source) and it might omit some features that are available in a paid version.

Shareware is even less well-defined than Freeware, but usually means that (after a trial period) the software stops functioning or starts to seriously nag the user to buy a license.

Going by those two definitions, I would classify your software as Freeware and you could mention in the description that the full functionality is offered during the initial trial period.