问:
How do I make this functional DSL written in an imperative language more efficient?
Suppose I create a simple functional Domain-specific language (DSL) using an imperative language, in this case C++. Here is a simple implementation of a DSL that can has the notion of a simple value and operator (in this case the addition operator):

```<code>// some operator
template <typename LHS, typename RHS>
struct OpImpl
{
    Op(LHS lhs, RHS rhs) : mLhs(lhs), mRhs(rhs) {}
    auto operator()() const
    {
      return mLhs() + mRhs(); // let's say it's a non-trivial operation, and can't be optimised away but also has no side effects.
    }
    LHS mLhs;
    RHS mRhs;
};

template <typename LHS, typename RHS>
auto Op(LHS&& lhs, RHS&& rhs) { return Op<LHS, RHS>(lhs, rhs); }

struct Value
{
    Value(int value) : mValue(value) {}
    auto operator()() const
    {
        return mValue;
    }
    const int mValue;
};
</code>```

Disregarding other problems with this, if I try to create a nested expression using this "language" I will very quickly end up with redundant leaf nodes:

```<code>int main()
{
    auto Res0 = Op(Value(1), Value(2)); // 1 + 2
    auto Res1 = Op(Res0, Res0); // (1 + 2) + (1 + 2)
    auto Res2 = Op(Res1, Res1); // ((1 + 2) + (1 + 2) + (1 + 2) + (1 + 2))
    auto Res3 = Op(Res2, Res2); // etc.
    auto Res4 = Op(Res3, Res3);
    auto Res5 = Op(Res4, Res4);
    auto Res6 = Op(Res5, Res5);
    auto Res7 = Op(Res6, Res6);
    auto Res8 = Op(Res7, Res7);
    auto Res9 = Op(Res8, Res8);
    auto Res10 = Op(Res9, Res9);
    auto Res11 = Op(Res10, Res10);
    auto Res12 = Op(Res11, Res11);
    auto Res13 = Op(Res12, Res12);
    auto Res14 = Op(Res13, Res13);
    auto Res15 = Op(Res14, Res14);
    auto Res16 = Op(Res15, Res15);
    auto Res17 = Op(Res16, Res16);
    auto Res18 = Op(Res17, Res17);
    auto Res19 = Op(Res18, Res18);
    auto Res20 = Op(Res19, Res19);
}
</code>```

The above code in any normal language will have linear complexity on the number of "Res" depths (in this case 21), and presumably functional language implementations do as well.

However, in the above example, my program will call the () operator  on the Value class 2^21 times. If Value is not trivial to calculate, this could make my program tremendously inefficient!

I can reduce the number of calls to Value by introducing a cache:

```<code>template <
struct OpImpl
{
    Op(LHS lhs, RHS rhs) : mLhs(lhs), mRhs(rhs) {}
    auto operator()() const
    {
        // some unique identifier
        auto cacheIndex = findMyIndex(this) // this could be a typeid, etc.

        if (!cache.count(cacheIndex))
            cache[cacheIndex] = mLhs() + mRhs();
        return cache[cacheIndex];
    }

    LHS mLhs;
    RHS mRhs;
};
</code>```

The above reduces the number of calls to the parenthesis operator of Value to 2 and the number of calls to OpImpl to 21. With some tweaking (figuring out the cache position at construction, using an efficient lookup, memory pools, etc.) we can probably make these lookups quite cheap, but we're still doing 21 lookups / pointer indirection for a series of operations that would be much more efficient in bespoke c++ or with a real functional language.

So, to get to my question; how do functional languages solve this problem, and, more importantly, how do I apply such a solution to the simple DSL example given above, such that the code exhibits a reasonable amount of efficiency?

Note that I am not asking about making the above algorithm perform more quickly, I want to find a better algorithm.

答:
My understanding is that a lazy evaluated language actually holds everything in a wrapper like this:

```<code>class LogicalValue {
    ActualValue *value;
    ActualValue operator()() {
       if (value == null) {
           value = computeValue();
       }
       return value;
    }
}
</code>```

This is like your caching example, except that it doesn't attempt to reuse values from other copies of LogicalValue. If I apply the same function to the same operations a second time, it'll get recomputed. The fact is, attempting to memoize everything all the time is a massive performance loss. There is typically only a small set of cases where it is useful, and its explicitly enabled there.

Now, that is theoretically what happens. An actual optimizing functional language compiler will do a lot of optimizations on-top of this structure to get rid of the overhead. For example, if you use a value repeatedly, there's no point in repeatedly checking if it has been evaluated already. On the other hand, if you just created a LogicalValue, there is no point in checking to see if it has been evaluated.

As far your actual case: If we ignore conditionals, it is actually pretty trivial. We always have to compute everything. Just use a depth first traversal of the of graph, adding items to a to-calculate list if they aren't already added. Once you have the list, all you need to do is traverse the list in order evaluating each option. You know that all pre-requisites have been precomputed, because they were added to the list first.

Conditionals make things more complicated because some portions of the DAG won't need to be evaluated. Depending on the complexity of your operations, it might be acceptable to evaluate them anyways. If not, you'll have to come up with a more sophisticated handling.

Body:
My understanding is that a lazy evaluated language actually holds everything in a wrapper like this:

class LogicalValue {
    ActualValue *value;
    ActualValue operator()() {
       if (value == null) {
           value = computeValue();
       }
       return value;
    }
}

This is like your caching example, except that it doesn't attempt to reuse values from other copies of LogicalValue. If I apply the same function to the same operations a second time, it'll get recomputed. The fact is, attempting to memoize everything all the time is a massive performance loss. There is typically only a small set of cases where it is useful, and its explicitly enabled there.

Now, that is theoretically what happens. An actual optimizing functional language compiler will do a lot of optimizations on-top of this structure to get rid of the overhead. For example, if you use a value repeatedly, there's no point in repeatedly checking if it has been evaluated already. On the other hand, if you just created a LogicalValue, there is no point in checking to see if it has been evaluated.

As far your actual case: If we ignore conditionals, it is actually pretty trivial. We always have to compute everything. Just use a depth first traversal of the of graph, adding items to a to-calculate list if they aren't already added. Once you have the list, all you need to do is traverse the list in order evaluating each option. You know that all pre-requisites have been precomputed, because they were added to the list first.

Conditionals make things more complicated because some portions of the DAG won't need to be evaluated. Depending on the complexity of your operations, it might be acceptable to evaluate them anyways. If not, you'll have to come up with a more sophisticated handling.


问:
Implementing SEO for a Zend Framework/PHP/Angular.js application
A team has implemented a web application using MySql, PHP with the Zend framework and Angular.js on the client side. I am in charge of implementing the SEO for this application.

I understand I have to take HTML snapshots of the Angular pages and serve them to web crawlers. That's the only solution working for search engines not executing Javascript.

How can I take such snapshots efficiently? I mean, is there a PHP-related tool that can help me? Should I call a tool from PHP? If yes, which one?

Had this application been developed with node.js, I might have used something like Grunt's grunt-html-snapshot. Is there an equivalent for the Zend framework?

Would you recommend I take snapshots once for all, or should I generate them dynamically? The content of the website does not change that often. It is not critical to have the latest content for SEO purposes.

答:
Totally depends on your application. I've seen a few commercial solutions:

https://prerender.io middleware, which works with Zend Framework2. It's free for under 250 "pages" and works if 7-day caching is acceptable.

Also, check out Brombone.

If you want to go manual, you'll need to do a few things (details here):

Set up hashbang (#!) syntax and HTML5 mode with $location service

Add <meta name="fragment" content="!"> to your html header, which tells Google (and others) to crawl the site using the ?_escaped_fragment_= tag

You can then parse the escaped fragment on the backend to serve some sort of static rendering

ContentLicense: CC BY-SA 3.0


问:
Does knowing Latin or other logical languages contribute to being a better programmer?
I'm currently studying Latin at school, and what I've learned is that it's a very logical language. I feel this has contributed to my programming ability, as it makes it my code easier to understand.

Is there any relation between knowledge of a very logical language such as Latin and the comprehension of code?

答:
I studied it and I think it kind of might have slightly helped me.

My native language is Italian which, despite being a neo-latin language, has little to nothing to do with Latin when it comes to grammar and syntax.

Organizing your thought in a language so different, in which you can't just start a sentence and improvise but you need to create a mental scheme of the full sentence structure before beginning to construct it, and keep it in mind when you want to add subordinates, might be a good logic/memory exercise.

Might help with pointers.

EDIT: correct German requires more or less the same efforts, and it's alive.

ContentLicense: CC BY-SA 2.5


问:
Should serialization and deserialization be the responsibility of the class being serialized?
I'm currently in the (re)design phase of several model classes of a C# .NET application.  (Model as in M of MVC).  The model classes already have plenty of well-designed data, behaviors, and interrelationships.  I am rewriting the model from Python to C#.

In the old Python model, I think I see a wart.  Each model knows how to serialize itself, and the serialization logic has nothing to do with the rest of the behavior of any of the classes.  For example, imagine:

Image class with a .toJPG(String filePath) .fromJPG(String filePath) method

ImageMetaData class with a .toString() and .fromString(String serialized) method.

You can imagine how these serialization methods are not cohesive with the rest of the class, yet only the class can be guaranteed to know sufficient data to serialize itself.

Is it common practice for a class to know how to serialize and deserialize itself?  Or am I missing a common pattern?

答:
I generally avoid having the class know how to serialize itself, for a couple of reasons. First, if you want to (de)serialize to/from a different format, you now need to pollute the model with that extra logic. If the model is accessed via an interface, then you also pollute the contract.

```<code>public class Image
{
    public void toJPG(String filePath) { ... }

    public Image fromJPG(String filePath) { ... }
}
</code>```

But what if you want to serialize it to/from a PNG, and GIF? Now the class becomes

```<code>public class Image
{
    public void toJPG(String filePath) { ... }

    public Image fromJPG(String filePath) { ... }

    public void toPNG(String filePath) { ... }

    public Image fromPNG(String filePath) { ... }

    public void toGIF(String filePath) { ... }

    public Image fromGIF(String filePath) { ... }
}
</code>```

Instead, I typically like to use a pattern similar to the following:

```<code>public interface ImageSerializer
{
    void serialize(Image src, Stream outputStream);

    Image deserialize(Stream inputStream);
}

public class JPGImageSerializer : ImageSerializer
{
    public void serialize(Image src, Stream outputStream) { ... }

    public Image deserialize(Stream inputStream) { ... }
}

public class PNGImageSerializer : ImageSerializer
{
    public void serialize(Image src, Stream outputStream) { ... }

    public Image deserialize(Stream inputStream) { ... }
}

public class GIFImageSerializer : ImageSerializer
{
    public void serialize(Image src, Stream outputStream) { ... }

    public Image deserialize(Stream inputStream) { ... }
}
</code>```

Now, at this point, one of the caveats with this design is that the serializers need to know the identity of the object it's serializing. Some would say that this is bad design, as the implementation leaks outside of the class. The risk/reward of this is really up to you, but you could slightly tweak the classes to do something like

```<code>public class Image
{
    public void serializeTo(ImageSerializer serializer, Stream outputStream)
    {
        serializer.serialize(this.pixelData, outputStream);
    }

    public void deserializeFrom(ImageSerializer serializer, Stream inputStream)
    {
        this.pixelData = serializer.deserialize(inputStream);
    }
}
</code>```

This is more of a general example, as images usually have metadata that goes along with it; things like compression level, colorspace, etc. which may complicate the process.

Body:
I generally avoid having the class know how to serialize itself, for a couple of reasons. First, if you want to (de)serialize to/from a different format, you now need to pollute the model with that extra logic. If the model is accessed via an interface, then you also pollute the contract.

public class Image
{
    public void toJPG(String filePath) { ... }

    public Image fromJPG(String filePath) { ... }
}

But what if you want to serialize it to/from a PNG, and GIF? Now the class becomes

public class Image
{
    public void toJPG(String filePath) { ... }

    public Image fromJPG(String filePath) { ... }

    public void toPNG(String filePath) { ... }

    public Image fromPNG(String filePath) { ... }

    public void toGIF(String filePath) { ... }

    public Image fromGIF(String filePath) { ... }
}

Instead, I typically like to use a pattern similar to the following:

public interface ImageSerializer
{
    void serialize(Image src, Stream outputStream);

    Image deserialize(Stream inputStream);
}

public class JPGImageSerializer : ImageSerializer
{
    public void serialize(Image src, Stream outputStream) { ... }

    public Image deserialize(Stream inputStream) { ... }
}

public class PNGImageSerializer : ImageSerializer
{
    public void serialize(Image src, Stream outputStream) { ... }

    public Image deserialize(Stream inputStream) { ... }
}

public class GIFImageSerializer : ImageSerializer
{
    public void serialize(Image src, Stream outputStream) { ... }

    public Image deserialize(Stream inputStream) { ... }
}

Now, at this point, one of the caveats with this design is that the serializers need to know the identity of the object it's serializing. Some would say that this is bad design, as the implementation leaks outside of the class. The risk/reward of this is really up to you, but you could slightly tweak the classes to do something like

public class Image
{
    public void serializeTo(ImageSerializer serializer, Stream outputStream)
    {
        serializer.serialize(this.pixelData, outputStream);
    }

    public void deserializeFrom(ImageSerializer serializer, Stream inputStream)
    {
        this.pixelData = serializer.deserialize(inputStream);
    }
}

This is more of a general example, as images usually have metadata that goes along with it; things like compression level, colorspace, etc. which may complicate the process.


答:
Serialization is a two part problem:

Knowledge about how to instantiate a class aka structure.

Knowledge about how to persist/transfer the information that is needed to instantiate a class aka mechanics.

As far as possible, structure should be kept separate from the mechanics. This increases the modularity of your system. If you bury the information on #2 within your class then you break modularity because now your class must be modified to keep pace with new ways of serialization (if they come along).

In the context of image serialization you would keep the information on serialization separate from the class itself and keep it rather in the algorithms that can determine the format of serialization --therefore, different classes for JPEG, PNG, BMP etc. If tomorrow a new serialization algorithm comes along you simply code that algorithm and your class contract remains unchanged.

In the context of IPC, you can keep your class separate and then selectively declare the information that is needed for serialization (by annotations/attributes). Then your serialization algorithm can decide whether to use JSON, Google Protocol Buffers, or XML for serialization. It can even decide whether to use the Jackson parser or your custom parser --there are many options you'd get easily when you design in a modular fashion!

Title: Should serialization and deserialization be the responsibility of the class being serialized?

Body:
I'm currently in the (re)design phase of several model classes of a C# .NET application.  (Model as in M of MVC).  The model classes already have plenty of well-designed data, behaviors, and interrelationships.  I am rewriting the model from Python to C#.

In the old Python model, I think I see a wart.  Each model knows how to serialize itself, and the serialization logic has nothing to do with the rest of the behavior of any of the classes.  For example, imagine:

Image class with a .toJPG(String filePath) .fromJPG(String filePath) method

ImageMetaData class with a .toString() and .fromString(String serialized) method.

You can imagine how these serialization methods are not cohesive with the rest of the class, yet only the class can be guaranteed to know sufficient data to serialize itself.

Is it common practice for a class to know how to serialize and deserialize itself?  Or am I missing a common pattern?


问:
What is business logic code and what is data access code, and what's the difference?
I ask this because it seems people usually consider the code that goes into a DAO or Repository implementation as "data access code", while the code that directly uses these DAOs/Repositories as "business logic code".

However, this doesn't seem to make logical sense.

Consider a business service method with code like the following (using Java, but it would be similar in C#, etc.):

```<code>public BigDecimal computeCustomerTotal(Customer customer) {
    List<Order> orders = orderRepository.findByCustomer(customer);

    BigDecimal total = orders.stream()
        .filter(Order::isActive).map(Order::getTotal).reduce(ZERO, BigDecimal::add);

    return total;
}
</code>```

Sure, the above implementation doesn't make "proper" use of a database's capabilities, but bear with me. The point here is that, I assume, everyone agrees it contains only business logic code, with Customer and Order being domain entities (ie, they are not "data" objects).

So, what if I want to make it right, by moving the whole computation to the database, instead of executing in the client program? If I follow "conventional wisdom", I would create a new method in the repository:

```<code>public BigDecimal getCustomerTotal(Customer customer) {
    BigDecimal total = performQuery(
        "select sum(o.total) from Order o where o.customer = ?1 and o.active",
        customer);

    return total;
}
</code>```

(Assume performQuery is a JPA-based utility method which takes a JPA-QL
sentence with optional arguments.)

The second implementation is obviously better than the first, as it probably performs better, and makes proper use of the underlying technologies (JPA/Hibernate, and a relational database).

The problem, though, is that business logic (the rule that only active orders should be considered) has been moved from a business service method to a (supposed) data access method, through a simple implementation change.
Also, this code which is now in the DAO/Repository does not actually know about data access concerns, such as the mapping from entity types and attributes to tables and columns, or about the actual SQL code that gets generated and sent to the DB engine.

Wouldn't it be more logical to regard both methods as containing only business logic code, and just get rid of the DAO/Repository/DAL altogether?

Personally, I don't see any data access code there, and to me things like DAOs, Repositories, or "data access layers" (DAL) are in reality anti-patterns. Note that even when using JDBC + SQL in a DAO/Repository implementation, it will inevitably contain business logic, typically in the form of "where" clauses.

答:
What is business logic code and what is data access code, and what's the difference?

There is a short answer to that:

a) Code, that is used to open a connection to a DB, to retrieve data, do OR-mapping etc. is called data access code

```<code> static public int AddProductCategory(string newName, string connString)
 {
     Int32 newProdID = 0;
     string sql =
         "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
         + "SELECT CAST(scope_identity() AS int)";
     using (SqlConnection conn = new SqlConnection(connString))
     {
         SqlCommand cmd = new SqlCommand(sql, conn);
         cmd.Parameters.Add("@Name", SqlDbType.VarChar);
         cmd.Parameters["@name"].Value = newName;
         try
         {
             conn.Open();
             newProdID = (Int32)cmd.ExecuteScalar();
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
     }
     return (int)newProdID;
 }
</code>```

Example taken from MSDN

b) Code, that is used transform this data or conataining the rules, when to retrieve this data is called business logic

Both are different responsibilities and are usually implemented in different layers of your application:

a) In a layer sometimes called service-layer sits the logic, when to retrieve what kind of data and how this data is treated aka business logic

b) In case you are implementing the Repository Pattern: this is the place where the data acces code lives.

The point here is that, I assume, everyone agrees it contains only business logic code, with Customer and Order being domain entities (ie, they are not "data" objects).

No. It is data access code, it retrieves data in a way which is relevant for the business logic.

Wouldn't it be more logical to regard both methods as containing only business logic code, and just get rid of the DAO/Repository/DAL altogether?

Neither of the methods contain any business logic. It is really only access code. The reason why you filter the data like you do is lead by business concerns, but that doesn't make them itself business logic.

Personally, I don't see any data access code there, and to me things like DAOs, Repositories, or "data access layers" (DAL) are in reality anti-patterns. Note that even when using JDBC + SQL in a DAO/Repository implementation, it will inevitably contain business logic, typically in the form of "where" clauses.

Maybe you should think about your definition of business logic.
These patterns are not in any way anti-patterns, these patterns allow clear separation of concerns.

Body:
What is business logic code and what is data access code, and what's the difference?

There is a short answer to that:

a) Code, that is used to open a connection to a DB, to retrieve data, do OR-mapping etc. is called data access code

 static public int AddProductCategory(string newName, string connString)
 {
     Int32 newProdID = 0;
     string sql =
         "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
         + "SELECT CAST(scope_identity() AS int)";
     using (SqlConnection conn = new SqlConnection(connString))
     {
         SqlCommand cmd = new SqlCommand(sql, conn);
         cmd.Parameters.Add("@Name", SqlDbType.VarChar);
         cmd.Parameters["@name"].Value = newName;
         try
         {
             conn.Open();
             newProdID = (Int32)cmd.ExecuteScalar();
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
     }
     return (int)newProdID;
 }

Example taken from MSDN

b) Code, that is used transform this data or conataining the rules, when to retrieve this data is called business logic

Both are different responsibilities and are usually implemented in different layers of your application:

a) In a layer sometimes called service-layer sits the logic, when to retrieve what kind of data and how this data is treated aka business logic

b) In case you are implementing the Repository Pattern: this is the place where the data acces code lives.

The point here is that, I assume, everyone agrees it contains only business logic code, with Customer and Order being domain entities (ie, they are not "data" objects).

No. It is data access code, it retrieves data in a way which is relevant for the business logic.

Wouldn't it be more logical to regard both methods as containing only business logic code, and just get rid of the DAO/Repository/DAL altogether?

Neither of the methods contain any business logic. It is really only access code. The reason why you filter the data like you do is lead by business concerns, but that doesn't make them itself business logic.

Personally, I don't see any data access code there, and to me things like DAOs, Repositories, or "data access layers" (DAL) are in reality anti-patterns. Note that even when using JDBC + SQL in a DAO/Repository implementation, it will inevitably contain business logic, typically in the form of "where" clauses.

Maybe you should think about your definition of business logic.
These patterns are not in any way anti-patterns, these patterns allow clear separation of concerns.


问:
How to implement a NavigationManager class without using singleton pattern
I'm practicing on writing testable code. One problem I have ran to (researched a lot too) is singleton pattern. It's global state nature makes it unreliable to test because singleton's property changes are kept between the execution of each case.

Even so, singleton is a design pattern that is used to address issues that regards the whole application, a NavigationManager for example.

Here is a simple implementation of a navigation manager class, whose responsability is to keep track of the user's navigation through the app.

For examples I'd like us to use C# or Java.

```<code>class NavigationManager {
    private ICollection<INavigable> navigables; // all possible navigables views
    private Stack<INavigable> navigableStack; // the navigation stack
    private INavigable currentNavigable;  // the current view

    private NavigationManager() {
        navigables = new ICollection<INavigable>()
        navigables.Add( // register all posible navigables
    }

    static NavigationManager Instance {
        get {
            if(_instance == null ) {
                  _instance = new NavigationManager();
            }
            return _instance
        }
    }
    private static NavigationManager _instance;

    void navigateTo(INavigable n) { //.. code to change view
}
</code>```

It is clear the class should be a singleton so that we can navigate through views with navigateTo(), what's an alternative to singleton to achieve this?

答:
It's not because a class should only have one instance in a particular application that you have to use a singleton pattern. That is the key to solving this.

Simply only instantiating an instance of the class once and then passing it around to other classes needing it still maintains the singleton as a concept - only one instance - but does not have the disadvantage in the testing department and leads to nicer code in general because not everything depends on a singleton. To take this further, if needed, you can even make everything take an interface instead and also get rid of the dependency on a concrete implementation. Which in turn improves testability even more (depending on language and tools used, but most work better with interfaces). Suggested reading: Dependency Inversion, Inversion of Control.

In a small app passing around that instance can be done 'manually' via arguments. In large apps that becomes tedious and that is where Dependency Injection comes into the picture, implemented what is called an 'Inversion of Control' framework. It's abit much to go into detail here so check some tutorials on particular frameworks.

To give you a rough idea of how it solves your problem here is a sample for C# using MEF which I like personally because it uses attributes. First you don't need the static Instance method anymore. Furthermore you make it implement an interface. This results in code like

```<code>interface INavigationManager
{
  void NavigateTo( INavigable n );
}

[Export( typeof( INavigationManager) )]
class NavigationManager : INavigationManager
{
  //....current implementation
}

class DoSomeNavigating
{
  private readonly INavigationManager navMan;

  [ImportingConstructor]
  DoSomeNavigating( INavigationManager navMan )
  {
    this.navMan = navMan;
  }

  public void Go( INavigable n )
  {
    navMan.NavigateTo( n );
  }
}
</code>```

First the testing: no dependency on NavigationManager itself anymore, and suppose you use the Moq mocking framework you'd write tests like

```<code>[Test]
void DoSomeNavigating_NavigatesToSomething()
{
  var navMan = new Mock<INavigationManager>();
  var navigable = new Mock<INavigable>();
  navMan.Setup( m => m.NavigateTo( navigable ) );

  new DoSomeNavigating( navMan.Object ).Go( navigable.Object );

  mock.VerifyAll(); //check that navMan.NavigateTo( navigable ) was called
}
</code>```

When you need DoSomeNavigating in the application itself, you ask MEF to create an instance for you and have it automatically fetch an instance of NavigationManager. As the latter is marked with just Export, MEF knows it should should only create one instance of it so it takes care of the singleton concept for you. Since the first is marked with ImportingConstructor MEF knows it wants an instance of something which implements INavigationManager. Which in this case will be the NavigationManager instance.

```<code>var doNav = container.GetExportedValue<DoSomeNavigating>();
</code>```

Body:
It's not because a class should only have one instance in a particular application that you have to use a singleton pattern. That is the key to solving this.

Simply only instantiating an instance of the class once and then passing it around to other classes needing it still maintains the singleton as a concept - only one instance - but does not have the disadvantage in the testing department and leads to nicer code in general because not everything depends on a singleton. To take this further, if needed, you can even make everything take an interface instead and also get rid of the dependency on a concrete implementation. Which in turn improves testability even more (depending on language and tools used, but most work better with interfaces). Suggested reading: Dependency Inversion, Inversion of Control.

In a small app passing around that instance can be done 'manually' via arguments. In large apps that becomes tedious and that is where Dependency Injection comes into the picture, implemented what is called an 'Inversion of Control' framework. It's abit much to go into detail here so check some tutorials on particular frameworks.

To give you a rough idea of how it solves your problem here is a sample for C# using MEF which I like personally because it uses attributes. First you don't need the static Instance method anymore. Furthermore you make it implement an interface. This results in code like

interface INavigationManager
{
  void NavigateTo( INavigable n );
}

[Export( typeof( INavigationManager) )]
class NavigationManager : INavigationManager
{
  //....current implementation
}

class DoSomeNavigating
{
  private readonly INavigationManager navMan;

  [ImportingConstructor]
  DoSomeNavigating( INavigationManager navMan )
  {
    this.navMan = navMan;
  }

  public void Go( INavigable n )
  {
    navMan.NavigateTo( n );
  }
}

First the testing: no dependency on NavigationManager itself anymore, and suppose you use the Moq mocking framework you'd write tests like

[Test]
void DoSomeNavigating_NavigatesToSomething()
{
  var navMan = new Mock<INavigationManager>();
  var navigable = new Mock<INavigable>();
  navMan.Setup( m => m.NavigateTo( navigable ) );

  new DoSomeNavigating( navMan.Object ).Go( navigable.Object );

  mock.VerifyAll(); //check that navMan.NavigateTo( navigable ) was called
}

When you need DoSomeNavigating in the application itself, you ask MEF to create an instance for you and have it automatically fetch an instance of NavigationManager. As the latter is marked with just Export, MEF knows it should should only create one instance of it so it takes care of the singleton concept for you. Since the first is marked with ImportingConstructor MEF knows it wants an instance of something which implements INavigationManager. Which in this case will be the NavigationManager instance.

var doNav = container.GetExportedValue<DoSomeNavigating>();


问:
Ways to avoid using switches to map strings to classes
I have a C# solution that reads records from a db and processes them into another db. The records to be processed are essentially one long string that represents the data and then another string "code" that determines how that big data string should be parsed. There are dozens and dozens of different kinds of records; I have them represented as distinct concrete classes that all inherit from an abstract class.

I can generate the code to make classes for the different records easily enough. However, is there a better (i.e. less verbose, more dynamic) way to map the "code" to the class that represents it? Right now I'm just using a huge switch, something like:

```<code>BaseRecord record;
switch(code) {
    case "A":
        record = new A(stringData);
    case "B":
        record = new B(stringData);
    .
    .
    .
    case "Z":
        record = new Z(stringData);
</code>```

where A, B, ..., Z all derive from BaseRecord.

Other than reflection, I can't think of a way to map string representations of class names to the classes they represent.

答:
Well, it is possible to avoid the switch statement: You can create an abstract factory class, and have some classes inherit from it (ideally via a template argument) to produce objects of the different derived types. Then you can put all the concrete factories you need in a map and use the strings to index into that map to produce a factory for the desired dynamic type.

However, while possible, this is hardly worth doing. As far as I can see, your switch statement is mind-numbingly simple (albeit long). The abstract factory would introduce a lot of additional complexity, so the switch seems to be more compliant to the KISS principle.

Generally speaking, there's nothing bad about a switch statement, not even one with a lot of cases (as long as the cases are simple and self contained). The problem with switch statements is only when they crop up everywhere, which indicates that you should be using inheritance instead. A single switch to perform deserialization seems fine to me.


问:
Is testable code better code?
I'm attempting to get into the habit of writing unit tests regularly with my code, but I've read that first it's important to write testable code.
This question touches on SOLID principles of writing testable code, but I want to know if those design principles are beneficial (or at least not harmful) without planning on writing tests at all. To clarify - I understand the importance of writing tests; this is not a question on their usefulness.

To illustrate my confusion, in the piece that inspired this question, the writer gives an example of a function that checks the current time, and returns some value depending on the time. The author points to this as bad code because it produces the data (the time) it uses internally, thus making it difficult to test. To me, though, it seems like overkill to pass in the time as an argument. At some point the value needs to be initialized, and why not closest to consumption? Plus, the purpose of the method in my mind is to return some value based on the current time, by making it a parameter you imply that this purpose can/should be changed. This, and other questions, lead me to wonder if testable code was synonymous with "better" code.

Is writing testable code still good practice even in the absence of tests?

Is testable code actually more stable? has been suggested as a duplicate. However, that question is about the "stability" of the code, but I am asking more broadly about whether the code is superior for other reasons as well, such as readability, performance, coupling, and so forth.

答:
To me, though, it seems like overkill to pass in the time as an argument.

You're right, and with mocking you can make the code testable and avoid passing the time (pun intention undefined). Example code:

```<code>def time_of_day():
    return datetime.datetime.utcnow().strftime('%H:%M:%S')
</code>```

Now let's say you want to test what happens during a leap second. As you say, to test this the overkill way you would have to change the (production) code:

```<code>def time_of_day(now=None):
    now = now if now is not None else datetime.datetime.utcnow()
    return now.strftime('%H:%M:%S')
</code>```

If Python supported leap seconds the test code would look like this:

```<code>def test_handle_leap_second(self):
    actual = time_of_day(
        now=datetime.datetime(year=2015, month=6, day=30, hour=23, minute=59, second=60)
    expected = '23:59:60'
    self.assertEquals(actual, expected)
</code>```

You can test this, but the code is more complex than necessary and the tests still can't reliably exercise the code branch that most production code will be using (that is, not passing a value for now). You work around this by using a mock. Starting from the original production code:

```<code>def time_of_day():
    return datetime.datetime.utcnow().strftime('%H:%M:%S')
</code>```

Test code:

```<code>@unittest.patch('datetime.datetime.utcnow')
def test_handle_leap_second(self, utcnow_mock):
    utcnow_mock.return_value = datetime.datetime(
        year=2015, month=6, day=30, hour=23, minute=59, second=60)
    actual = time_of_day()
    expected = '23:59:60'
    self.assertEquals(actual, expected)
</code>```

This gives several benefits:

You're testing time_of_day independently of its dependencies.

You're testing the same code path as production code.

The production code is as simple as possible.

On a side note, it is to be hoped that future mocking frameworks will make things like this easier. For example, since you have to refer to the mocked function as a string you can't easily make IDEs change it automatically when time_of_day starts using another source for time.

Title: Is testable code better code?

Body:
To me, though, it seems like overkill to pass in the time as an argument.

You're right, and with mocking you can make the code testable and avoid passing the time (pun intention undefined). Example code:

def time_of_day():
    return datetime.datetime.utcnow().strftime('%H:%M:%S')

Now let's say you want to test what happens during a leap second. As you say, to test this the overkill way you would have to change the (production) code:

def time_of_day(now=None):
    now = now if now is not None else datetime.datetime.utcnow()
    return now.strftime('%H:%M:%S')

If Python supported leap seconds the test code would look like this:

def test_handle_leap_second(self):
    actual = time_of_day(
        now=datetime.datetime(year=2015, month=6, day=30, hour=23, minute=59, second=60)
    expected = '23:59:60'
    self.assertEquals(actual, expected)

You can test this, but the code is more complex than necessary and the tests still can't reliably exercise the code branch that most production code will be using (that is, not passing a value for now). You work around this by using a mock. Starting from the original production code:

def time_of_day():
    return datetime.datetime.utcnow().strftime('%H:%M:%S')

Test code:

@unittest.patch('datetime.datetime.utcnow')
def test_handle_leap_second(self, utcnow_mock):
    utcnow_mock.return_value = datetime.datetime(
        year=2015, month=6, day=30, hour=23, minute=59, second=60)
    actual = time_of_day()
    expected = '23:59:60'
    self.assertEquals(actual, expected)

This gives several benefits:

You're testing time_of_day independently of its dependencies.

You're testing the same code path as production code.

The production code is as simple as possible.

On a side note, it is to be hoped that future mocking frameworks will make things like this easier. For example, since you have to refer to the mocked function as a string you can't easily make IDEs change it automatically when time_of_day starts using another source for time.


问:
Should you write your back-end as an API?
I had a heated discussion today about our MVC application. We have a website written in MVC (ASP.NET), and it usually follows the pattern of do something in the view -> hit the controller -> controller builds a model (calls a Manager that gets the data, builds the model in the controller method itself) -> model goes to view -> rinse & repeat.

He said that our code was too tightly coupled. For example, if we wanted a desktop application as well, we would not be able to use our existing code.

The solution and best practice he said is to build an API, and then build your website on top of your API, and then building a desktop application, mobile app, etc. is very simple.

This seems like a bad idea to me for various reasons.

Anyway I can't seem to find anything by googling that might discuss this practice. Does anyone have any information about pros, cons, why you should, why you shouldn't or further reading?

Some reasons I think it's a bad idea:

It's way too abstract to run your backend off an API. You're trying to make it too flexible which will make it an unmanagable mess.

All the stuff built into MVC seems useless, like roles and authentication. For example, [Authorize] attributes and security; you will have to roll your own.

All your API calls will require security information attached, and you will have to develop a token system and whatnot.

You will have to write complete API calls for every single function your program will ever do. Pretty much every method you want to implement will need to be ran off an API. A Get/Update/Delete for every user, plus a variant for each other operation eg update user name, add user to a group, etc. etc. and each one would be a distinct API call.

You lose all kinds of tools like interfaces and abstract classes when it comes to APIs. Stuff like WCF has very tenuous support for interfaces.

You have a method that creates a user, or performs some task. If you want to create 50 users, you can just call it 50 times. When you decide to do this method as an API your local webserver can named-pipes connect to it and no problem - your desktop client can hit it too, but suddenly your bulk user creation will involve hammering the API over the Internet 50 times which isn't good. So you have to create a bulk method, but really you're just creating it for desktop clients. This way, you end up having to a) modify your API based on what's integrating with it, and you can't just directly integrate with it, b) do a lot more work to create an extra function.

YAGNI. Unless you're specifically planning to write two identically functioning applications, one web and one Windows application for example, it is a huge amount of extra development work.

Debugging is much harder when you can't step through end-to-end.

Lots of independent operations that will require lots of back and forth, for example some code might get the current user, check the user is in the administrator role, get the company the user belongs to, get a list of other members, send them all an email. That would require a lot of API calls, or writing a bespoke method the specific task you want, where that bespoke method's only benefit would be speed yet the downside would be it would be inflexible.

Probably some more reasons these are just off the top of my head.

It just seems to me like unless you really need two identical applications, then it's really not worth it. I've never seen an ASP.NET application built like this either, you'd have to write two separate applications (the API and your code) and version control them both as well (if your user page gets a new field, you'd have to update the API and your consuming code simultaneously to ensure no ill-effects or put lots of extra work into keeping it robust).

Edit: Some great responses, really starting to get a good idea of what this all means now. So to expand on my question, how would you structure an MVC app to follow this API structure?

For example, you have a website that displays info about a user. Under MVC, you have:

View - (CS)HTML page that displays a UserViewModel
Controller - Calls GetUser() and creates a UserViewModel that it passes to the view
Manager class (sort of your API) that has a GetUser method.

The controller does GetUser() but you want a desktop app too. This means your GetUser needs to be exposed via some kind of API. You might want a TCP connection, either WCF, or perhaps Remoting. You also want a mobile app which will be RESTful since persistent connections are flaky.

So would you then write an API for each one, a WCF web service that has a method GetUser() and the code just does return new UserManager().GetUser() ? And an mvc 4 web api method that does the same thing? While continuing to call GetUser directly in your MVC controller method?

Or would you choose the solution that would work for all three (web api REST service) and build everything on that, so all three apps make API calls (the mvc ones, to the local machine).

And is this just a theoretical perfect scenario? I can see large overheads in developing this way, especially if you have to develop in a way that will let you do operations in a RESTful manner. I think some of this has been covered in the replies.

Edit 2: After reading more stuff, I've put a comment below that I think might explain it. The question is a bit of a trick question I think. Should you write your back-end as an API had me confused thinking there should be a single webservice that everything (mvc app, desktop app, mobile app) calls to do stuff.

The conclusion I have come to is that what you should really do is make sure your business logic layer is correctly decoupled. Looking at my code, I do this already - the controller will call GetUser() on a manager, then create a view model from it to render with a View. So really, the business logic layer is an API. If you want to call it from a desktop app though, you'll need to write something like a WCF service to facilitate calling it. Even just having a WCF method called GetUser() that contains the code return MyBusinessLayer.GetUser() would be sufficient. So the API is the business logic, and WCF / web api etc. are just titbits of code to let external applications in to call it.

So there is some overhead, in that you have to wrap your business logic layer in different APIs depending on what you need, and you will have to write an API method for each operation you want your other apps to do, plus you will need to sort out a way to do authentication, but for the most part it's the same. Stick your business logic in a separate project (class library), and you will probably have no issue!

Hopefully this interpretation is correct. Thanks for all the discussion/comments it has generated.

答:
There are good answers here. I post this as a partial answer; it would perhaps be better as a comment. However sticking the same comment on numerous posts is not good.

One cannot claim YAGNI is a reason for not creating an API.

The API is a natural and logical testing endpoint. Thus right from day 0, there are two applications that use the API: the UI and the testing suite. One is meant for humans, the other is meant for machines. They are necessarily different. Testing front-end behavior is a much different task than testing back-end behavior. Thus the techniques, and probably the tools, are completely different. The API allows the best tool to be used for the job. Further, with the separation afforded by the API, the front-end testers don't have to test back-end functionality.

The API also helps keep the front-end coders out of the back-end coder's concerns, and vice-versa. These are very different skills at our company; the API allows us to focus where we're strongest.


问:
How definite of an order is there to a depth-first search of a graph?
I have the following graph that I need to simulate a depth-first search of; starting at g:

My question is: How definite of an order is there when performing a depth-first search? When doing a DFS of a tree, I always see the left-most child searched first (completely), then after backtracking, the second-most-left child...

But with a graph, "left" seems a lot more arbitrary.

For the above graph, I got the following order:

```<code>g, j, i, m, n, o, k, h, p, l, e, a, f, c, b, d
</code>```

But along the way, I found that there were many other possible paths to take. I'm guessing when implementing a DPS, I would visit the vertices in the order that they appear in the adjacency list (providing I'm using an adjacency list), but I don't have such information here.

Am I right that there are many possible answers to this question? And is my trace of the DPS correct?

答:
Yes, the exact path of the search does depend on what starting point you choose and--every time you hit a node with multiple unvisited children--what order you choose to visit the children in. Most implementations of DFS will always choose the same order, but which order that is depends on details of the algorithm implementation and graph representation that normally don't matter too much. Finally, your trace for that graph looks like one a valid one to me.

Note that it's possible for a directed graph to have only one valid starting point (in the sense that no other would allow it to visit every node) and one available path, but that's only in the trivial case of a "straight line" graph.


问:
Creating two-way object references and keeping data integrity
I have two different classes; a Player and a Group. I need to be able to query a Player which Groups they are registered to (player.getGroups()), and which Players are registered to a Group (group.getPlayers()) quickly. The simplest solution is to have each Player keep a list of the Groups it's registered to, and each Group keep a list of all players registered to that group.

This introduces some data integrity problems (how do I ensure that if a Player references a Group, the Group also references the Player) and problems of how to add a Player to a Group.

A solution to the latter problem is to have a single method on either the Player or the Group:

```<code>public class Player {

    // ...

    public void registerToGroup(Group group) {
        this.groups.add(group);
        group.addPlayer(player);
    }

    // ...

}
</code>```

This works, but also introduces some side consequences of modifying the Group you pass, which you might not expect. But maybe this is the best (and relatively simple) way to do it?

What are the best practices for these kinds of problems? I would prefer not have to search through lists and filter out a certain Player to find out which Groups that Player is registered to, and I would prefer to not mix in databases as this is quite a small project but has to be able to be expanded on without much trouble.

答:
I solved this problem once with something like this:

```<code>class RelationshipManager {
    void addRelation(RelatableObject a, RelateableObject b);
    void removeRelation(RelatableObject a, RelatableObject b);

    List<C> getRelated(RelatableObject obj, Class<C> c);
}
</code>```

The RelationshipManager keeps track of which objects are related to other objects. I can then make requests like:

```<code>relationshipManager.getRelated(player, Group.class);
</code>```

To get all of the groups for a particular player.

You can go a step further and add methods to your class which call this:

```<code>class Player {

    List<Group> getGroups() {
       return relationshipManager.getRelated(this, Group.class);
    }
    void addGroup(Group group) {
       relationshipManager.addRelation(this, group);
    }
}
</code>```

In my case, I was in python, so I actually did something like:

```<code>class Player:
    groups = HasMany(Group)
</code>```

and HasMany overloaded the default getter/setter behavior of python to call into the relationship manager. I also has a BelongsTo which dealt with single elements instead of lists.

Body:
I solved this problem once with something like this:

class RelationshipManager {
    void addRelation(RelatableObject a, RelateableObject b);
    void removeRelation(RelatableObject a, RelatableObject b);

    List<C> getRelated(RelatableObject obj, Class<C> c);
}

The RelationshipManager keeps track of which objects are related to other objects. I can then make requests like:

relationshipManager.getRelated(player, Group.class);

To get all of the groups for a particular player.

You can go a step further and add methods to your class which call this:

class Player {

    List<Group> getGroups() {
       return relationshipManager.getRelated(this, Group.class);
    }
    void addGroup(Group group) {
       relationshipManager.addRelation(this, group);
    }
}

In my case, I was in python, so I actually did something like:

class Player:
    groups = HasMany(Group)

and HasMany overloaded the default getter/setter behavior of python to call into the relationship manager. I also has a BelongsTo which dealt with single elements instead of lists.


答:
Am I right that there are many possible answers to this question? And is my trace of the DPS correct?

Yes, there is no 'natural' ordering of the nodes of a graph. So there is also no 'natural' ordering in the result of the DFS of a graph.

Of course, in the example above, you could sort the nodes alphabetically as you have labels on them. If you assume that you have an order of the nodes, you can create a deterministic result of a DFS for example by always visiting lower nodes first.

Title: How definite of an order is there to a depth-first search of a graph?

Body:
I have the following graph that I need to simulate a depth-first search of; starting at g:

My question is: How definite of an order is there when performing a depth-first search? When doing a DFS of a tree, I always see the left-most child searched first (completely), then after backtracking, the second-most-left child...

But with a graph, "left" seems a lot more arbitrary.

For the above graph, I got the following order:

```<code>g, j, i, m, n, o, k, h, p, l, e, a, f, c, b, d
</code>```

But along the way, I found that there were many other possible paths to take. I'm guessing when implementing a DPS, I would visit the vertices in the order that they appear in the adjacency list (providing I'm using an adjacency list), but I don't have such information here.

Am I right that there are many possible answers to this question? And is my trace of the DPS correct?


答:
It seems to me that you're just missing a class definition.

Declare a class CustomerOrders with GetOrdersTotal method.

It's a pure business object. There no such table in the db. It wraps an Order DAO and applies business rules on on it (active order, filter by customer id).

So, OrderRepository is your DAL and CustomerOrders is your BL

Title: What is business logic code and what is data access code, and what's the difference?

Body:
I ask this because it seems people usually consider the code that goes into a DAO or Repository implementation as "data access code", while the code that directly uses these DAOs/Repositories as "business logic code".

However, this doesn't seem to make logical sense.

Consider a business service method with code like the following (using Java, but it would be similar in C#, etc.):

```<code>public BigDecimal computeCustomerTotal(Customer customer) {
    List<Order> orders = orderRepository.findByCustomer(customer);

    BigDecimal total = orders.stream()
        .filter(Order::isActive).map(Order::getTotal).reduce(ZERO, BigDecimal::add);

    return total;
}
</code>```

Sure, the above implementation doesn't make "proper" use of a database's capabilities, but bear with me. The point here is that, I assume, everyone agrees it contains only business logic code, with Customer and Order being domain entities (ie, they are not "data" objects).

So, what if I want to make it right, by moving the whole computation to the database, instead of executing in the client program? If I follow "conventional wisdom", I would create a new method in the repository:

```<code>public BigDecimal getCustomerTotal(Customer customer) {
    BigDecimal total = performQuery(
        "select sum(o.total) from Order o where o.customer = ?1 and o.active",
        customer);

    return total;
}
</code>```

(Assume performQuery is a JPA-based utility method which takes a JPA-QL
sentence with optional arguments.)

The second implementation is obviously better than the first, as it probably performs better, and makes proper use of the underlying technologies (JPA/Hibernate, and a relational database).

The problem, though, is that business logic (the rule that only active orders should be considered) has been moved from a business service method to a (supposed) data access method, through a simple implementation change.
Also, this code which is now in the DAO/Repository does not actually know about data access concerns, such as the mapping from entity types and attributes to tables and columns, or about the actual SQL code that gets generated and sent to the DB engine.

Wouldn't it be more logical to regard both methods as containing only business logic code, and just get rid of the DAO/Repository/DAL altogether?

Personally, I don't see any data access code there, and to me things like DAOs, Repositories, or "data access layers" (DAL) are in reality anti-patterns. Note that even when using JDBC + SQL in a DAO/Repository implementation, it will inevitably contain business logic, typically in the form of "where" clauses.


答:
As you have hypothesized and as others have confirmed, there isn't a single optimal answer to the question. That said, you can group all possible answers into equivalence classes, and then point out that some classes are better than others.

Because of the specifics of how you've formulated this problem, the most natural equivalence classes are "correct answers" vs "incorrect answers", so we don't get something very interesting from that. But consider a very similar question which is "given an (undirected?) graph, what is its Breadth First Ordering, starting at g?"

A template for all of the optimal answers might look like [{g}, {j, k, h, d}, {f, i, o, c}, {a, m, n, e, p, b, d}]. This template offers [g, j, k, h, d, f, i, o, c, a, m, n, e, p, b, d] as one possible answer, but also [g, d, h, k, j, c, o, i, f, d, b, p ,e, n, n, a] for example.

You could then take an answer like [g, j, k, h, f, d, i, o, c, a, m, n, e, p, b, d] and say that it's "one level out of order". [g, j, k, d, f, h, i, o, c, a, m, n, e, p, b, d] is also one level out of order, and thus would belong to the same equivalence set.

In contrast, an answer like [g, j, k, f, h, d, i, o, c, a, m, n, e, p, b, d] would be two levels out of order, and thus belong to a different equivalence set.

Alternatively, you could build a Hasse diagram of all the possible orderings, essentially providing a partial ordering over the answers saying certain answers are "better" than others.


问:
Should I create mock objects from scratch or modify the result of real calls in weakly typed languages?
In answer to Is testable code better code? I showed how time-dependent code could be testable by using mocks rather than modifying the implementation:

```<code>def time_of_day():
    return datetime.datetime.utcnow().strftime('%H:%M:%S')
</code>```

Test code:

```<code>@unittest.patch('datetime.datetime.utcnow')
def test_handle_leap_second(self, utcnow_mock):
    utcnow_mock.return_value = datetime.datetime(
        year=2015, month=6, day=30, hour=23, minute=59, second=60)
    actual = time_of_day()
    expected = '23:59:60'
    self.assertEquals(actual, expected)
</code>```

The problem here (apart from Python not handling leap seconds) is that the test code assumes that utcnow will return a datetime.datetime object in absolutely all situations. That may be true right now for this specific function with the current interpreter etc., but if the return type changes for whatever reason the test will be passing when it probably should be failing. So for a robust test suite it would be better to guarantee that the mock return value has the same class as the original function return value. This is obviously only possible in languages where the return type is enforced by the compiler or interpreter. You could work around this by modifying a return value of the original function rather than creating your own:

```<code>utcnow_mock.return_value = datetime.datetime.utcnow().replace(
    year=2015, month=6, day=30, hour=23, minute=59, second=60)
</code>```

Now we're operating with a different set of assumptions:

replace modifies the object returned by utcnow rather than returning some different object. This will not be an issue if the relevant object properties are writable.

utcnow always returns objects with the same class.

Which method is more likely to produce a robust test suite? Please consider that unlike this example creating and then modifying an object may be simpler than creating it with the correct properties from scratch.

答:
It depends on what you mean by "robust test suite".

One possible definition would be "my tests never test the wrong thing, even if the underlying requirements of the system change", and I think this is the definition you're leaning towards with your problem description. Honestly, I think this is an unsolvable problem (what if in the next revision of the library, utcnow() doesn't return any value at all and instead is intended to be used to acquire a lock on a DB table?). Also note that when you demand "don't give false positive" (don't have a test fail if there's actually no bug), you usually have to tolerate some false negatives (the test might say there's no bug, but actually there is one).

Another possible definition would be "my test always detect when a change would trigger a bug in my program, in terms of how the requirements were understood when this test was written". I think this is the more commonly used definition (although most of us don't explicitly think about these definitions nor the distinction between them). Under this definition, you would tend to prefer using mock objects rather than mutate existing objects -- but if it turns out that it's more convenient to mutate existing objects than create mock ones, that's okay too. The key insight here though is that if you're worried that utcnow() might change in such a way as to introduce a bug in your system, then you shouldn't write tests only to verify that time_of_day() is performing as you expect, but you should additionally write tests that verify utcnow() is performing as you expect.

Note that under this philosophy, we're aiming for "no false negatives" (if there's a bug, it should be the case that some test somewhere will fail), and so we tolerate a bit of false positive (sometimes a test will say there's a bug, but after inspection, we realize there's actually no bug, the test was just testing the wrong thing).


问:
Clean Code: can private methods rely on member variables set by other private methods?
I was asked to create a class that will connect to a remote service via soap. The class has only one public method send(recordName).

The class ended like this:

```<code>private recordName;
private recordId;

public send(recordName)
{
    this.recordName = recordName;
    this.validateRecordName();
    this.retrieveRecordId();

    if (this.recordExists()) {
        this.updateRecordOnRemoteServer();
    } else {
        this.addRecordOnRemoteServer();
    }
}

private validateRecordName()
{
   // throws exception if this.recordName does not meet certain criteria
}

private retrieveRecordId()
{
    response = // creates a soapClient, sends the recordName, and returns  a response
    this.recordId = response->id ? response->id : null;
}

private recordExists()
{
    return this.recordId !== null;
}

private updateRecordOnRemoteServer()
{
    someSoapClient->update('url', this.recordId); // notice the this.recordId reference
}

// omitting add method for brevity.
</code>```

But my boss (who has like 10 years more experience than me), told me I should pass the recordId as a parm to the update method, because otherwise the class suffers from a Orders Matter issue, and the update method is fragile, since it requires data that is set outside itself (retrieveRecordId()), and that has to be invoked by other method (in this case send()).

So the changes are really slight:

```<code>public send(recordName)
{
    // unchanged
    this.recordName = recordName;
    this.validateRecordName();

    // changed. Notice recordId is now a method var, not a class member.
    recordId = this.retrieveRecordId() // returns the id or null
    recordExists = recordId !== null;

    if (recordExists) {
        // notice the param is being passed
        this.updateRecordOnRemoteServer(recordId);
    } else {
        // add new record
    }
}
</code>```

I read Clean Code by Robert C. Martin, and most of his examples ended similar to what I proposed originally. He will initialize class memeber variables in the public method by invoking private methods, and those attributes will be used by other private methods; all in cascade.

When I first read the book I wasn't convinced it was "that clean" because I also thought that the class relied heavily on the invocation order of the private methods; but I started using that pattern in my own projects and I found it was helping me a lot to keep my code shorter and my public methods super readable.

I also learnt from the book to avoid passing params to private methods (unless there is no other way like sum(a, b), sub(a, b) kind of functions). 95% of the time he won't define arguments for private methods.

I would really like to know if there is a better approach.
Thank you!

答:
recordName and recordId are initialized and used during the execution of send, but they have existed before send was invoked and will continue to exist after send is done. Also, if send is called multiple times on the same object from different threads, the threads will mutate the same memory even though each needs different values, creating data races. It's not fun to have to synchronize threads that don't need to use the same data...

This is very similar to using global arguments - though the fact that they are private members touched by private methods helps containing the problem. The only reason Orders Matter is not an issue is that the class is small enough to easily notice when it raises problems. If the class gets bigger, it will become an issue.

When you have a subset of private methods that use a subset of private members, that usually means you need another class:

```<code>class Record {
    private recordName;
    private recordId;

    public Record(recordName) {
        this.recordName = recordName;

        validateRecordName();

        this.recordId = retrieveRecordId();
    }

    private retrieveRecordId()
    {
        response = // creates a soapClient, sends the recordName, and returns  a response
        return response->id ? response->id : null;
    }

    private validateRecordName()
    {
        // throws exception if this.recordName does not meet certain criteria
    }

    public recordExists()
    {
        return this.recordId !== null;
    }
}

public send(recordName)
{
    record = new Record(recordName);

    if (record.recordExists()) {
        this.updateRecordOnRemoteServer(record);
    } else {
        this.addRecordOnRemoteServer(record);
    }
}

private updateRecordOnRemoteServer(record)
{
    someSoapClient->update('url', record.recordId);
}
</code>```

Body:
recordName and recordId are initialized and used during the execution of send, but they have existed before send was invoked and will continue to exist after send is done. Also, if send is called multiple times on the same object from different threads, the threads will mutate the same memory even though each needs different values, creating data races. It's not fun to have to synchronize threads that don't need to use the same data...

This is very similar to using global arguments - though the fact that they are private members touched by private methods helps containing the problem. The only reason Orders Matter is not an issue is that the class is small enough to easily notice when it raises problems. If the class gets bigger, it will become an issue.

When you have a subset of private methods that use a subset of private members, that usually means you need another class:

class Record {
    private recordName;
    private recordId;

    public Record(recordName) {
        this.recordName = recordName;

        validateRecordName();

        this.recordId = retrieveRecordId();
    }

    private retrieveRecordId()
    {
        response = // creates a soapClient, sends the recordName, and returns  a response
        return response->id ? response->id : null;
    }

    private validateRecordName()
    {
        // throws exception if this.recordName does not meet certain criteria
    }

    public recordExists()
    {
        return this.recordId !== null;
    }
}

public send(recordName)
{
    record = new Record(recordName);

    if (record.recordExists()) {
        this.updateRecordOnRemoteServer(record);
    } else {
        this.addRecordOnRemoteServer(record);
    }
}

private updateRecordOnRemoteServer(record)
{
    someSoapClient->update('url', record.recordId);
}


问:
Is overriding Object.finalize() really bad?
The main two arguments against overriding Object.finalize() is that:

You don't get to decide when it's called.

It may not get called at all.

If I understand this correctly, I don't think those are good enough reasons to hate Object.finalize() so much.

It is up to the VM implementation and the GC to determine when the right time to deallocate an object is, not the developer. Why is it important to decide when Object.finalize() gets called?

Normally, and correct me if I'm wrong, the only time Object.finalize() wouldn't get called is when the application got terminated before the GC got a chance to run. However, the object got deallocated anyway when the application's process got terminated with it. So Object.finalize() didn't get called because it was not needed to be called. Why would the developer care?

Every time I'm using objects that I have to manually close (like file handles and connections), I get very frustrated. I have to be constantly checking if an object has an implementation of close(), and I'm sure I have missed a few calls to it at some points in the past. Why isn't it just simpler and safer to just leave it to the VM and GC to dispose of these objects by putting the close() implementation in Object.finalize()?

答:
Every time I'm using objects that I have to manually close (like file handles and connections), I get very frustrated. [...] Why isn't it just simpler and safer to just leave it to the VM and GC to dispose of these objects by putting the close() implementation in Object.finalize()?

Because file handles & connections (that is, file descriptors on Linux & POSIX systems) are quite a scarce resource (you might be limited to 256 of them on some systems, or to 16384 on some others; see setrlimit(2)). There is no guarantee that the GC will be called enough often (or at the right time) to avoid exhausting such limited resources. And if the GC is not called enough (or the finalization are not run at the right time) you'll be reaching that (possibly low) limit.

Finalization is a "best effort" thing in the JVM. It might not be called, or be called quite late... In particular, if you have a lot of RAM or if your program don't allocate a lot of objects (or if most of them die before being forwarded to some old enough generation by a copying generational GC), the GC could be called quite rarely, and the finalizations might not run very often (or even might not run at all).

So close file descriptors explicitly, if possible. If you are afraid of leaking them, use finalization as an extra measure, not as the main one.


答:
One of the biggest reasons not to rely of finalizers is that most of the resources one might be tempted to clean up in the finalizer are very limited. The garbage collector only runs every so often, since traversing references to determine whether or not something can be released is expensive. This means that it could 'be a while' before your objects actually get destroyed. If you have a lot of objects opening up short-lived database connections, for example, leaving the finalizers to clean up these connections could exhaust your connection pool while it waits for the garbage collector to finally run and free up finished connections. Then, because of the wait, you wind up with a large backlog of queued up requests, which quickly exhaust the connection pool again. It's a cycle that will quickly put your application into a crippled state of operation.

Additionally, the use of try-with-resources makes closing 'closable' objects on completion easy to do. If you are not familiar with this construct, I suggest you check it out:
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Title: Is overriding Object.finalize() really bad?

Body:
The main two arguments against overriding Object.finalize() is that:

You don't get to decide when it's called.

It may not get called at all.

If I understand this correctly, I don't think those are good enough reasons to hate Object.finalize() so much.

It is up to the VM implementation and the GC to determine when the right time to deallocate an object is, not the developer. Why is it important to decide when Object.finalize() gets called?

Normally, and correct me if I'm wrong, the only time Object.finalize() wouldn't get called is when the application got terminated before the GC got a chance to run. However, the object got deallocated anyway when the application's process got terminated with it. So Object.finalize() didn't get called because it was not needed to be called. Why would the developer care?

Every time I'm using objects that I have to manually close (like file handles and connections), I get very frustrated. I have to be constantly checking if an object has an implementation of close(), and I'm sure I have missed a few calls to it at some points in the past. Why isn't it just simpler and safer to just leave it to the VM and GC to dispose of these objects by putting the close() implementation in Object.finalize()?


答:
I have to be constantly checking if an object has an implementation of close(), and I'm sure I have missed a few calls to it at some points in the past.

In Eclipse, I get a warning whenever I forget to close something that implements Closeable/AutoCloseable. I'm not sure if that's an Eclipse thing or if it's part of the official compiler, but you might look into using similar static analysis tools to help you there. FindBugs, for example, can probably help you check whether you've forgotten to close a resource.


问:
What's special about "non-blocking" node.js?
In the short chapter, What is Node by McLaughlin, he writes:

"Node has no blocks, no threads competing for the same resource (Node
  is happy to just let things happen however they happen), nothing that
  has to start up upon request. Node just sits around waiting (quite
  literally; unused Node responders are sleeping). When a request comes
  in, it’s handled. This results in very fast code, without uber-
  programmers writing the server-side behavior."

While I think he's picking on PHP here - from what I understand there isn't a way for PHP to not call up new references to its databases, files, etc, whenever any php page is loaded - is this really different than other web technologies? Consider Django/Flask for example or a simple Python threaded-server using builtin methods - is it really any different than the no-blocks advantages of Node? You run a program and it binds a socket, running the function only as needed. (Doesn't Java also do this?)

答:
A Node program is at its core a normal program, it isn't even a web-server unless you write code specifically to make it so (though that is pretty easy with the built-in HTTP library). Your program will get the HTTP requests, and your code can respond any way you like, using all the resources otherwise available to the program.

If JavaScript was old-school linear execution you would, without some unwieldy complicated code, only be able to process one request at a time. This is pretty bad considering that most of the time taken handling a web request is usually spent waiting on I/O.

JavaScript program flow is however based on events, you set a handler as a piece of code that is run when an event happens, and when you are done handling that event JavaScript automatically goes on to the next event in the event queue. If you for instance need a piece of data from the database in order to handle a request you don't just wait for the database to answer, you set an event handler that fires when the database answers (often in the form of a callback function), and you complete the job when that happens, in the intervening time lots of other events may be handled.

This is what non-blocking means, you don't halt the entire program because you need to wait for something.

The great thing is, you still write your code in a mostly linear fashion, you usually don't have to pay much attention to the actual order of execution.


答:
Look at the matter this way: you should only be writing code that is (a) correct (otherwise your program is plain wrong) and (b) necessary (otherwise your code is too large, which means more RAM necessary, more cycles spent on useless things, more effort to understand it, more time spent on maintaining it etc. etc.)

Now consider what it is that you want done in a finalizer. Either it's necessary. In that case you can't put it into a finalizer, because you don't know if it will be called. That's not good enough. Or it it not necessary - then you shouldn't be writing it in the first place! Either way, putting it into the finalizer is the wrong choice.

(Note that the examples you name, like closing file streams, look as if they're not really necessary, but they are. It's just that until you hit the limit for open file handles on your system, you won't notice that your code is incorrect. But that limit is a feature of the operating system and is therefore even more unpredictable than the JVM's policy for finalizers, so it really, really is important that you don't waste file handles.)


答:
The problem is that you have a mutable class and private methods that act upon the state of the class.  Which means you have no real guarantee of what the state is at any particular point in time.

You should either ditch the methods that modify the state or initialize the state by passing the recordName into the constructor, and having the modifications apply to a particular instance.

Title: Clean Code: can private methods rely on member variables set by other private methods?

Body:
I was asked to create a class that will connect to a remote service via soap. The class has only one public method send(recordName).

The class ended like this:

```<code>private recordName;
private recordId;

public send(recordName)
{
    this.recordName = recordName;
    this.validateRecordName();
    this.retrieveRecordId();

    if (this.recordExists()) {
        this.updateRecordOnRemoteServer();
    } else {
        this.addRecordOnRemoteServer();
    }
}

private validateRecordName()
{
   // throws exception if this.recordName does not meet certain criteria
}

private retrieveRecordId()
{
    response = // creates a soapClient, sends the recordName, and returns  a response
    this.recordId = response->id ? response->id : null;
}

private recordExists()
{
    return this.recordId !== null;
}

private updateRecordOnRemoteServer()
{
    someSoapClient->update('url', this.recordId); // notice the this.recordId reference
}

// omitting add method for brevity.
</code>```

But my boss (who has like 10 years more experience than me), told me I should pass the recordId as a parm to the update method, because otherwise the class suffers from a Orders Matter issue, and the update method is fragile, since it requires data that is set outside itself (retrieveRecordId()), and that has to be invoked by other method (in this case send()).

So the changes are really slight:

```<code>public send(recordName)
{
    // unchanged
    this.recordName = recordName;
    this.validateRecordName();

    // changed. Notice recordId is now a method var, not a class member.
    recordId = this.retrieveRecordId() // returns the id or null
    recordExists = recordId !== null;

    if (recordExists) {
        // notice the param is being passed
        this.updateRecordOnRemoteServer(recordId);
    } else {
        // add new record
    }
}
</code>```

I read Clean Code by Robert C. Martin, and most of his examples ended similar to what I proposed originally. He will initialize class memeber variables in the public method by invoking private methods, and those attributes will be used by other private methods; all in cascade.

When I first read the book I wasn't convinced it was "that clean" because I also thought that the class relied heavily on the invocation order of the private methods; but I started using that pattern in my own projects and I found it was helping me a lot to keep my code shorter and my public methods super readable.

I also learnt from the book to avoid passing params to private methods (unless there is no other way like sum(a, b), sub(a, b) kind of functions). 95% of the time he won't define arguments for private methods.

I would really like to know if there is a better approach.
Thank you!


答:
In my experience, there is one and only one reason for overriding Object.finalize(), but it is a very good reason:

To place error logging code in finalize() which notifies you if you ever
  forget to invoke close().

Static analysis can only catch omissions in trivial usage scenarios, and the compiler warnings mentioned in another answer have such a simplistic view of things that you actually have to disable them in order to get anything non-trivial done.  (I have far more warnings enabled than any other programmer that I know of or ever heard of, but I don't have stupid warnings enabled.)

Finalization might seem to be a good mechanism for making sure that resources do not go undisposed, but most people see it in a completely wrong way: they think of it as an alternate fallback mechanism, a "second chance" safeguard which will automagically save the day by disposing of the resources that they forgot. This is dead wrong. There must be only one way of doing any given thing: either you always close everything, or finalization always closes everything.  But since finalization is unreliable, finalization cannot be it.

So, there is this scheme which I call Mandatory Disposal, and it stipulates that the programmer is responsible for always explicitly closing everything which implements Closeable or AutoCloseable.  (The try-with-resources statement still counts as explicit closing.)  Of course, the programmer may forget, so that's where finalization comes into play, but not as a magic fairy which will magically make things right in the end: If finalization discovers that close() was not invoked, it does not attempt to invoke it, precisely because there will (with mathematical certainty) be hordes of n00b programmers who will rely on it to do the job that they were too lazy or too absent minded to do.  So, with mandatory disposal, when finalization discovers that close() was not invoked, it logs a bright red error message, telling the programmer with big fat all-capital letters to fix his s-- er, his stuff.

As an additional benefit, rumor has it that "the JVM will ignore a trivial finalize() method (e.g. one which just returns without doing anything, like the one defined in the Object class)", so with mandatory disposal you can avoid all finalization overhead in your entire system (see alip's answer for information on how terrible this overhead is) by coding your finalize() method like this:

```<code>@Override
protected void finalize() throws Throwable
{
    if( Global.DEBUG && !closed )
    {
        Log.Error( "FORGOT TO CLOSE THIS!" );
    }
    //super.finalize(); see alip's comment on why this should not be invoked.
}
</code>```

The idea behind this is that Global.DEBUG is a static final variable whose value is known at compilation time, so if it is false then the compiler will not emit any code at all for the entire if statement, which will make this a trivial (empty) finalizer, which in turn means that your class will be treated as if it does not have a finalizer.  (In C# this would be done with a nice #if DEBUG block, but what can we do, this is java, where we pay apparent simplicity in the code with additional overhead in the brain.)

More about Mandatory Disposal, with additional discussion about disposing of resources in dot Net, here: michael.gr: Mandatory disposal vs. the "Dispose-disposing" abomination

Body:
In my experience, there is one and only one reason for overriding Object.finalize(), but it is a very good reason:

To place error logging code in finalize() which notifies you if you ever
  forget to invoke close().

Static analysis can only catch omissions in trivial usage scenarios, and the compiler warnings mentioned in another answer have such a simplistic view of things that you actually have to disable them in order to get anything non-trivial done.  (I have far more warnings enabled than any other programmer that I know of or ever heard of, but I don't have stupid warnings enabled.)

Finalization might seem to be a good mechanism for making sure that resources do not go undisposed, but most people see it in a completely wrong way: they think of it as an alternate fallback mechanism, a "second chance" safeguard which will automagically save the day by disposing of the resources that they forgot. This is dead wrong. There must be only one way of doing any given thing: either you always close everything, or finalization always closes everything.  But since finalization is unreliable, finalization cannot be it.

So, there is this scheme which I call Mandatory Disposal, and it stipulates that the programmer is responsible for always explicitly closing everything which implements Closeable or AutoCloseable.  (The try-with-resources statement still counts as explicit closing.)  Of course, the programmer may forget, so that's where finalization comes into play, but not as a magic fairy which will magically make things right in the end: If finalization discovers that close() was not invoked, it does not attempt to invoke it, precisely because there will (with mathematical certainty) be hordes of n00b programmers who will rely on it to do the job that they were too lazy or too absent minded to do.  So, with mandatory disposal, when finalization discovers that close() was not invoked, it logs a bright red error message, telling the programmer with big fat all-capital letters to fix his s-- er, his stuff.

As an additional benefit, rumor has it that "the JVM will ignore a trivial finalize() method (e.g. one which just returns without doing anything, like the one defined in the Object class)", so with mandatory disposal you can avoid all finalization overhead in your entire system (see alip's answer for information on how terrible this overhead is) by coding your finalize() method like this:

@Override
protected void finalize() throws Throwable
{
    if( Global.DEBUG && !closed )
    {
        Log.Error( "FORGOT TO CLOSE THIS!" );
    }
    //super.finalize(); see alip's comment on why this should not be invoked.
}

The idea behind this is that Global.DEBUG is a static final variable whose value is known at compilation time, so if it is false then the compiler will not emit any code at all for the entire if statement, which will make this a trivial (empty) finalizer, which in turn means that your class will be treated as if it does not have a finalizer.  (In C# this would be done with a nice #if DEBUG block, but what can we do, this is java, where we pay apparent simplicity in the code with additional overhead in the brain.)

More about Mandatory Disposal, with additional discussion about disposing of resources in dot Net, here: michael.gr: Mandatory disposal vs. the "Dispose-disposing" abomination


答:
I read Clean Code by Robert C. Martin, and most of his examples ended
  similar to what I proposed originally

Yes, that is his style. As far as I'm concerned he is giving bad advice which you should stop following right now.

For me, your version makes it unclear how things inter-relate.

```<code>public send(recordName)
{
    this.recordName = recordName;
    this.validateRecordName();
</code>```

Does this validate against the recordName I just stored? Probably, but I can't tell from here.

```<code>    this.retrieveRecordId();
</code>```

Does this depend on the validateRecordName() somehow? Or does it just depend on the recordName being stored? I can't tell.

```<code>    if (this.recordExists()) {
</code>```

Is this a reference to the id not being found? Or is it a reference to the name not being found?

```<code>        this.updateRecordOnRemoteServer();
    } else {
        this.addRecordOnRemoteServer();
    }
</code>```

What does these update/add? Do they set the name? Will my recordId be set afterwards? I don't know.

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

You version doesn't let me know how the different pieces relate unless I go an read them. I think this seen as readable by some, because your version looks a lot like a natural language description of the process. I think thats a bad idea because natural languages suck. I want a language that makes it explicit how everything relates.

The fact is, I don't think you far enough in your non-Robert Martin version. You still stored recordName on the instance, and you simply shouldn't do that.

```<code>public send(recordName)
{
    this.validateRecordName(recordName);

    recordId = this.retrieveRecordId(recordName) // returns the id or null
    recordExists = recordId !== null;

    if (recordExists) {
        // notice the param is being passed
        this.updateRecordOnRemoteServer(recordId);
    } else {
        this.addNewRecordOnRemoteServer(recordName);
    }
}
</code>```

Now I can tell how state moves between my different functions.

My rule is that you should only put things at the object level if they have the same lifetime as the object. Anything that is only meaningful for the lifetime of the send call should not be put on the object. Only things like connections to the server or perhaps a name -> id cache belong as a member instance.

Body:
I read Clean Code by Robert C. Martin, and most of his examples ended
  similar to what I proposed originally

Yes, that is his style. As far as I'm concerned he is giving bad advice which you should stop following right now.

For me, your version makes it unclear how things inter-relate.

public send(recordName)
{
    this.recordName = recordName;
    this.validateRecordName();

Does this validate against the recordName I just stored? Probably, but I can't tell from here.

    this.retrieveRecordId();

Does this depend on the validateRecordName() somehow? Or does it just depend on the recordName being stored? I can't tell.

    if (this.recordExists()) {

Is this a reference to the id not being found? Or is it a reference to the name not being found?

        this.updateRecordOnRemoteServer();
    } else {
        this.addRecordOnRemoteServer();
    }

What does these update/add? Do they set the name? Will my recordId be set afterwards? I don't know.

}

You version doesn't let me know how the different pieces relate unless I go an read them. I think this seen as readable by some, because your version looks a lot like a natural language description of the process. I think thats a bad idea because natural languages suck. I want a language that makes it explicit how everything relates.

The fact is, I don't think you far enough in your non-Robert Martin version. You still stored recordName on the instance, and you simply shouldn't do that.

public send(recordName)
{
    this.validateRecordName(recordName);

    recordId = this.retrieveRecordId(recordName) // returns the id or null
    recordExists = recordId !== null;

    if (recordExists) {
        // notice the param is being passed
        this.updateRecordOnRemoteServer(recordId);
    } else {
        this.addNewRecordOnRemoteServer(recordName);
    }
}

Now I can tell how state moves between my different functions.

My rule is that you should only put things at the object level if they have the same lifetime as the object. Anything that is only meaningful for the lifetime of the send call should not be put on the object. Only things like connections to the server or perhaps a name -> id cache belong as a member instance.


问:
Is this a Model or a ViewModel?
In a login screen, a user may expose his username and password data. The same way, in a user list screen, it may expose user name, age, and phone. But none of this views may expose any other user information like address and some others.

I was under the idea that an entity (in this case, user) is the Model itself. And then, viewmodels would be used to expose properties depending on the case:

```<code>LoginViewModel
  - username
  - password

UserListViewModel
  - name
  - age
  - telephone
</code>```

But in some cases I have seen these ViewModels called Models so I'm confused. Are these classes that expose certain properties called Model or ViewModels?

答: You are correct, a view model is a type designed specifically for the view, the view model may aggregate multiple models or maybe show a subset of a single model. in the context of MVC the M stands for Model, but when working with business logic we also have models, so to be clear in the the M in MVC is the View Model where we have business models referenced from outside of our mvc application.</p>

Title: Is this a Model or a ViewModel?


问:
How can I avoid needing to check for the existence another vertex when adding to an adjacency list?
I'm writing a Graph, and decided to make the Adjacency List its own class.

Right now, (stripped down) it looks like this:

```<code>public class AdjacencyList<Vertex> {

    //A map between a vertex, and a list of vertices that it connects to.
    private HashMap<Vertex, HashSet<Vertex>> vertices =
        new HashMap<Vertex, HashSet<Vertex>>();

    //Adds a new vertex, and gives it a list of outgoing vertices.
    public void addVertex(Vertex v, List<Vertex> outgoing) {
        vertices.put(v, new HashSet<Vertex>(outgoing));
    }

    //Adds a directed (one-way) edge to the given vertex.
    public void addDirectedToVertex(Vertex v, Vertex newVertex) {
        HashSet<Vertex> outgoingList = vertices.get(v);
        if (outgoingList != null) {
            outgoingList.add(newVertex);

        } else {
            throw new NoSuchElementException("Vertex " + v + " doesn't exist.");
        }
    }

}
</code>```

Which was fine, until I realized that it's possible to add a vertex to a vertex's outgoing list that doesn't have its own spot in the hash map. This could lead to someone adding a vertex to another vertex's outgoing list that doesn't otherwise exist anywhere; which I'm sure would cause problems down the road.

To fix it, I thought of adding a check to the top before the addition. If the vertex to be added to the list doesn't exist in the HashMap, I could either throw, or give it its own entry. Something like this:

```<code>//Adds a directed (one-way) edge to the given vertex.
public void addDirectedToVertex(Vertex v, Vertex newVertex) {
    if (!vertices.containsKey(newVertex)) {
        addVertex(newVertex);
    }

    HashSet<Vertex> outgoingList = vertices.get(v);
    if (outgoingList != null) {
        outgoingList.add(newVertex);

    } else {
        throw new NoSuchElementException("Vertex " + v + " doesn't exist.");
    }
}
</code>```

Unfortunately, that means that every addition will require 2 lookups, which seems unnecessarily complicated.

Is this something I should be concerning myself about, or would this be considered pre-mature optimization?

If this is a legitimate problem, can any-one see a way to reconfigure things to improve it?

答:
Checking whether an element exists in a hash map is fairly cheap. Hash maps give fast lookups; it's what they do. I wouldn't worry about it, especially if you aren't actively encountering bad performance. The value of having good, resilient, failfast code is better than having code that might be trivially faster but makes it easier to introduce bugs.

One thing to consider is Amdahl's law. It doesn't make a lot of sense to worry about the insertion performance of your graph, when the computational cost of most algorithms working on your graph (because there's no point in having a graph if you're not going to do anything with it) will be orders of magnitude more expensive than putting things into the graph.