问:
designing domain model that can handle large number of data filters?
I'm currently working on a project that I came into several years after it was built. The code is mostly procedural with a few objects that act more like buckets of functions than anything else. I want to start fixing it up by consolidating the database access and external API calls into domain models.

I have the general idea down, but I don't know how to handle getting lists of my data when I have multiple filters. Having methods called $HelpRequestMapper->getById($id) work fine, but what do I do when the user wants to do multiple filters?

Should I have methods for each possible case? Ie, $HelpRequestMapper->getByCompanyAndUserAssignedToAndQueueAndStatusAndPriorityAndSearchString($company_id, $user_id, $queue_id, $status, $priority, $search_string) This seems like it would get unwieldy very fast and not be much better than what we have now.

Should I pass in an array/object and build a query from it using something like $HelpRequestMapper->getMultiple($array_of_options) that does some magical query building stuff to get the data I want?

Should I do something else?

Thanks

答:
It depends a bit on the implementation of the filter, but you could look into the Decorator Pattern and Strategy Pattern and see if they are of use to you.

You could solve this by creating an abstract Filter class with a filter-method that takes a list of objects and returns a list of objects. Each type of filter (CompanyFilter, UserAssignedFilter, QueueFilter...) would be a separate class that extends filter. When creating the filter you would pass the filter criteria in the constructor, and the implementation of the filter-method would take the objects passed to it and only return the ones matching the filter.

You could then have a RequestQuery that you can push filters onto which fetches the data, runs the data through all the filters and returns the result.

Quick demo in C#

```<code>public class MyObject
{
    public string Company { get; set; }
    public string UserAssignedTo { get; set; }
}

public abstract class Filter
{
    public abstract IEnumerable<MyObject> Apply(IList<MyObject> list);
}

public class CompanyFilter : Filter
{
    private string _companyToFilter;

    public CompanyFilter(string companyToFilter)
    {
        _companyToFilter = companyToFilter;
    }

    public override IEnumerable<MyObject> Apply(IList<MyObject> list)
    {
        return list.Where(x => x.Company == _companyToFilter);
    }
}

public class UserAssignedToFilter: Filter
{
    private string _userToFilter;

    public UserAssignedToFilter(string userToFilter)
    {
        _userToFilter = userToFilter;
    }

    public override IEnumerable<MyObject> Apply(IList<MyObject> list)
    {
        return list.Where(x => x.UserAssignedTo == _userToFilter);
    }
}

public class RequestQuery
{
    public IEnumerable<MyObject> FindData(IList<Filter> filtersToApply)
    {
        IList<MyObject> data = null; //fetch data somewhere

        foreach(var filter in filtersToApply)
        {
            data = filter.Apply(data);
        }

        return data;
    }
}
</code>```

Body:
It depends a bit on the implementation of the filter, but you could look into the Decorator Pattern and Strategy Pattern and see if they are of use to you.

You could solve this by creating an abstract Filter class with a filter-method that takes a list of objects and returns a list of objects. Each type of filter (CompanyFilter, UserAssignedFilter, QueueFilter...) would be a separate class that extends filter. When creating the filter you would pass the filter criteria in the constructor, and the implementation of the filter-method would take the objects passed to it and only return the ones matching the filter.

You could then have a RequestQuery that you can push filters onto which fetches the data, runs the data through all the filters and returns the result.

Quick demo in C#

public class MyObject
{
    public string Company { get; set; }
    public string UserAssignedTo { get; set; }
}

public abstract class Filter
{
    public abstract IEnumerable<MyObject> Apply(IList<MyObject> list);
}

public class CompanyFilter : Filter
{
    private string _companyToFilter;

    public CompanyFilter(string companyToFilter)
    {
        _companyToFilter = companyToFilter;
    }

    public override IEnumerable<MyObject> Apply(IList<MyObject> list)
    {
        return list.Where(x => x.Company == _companyToFilter);
    }
}

public class UserAssignedToFilter: Filter
{
    private string _userToFilter;

    public UserAssignedToFilter(string userToFilter)
    {
        _userToFilter = userToFilter;
    }

    public override IEnumerable<MyObject> Apply(IList<MyObject> list)
    {
        return list.Where(x => x.UserAssignedTo == _userToFilter);
    }
}

public class RequestQuery
{
    public IEnumerable<MyObject> FindData(IList<Filter> filtersToApply)
    {
        IList<MyObject> data = null; //fetch data somewhere

        foreach(var filter in filtersToApply)
        {
            data = filter.Apply(data);
        }

        return data;
    }
}


问:
Can I update an attached object using a detached but equal object?
I retrieve movie data from an external API. In a first phase I will scrape each movie and insert it into my own database. In a second phase I will periodically update my database by using the API's "Changes" API which I can query to see what movies have had their information changed.

My ORM layer is Entity-Framework. The Movie class looks like this:

```<code>class Movie
{
    public virtual ICollection<Language> SpokenLanguages { get; set; }
    public virtual ICollection<Genre> Genres { get; set; }
    public virtual ICollection<Keyword> Keywords { get; set; }
}
</code>```

The problem arises when I have a movie that needs to be updated: my database will think of the object being tracked and the new one that I receive from the update API call as different objects, disregarding .Equals().

This causes a problem because when I now try to update the database with the updated movie, it will insert it instead of updating the existing Movie.

I had this issue before with the languages and my solution was to search for the attached language objects, detach them from the context, move their PK to the updated object and attach that to the context. When SaveChanges() is now executed, it will essentially replace it.

This is a rather smelly approach because if I continue this approach to my Movie object, it means I'll have to detach the movie, the languages, the genres and the keywords, look up each one in the database, transfer their IDs and insert the new objects.

Is there a way to do this more elegantly? Ideally I just want to pass in the updated movie to the context and have that select the correct movie to update based on the Equals() method, update all its fields and for each complex object: use the existing record again based on its own Equals() method and insert if it doesn't exist yet.

I can skip the detaching/attaching by providing .Update() methods on each complex object which I can use in combination of retrieving all the attached objects but this will still require me to retrieve every single existing object to then update it.

答:
I didn't find what I was hoping for but I did find an improvement over the existing select-detach-update-attach sequence.

The extension method AddOrUpdate(this DbSet) allows you to do exactly what I want to do: Insert if it's not there and update if it found an existing value. I didn't realize using this sooner since I've really only seen it be used in the seed() method in combination with Migrations. If there is any reason I shouldn't use this, let me know.

Something useful to note: There is an overload available which allows you to specifically select how equality should be determined. Here I could have used my TMDbId but I instead opted to simply disregard my own ID altogether and instead use a PK on TMDbId combined with DatabaseGeneratedOption.None. I use this approach on each subcollection as well, where appropriate.

Interesting part of the source:

```<code>internalSet.InternalContext.Owner.Entry(existing).CurrentValues.SetValues(entity);
</code>```

which is how the data is actually updated under the hood.

All that is left is calling AddOrUpdate on each object that I want to be affected by this:

```<code>public void InsertOrUpdate(Movie movie)
{
    _context.Movies.AddOrUpdate(movie);
    _context.Languages.AddOrUpdate(movie.SpokenLanguages.ToArray());
    // Other objects/collections
    _context.SaveChanges();
}
</code>```

It isn't as clean as I hoped since I have to manually specify each piece of my object that needs to be updated but it's about as close as it will get.

Related reading: https://stackoverflow.com/questions/15336248/entity-framework-5-updating-a-record

Update:

It turns out my tests weren't rigorous enough. After using this technique I noticed that while the new language was added, it wasn't connected to the movie. in the many-to-many table. This is a known but seemingly low-priority issue and hasn't been fixed as far as I know.

In the end I decided to go for the approach where I have Update(T) methods on each type and follow this sequence of events:

Loop over collections in new object

For each entry in each collection, look it up in the database

If it exists, use the Update() method to update it with the new values

If it doesn't exist, add it to the appropriate DbSet

Return the attached objects and replace the collections in the root object with the collections of the attached objects

Find and update the root object

It's a lot of manual work and it's ugly so it'll go through a few more refactorings but now my tests indicate it should work for more rigorous scenarios.

After cleaning it up further I now use this method:

```<code>private IEnumerable<T> InsertOrUpdate<T, TKey>(IEnumerable<T> entities, Func<T, TKey> idExpression) where T : class
{
    foreach (var entity in entities)
    {
        var existingEntity = _context.Set<T>().Find(idExpression(entity));
        if (existingEntity != null)
        {
            _context.Entry(existingEntity).CurrentValues.SetValues(entity);
            yield return existingEntity;
        }
        else
        {
            _context.Set<T>().Add(entity);
            yield return entity;
        }
    }
    _context.SaveChanges();
}
</code>```

This allows me to call it like this and insert/update the underlying collections:

```<code>movie.Genres = new List<Genre>(InsertOrUpdate(movie.Genres, x => x.TmdbId));
</code>```

Notice how I reassign the retrieved value to the original root object: now it is connected to each attached object. Updating the root object (the movie) is done the same way:

```<code>var localMovie = _context.Movies.SingleOrDefault(x => x.TmdbId == movie.TmdbId);
if (localMovie == null)
{
    _context.Movies.Add(movie);
}
else
{
    _context.Entry(localMovie).CurrentValues.SetValues(movie);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I didn't find what I was hoping for but I did find an improvement over the existing select-detach-update-attach sequence.

The extension method AddOrUpdate(this DbSet) allows you to do exactly what I want to do: Insert if it's not there and update if it found an existing value. I didn't realize using this sooner since I've really only seen it be used in the seed() method in combination with Migrations. If there is any reason I shouldn't use this, let me know.

Something useful to note: There is an overload available which allows you to specifically select how equality should be determined. Here I could have used my TMDbId but I instead opted to simply disregard my own ID altogether and instead use a PK on TMDbId combined with DatabaseGeneratedOption.None. I use this approach on each subcollection as well, where appropriate.

Interesting part of the source:

internalSet.InternalContext.Owner.Entry(existing).CurrentValues.SetValues(entity);

which is how the data is actually updated under the hood.

All that is left is calling AddOrUpdate on each object that I want to be affected by this:

public void InsertOrUpdate(Movie movie)
{
    _context.Movies.AddOrUpdate(movie);
    _context.Languages.AddOrUpdate(movie.SpokenLanguages.ToArray());
    // Other objects/collections
    _context.SaveChanges();
}

It isn't as clean as I hoped since I have to manually specify each piece of my object that needs to be updated but it's about as close as it will get.

Related reading: https://stackoverflow.com/questions/15336248/entity-framework-5-updating-a-record

Update:

It turns out my tests weren't rigorous enough. After using this technique I noticed that while the new language was added, it wasn't connected to the movie. in the many-to-many table. This is a known but seemingly low-priority issue and hasn't been fixed as far as I know.

In the end I decided to go for the approach where I have Update(T) methods on each type and follow this sequence of events:

Loop over collections in new object

For each entry in each collection, look it up in the database

If it exists, use the Update() method to update it with the new values

If it doesn't exist, add it to the appropriate DbSet

Return the attached objects and replace the collections in the root object with the collections of the attached objects

Find and update the root object

It's a lot of manual work and it's ugly so it'll go through a few more refactorings but now my tests indicate it should work for more rigorous scenarios.

After cleaning it up further I now use this method:

private IEnumerable<T> InsertOrUpdate<T, TKey>(IEnumerable<T> entities, Func<T, TKey> idExpression) where T : class
{
    foreach (var entity in entities)
    {
        var existingEntity = _context.Set<T>().Find(idExpression(entity));
        if (existingEntity != null)
        {
            _context.Entry(existingEntity).CurrentValues.SetValues(entity);
            yield return existingEntity;
        }
        else
        {
            _context.Set<T>().Add(entity);
            yield return entity;
        }
    }
    _context.SaveChanges();
}

This allows me to call it like this and insert/update the underlying collections:

movie.Genres = new List<Genre>(InsertOrUpdate(movie.Genres, x => x.TmdbId));

Notice how I reassign the retrieved value to the original root object: now it is connected to each attached object. Updating the root object (the movie) is done the same way:

var localMovie = _context.Movies.SingleOrDefault(x => x.TmdbId == movie.TmdbId);
if (localMovie == null)
{
    _context.Movies.Add(movie);
}
else
{
    _context.Entry(localMovie).CurrentValues.SetValues(movie);
}


问:
What are the underlying patterns in systems allowing asynchronous operations?
Say I'm working with a system that allows async, nonblocking operations.  If I queue up a set of those operations and specify their result buffer references:

```<code>nonblocking_write( message, write_buffer );
nonblocking_read( source, read_buffer );
nonblocking_read( other_source, other_read_buffer );

wait();

// do stuff with results now in the buffers
</code>```

or queue up the same set of operations, but specify result callbacks to do stuff with results directly

```<code>nonblocking_write( message, write_handler );
nonblocking_read( source, read_handler );
nonblocking_read( other_source, other_read_handler );

// doing stuff happens in the result handlers, not here
</code>```

My question is about the library or environment exposing the nonblocking_*() operations.  What software structures and patterns allow this kind of thing to happen?

These are my thoughts so far:

In a multithreaded environment, spawn a new thread within the nonblocking operation, then run an equivalent blocking operation within that thread.

In a  single threaded environment, define an event construct and tasks that handle 'events', then have nonblocking operations push event/task pairs into a queue for an event loop to run later.  (I think this is how JavaScript does it.)

答:
Since no one else has answered and I've now had a full day to remember all my old comp sci courses, I'll try writing a proper answer this time.

To the best of my knowledge, all asynchronous behavior in computers is at some level implemented by putting things in a queue and coming back to that queue later to process the things when it's more convenient. When you create a thread, you're pushing some thread-identifying information onto a queue that live inside the OS kernel. When you fire an event or send a message--in every language and framework I'm familiar with--you're pushing an event or message object into an event queue or a mailbox or whatever one wishes to call it.

Of course, the devil is in the (implementation) details, and there are a lot of details.

With Javascript, what I just said is the whole story: the browser has a simple queue of events that it resolves one at a time in order. In particular, it assumes each event handler is a single function call that will simply run to completion without incident.

With OS threads, you don't have functions to call, but tasks to execute for a set time frame. Thus you have a hardware timer interrupt that periodically forces the CPU to go execute the OS kernel's thread scheduling routine.

Network sockets are a bit special because the "queue" is not really a queue, in that it's not FIFO or LIFO or any other definite ordering. Instead, the OS has to constantly poll your networking hardware to see if it has any new data, and when it does, it has to figure out who that data belongs to, because it has no way of knowing whose requests will finish first. The "queue" is probably more like a map from port numbers to execution contexts that need to be resumed when data matching that port number finally appears.

It should go without saying that these implementations have very different priorities with regards to stability, predictability, optimizeability, and interoperability.


问:
Enums in java switch-statements and completeness
I feel like I should be able to find an answer to this, but it turns out to be harder to search than expected... so:

In C#, when we do something like:

```<code>enum MyEnumClass { A, B };

static String Test(MyEnumClass m)
{
    switch (m)
    {
        case MyEnumClass.A: return "the value was A";
        case MyEnumClass.B: return "the value was B";
        //default: return "The value was ????"; //we need to uncomment this
    }
}
</code>```

we get a "not all code paths return a value" error and need to add the default case, because enums are actually just numbers in disguise and we might be calling the method with a value we didn't cover like so:

```<code>test((MyEnumClass)53)
</code>```

However, I don't think we can do such a thing (call the method with anything else than our two enum-values) in Java (Or can we?). Still, if we write similar code in Java, we get a similar error. If this is the case, is there any reason why the compiler cant figure out such a switch statement is complete and hence that the default case isn't necessary?

答:
Imagine what would happen if you decided that enum needed a new value, but that enum is being used in a thousand switch statements just like that one. Because Java forced them all to have a default case when they wrote those switches, then whatever logging statement or exception throw everyone chose to put there will probably save them a lot of headaches when you make that change.

If the Java compiler accepted those thousand switch statements with only two cases because they cover all the values...then you can't ever add your third value, because nobody's code would compile anymore. And as ddyer pointed out, separate compilation makes such a check impossible in the general case.

So you're left with either always requiring a default case, or never requiring it. Since Java has a very different philosophy from C++, it chose the former.

Also, Enums in Java can be null, so you have to be prepared for that.


问:
Is logging next to an implementation a SRP violation?
When thinking of agile software development and all the principles (SRP, OCP, ...) I ask myself how to treat logging.

Is logging next to an implementation a SRP violation?

I would say yes because the implementation should be also able to run without logging. So how can I implement logging in a better way? I've checked some patterns and came to a conclusion that the best way not to violate the principles in a user-defined way, but to use any pattern which is known to violate a principle is to use a decorator pattern.

Let's say we have a bunch of components completely without SRP violation and then we want to add logging.

component A

component B uses A

We want logging for A, so we create another component D decorated with A both implementing an interface I.

interface I

component L (logging component of the system)

component A implements I

component D implements I, decorates/uses A, uses L for logging

component B uses an I

Advantages:
- I can use A without logging
- testing A means I don't need any logging mocks
- tests are simpler

Disadvantage:
- more components and more tests

I know this seem to be another open discussion question, but I actually want to know if someone uses better logging strategies than a decorator or SRP violation. What about static singleton logger which are as default NullLogger and if syslog-logging is wanted, one change the implementation object at runtime?

答:
Of course it's a violation of SRP as you have a cross cutting concern. You can however create a class that is responsible for composing the logging with execution of any action.

example:

```<code>class Logger {
   ActuallLogger logger;
   public Action ComposeLog(string msg, Action action) {
      return () => {
          logger.debug(msg);
          action();
      };
   }
}
</code>```

Body:
Of course it's a violation of SRP as you have a cross cutting concern. You can however create a class that is responsible for composing the logging with execution of any action.

example:

class Logger {
   ActuallLogger logger;
   public Action ComposeLog(string msg, Action action) {
      return () => {
          logger.debug(msg);
          action();
      };
   }
}


答:
The reason the compiler will prompt "not all code paths return a value" is because it notices that your switch case does not cover all of the possibilities.  This is NOT a restriction on the type of object you are using a switch on.  If you return a value in the default case, the compiler reads it as a way of handling the case for other possible values.

Another option is to add a return statement after the switch statement.

Title: Enums in java switch-statements and completeness

Body:
I feel like I should be able to find an answer to this, but it turns out to be harder to search than expected... so:

In C#, when we do something like:

```<code>enum MyEnumClass { A, B };

static String Test(MyEnumClass m)
{
    switch (m)
    {
        case MyEnumClass.A: return "the value was A";
        case MyEnumClass.B: return "the value was B";
        //default: return "The value was ????"; //we need to uncomment this
    }
}
</code>```

we get a "not all code paths return a value" error and need to add the default case, because enums are actually just numbers in disguise and we might be calling the method with a value we didn't cover like so:

```<code>test((MyEnumClass)53)
</code>```

However, I don't think we can do such a thing (call the method with anything else than our two enum-values) in Java (Or can we?). Still, if we write similar code in Java, we get a similar error. If this is the case, is there any reason why the compiler cant figure out such a switch statement is complete and hence that the default case isn't necessary?


问:
Mixing jQuery with JavaScript
I just asked this question at SO about some bugginess I am experiencing with jQuery and IE8, and someone commented that he was appalled that I would mix JavaScript with jQuery (he has since deleted his comment for some reason).

This person had a high reputation, relative to mine (3000+), so I don't want to ignore his criticism. I'm still relatively new to web development, and I mostly work alone, so I wasn't aware that this could be a problem. Why should mixing the two be avoided?

答: I prefer to mix them. I usually start off with using strictly (or mostly) jQuery. Since things can get quite CPU intensive with projects I work on that involve possibly 100's of widgets. I find that writing in jQuery is a great start, but when I want to start optimizing my products, I switch a lot of what I can to JavaScript. jQuery is great, but obviously running the native code is faster in most cases.</p>

Title: Mixing jQuery with JavaScript


问:
Why do schools teach arrays over List?
Most of the assignments in my school for the initial programming classes required me to use arrays. I work full time now, and I never used an array for any project that I have worked on. Even in the exisiting projects I never saw the use of arrays anywhere. In my opinion, List is easier to use and is a standard. Why do professors tell students to use arrays in their assignments? Is it just so that students understand the basics? </p>

<p>Since most of the universities teach Java, this question is specific to Java. </p>

答:
One reason that first-year programming classes use arrays is legacy: that's how the professors originally learned it before we started using standard libraries with dynamic lists baked in. Using the primitive data types is also more generally applicable: arrays exist in pretty much any computer language under the sun (and can be implemented in a handful of assembly instructions). When I was first learning programming, implementing a linked list was one of the assignments.

It's much easier to start from first-principles and then say "That's the basic structure. This language (or its libraries) gives you this high-level data structure that does all that, but gives you x, y, and z," than it is to say "So that's these high-level data structures, now here's what's under the hood." Learning to reason about whether to use a LinkedList vs. an ArrayList (or a HashSet vs. a TreeSet) is usually a second or third-year Algorithms course. Lists and Maps have the same interfaces and give the same results, but can have dramatically different behaviors in an application of any size. And once you get out of Programming 101, there's no guarantee that Programming 102 will be using the same language. If you start from the concept of an array, you can just say "this is how you use arrays in this language", rather than trying to explain why you don't get all the fancy things that Java Lists give you. And once you get out into "the real world", there are still people out there who have to program in C (particularly in high-performance projects where you need to get as close to the metal as possible).

Another reason to prefer "array" over "List" in an introductory course is that arrays are fundamentally easy to understand: An array of 20 bytes takes 20 bytes (plus a couple to indicate either the end of the array or the length, depending on implementation).

A "List" is a completely different kettle of fish and can be implemented in many different ways (ArrayList, LinkedList, and probably a couple I've forgotten), with fundamentally different performance characteristics. Without understanding the guts of what the different List classes are doing, you can't have a meaningful discussion of when you should use List foo = new ArrayList() vs. List foo = new LinkedList(). If you try to get the student to use a List implementation, someone is going to ask why you're using ArrayList instead of one of the other implementations. And "ArrayList" includes the word "Array" and is backed by one, so it really isn't a huge logic jump from "array" to "ArrayList".

Contrary to popular belief, there ARE situations in which it makes sense to use arrays over Lists, particularly when you're dealing with a list of static size. Here are a couple:

Lookup and iteration are slightly faster because you're not dealing with method invocation overhead: foo[n] dereferences and does some behind-the-scenes pointer arithmetic, while foo.get(n) has to dereference, do a method invocation, do a second dereference, and then maybe do pointer arithmetic (if you're using an ArrayList; LinkedLists potentially need to iterates over every element of the List).

Initialization is much cleaner: int[] foo = new int[]{1, 2, 3, 4, 5} vs. the suggestions in Another StackOverflow question

Title: Why do schools teach arrays over List?


问:
Use of validators for simple validations
I've been working in Liferay code, and I've come across this construct a few times:

```<code>List<?> list;
...
if (Validator.isNotNull(list)) {
    //do stuff
}}
</code>```

The source code for Validator.java looks like this:

```<code>public static boolean isNotNull(Object obj) {
    return !isNull(obj);
}

public static boolean isNull(String obj) {
    ...
}

public static boolean isNull(Long obj) {
    ...
}

public static boolean isNull(Integer obj) {
    ...
}

public static boolean isNull(Object obj) {
    if (obj instanceof String) {
        return isNull((String)obj);
    }

    if (obj instanceof Long) {
        return isNull((Long)obj);
    }

    if (obj instanceof Integer) {
        return isNull((Integer)obj);
    }

    return obj == null;
}
</code>```

So my question: what are the benefits of calling Validator to do this function rather than simply writing if (obj == null)? Do these function calls add a significant enough overhead that it is worth avoiding this method of programming?

答:
Look at the implementation of isNull for different types. Such as string:

```<code>public static boolean isNull(String s) {
    if (s == null) {
        return true;
    }

    s = s.trim();

    if ((s.length() == 0) || (s.equals(StringPool.NULL))) {
        return true;
    }

    return false;
}
</code>```

This is not the same as obj == null, because if obj has a value of "\t ", the null comparison will return false. On the other hand, isNull will return true because of the s = s.trim() followed by s.length() == 0.

If you've used .NET Framework, the isNull(String s) is what is called string.IsNullOrWhiteSpace()—a much better name for the method.

For instance, in your first piece of code, if list is an empty, non-null list:

list == null will return false,

Validator.isNull(list) will return true.

Do these function calls add a significant enough overhead that it is worth avoiding this method of programming?

Since the method doesn't do the same thing as obj == null, comparing its performance makes no real sense. The caller of isNull uses this method because it is convenient when checking for, say, a null or empty list, or a null, empty or whitespace string.

Obviously, if the only thing you need is to check whether the variable is null, just do obj == null; Validator.isNull is not for that (despite its name).

Note that the isNull(Object) overload does an additional job of comparing the type of the object and eventually doing a cast. This means that when using the validator library, you should try to always work with typed variables. For instance:

```<code>Object obj = this.loadSomethingFromProxy();
if (Validator.isNotNull(obj))
{
    something = (Long)obj;
    this.doStuff(something);
}
</code>```

should be refactored into:

```<code>Long something = (Long)this.loadSomethingFromProxy();
if (Validator.isNotNull(obj))
{
    this.doStuff(something);
}
</code>```

because in the later case, you are doing the cast only once (instead of twice) and then call the isNotNull(Long) overload, skipping type checking.

Body:
Look at the implementation of isNull for different types. Such as string:

public static boolean isNull(String s) {
    if (s == null) {
        return true;
    }

    s = s.trim();

    if ((s.length() == 0) || (s.equals(StringPool.NULL))) {
        return true;
    }

    return false;
}

This is not the same as obj == null, because if obj has a value of "\t ", the null comparison will return false. On the other hand, isNull will return true because of the s = s.trim() followed by s.length() == 0.

If you've used .NET Framework, the isNull(String s) is what is called string.IsNullOrWhiteSpace()—a much better name for the method.

For instance, in your first piece of code, if list is an empty, non-null list:

list == null will return false,

Validator.isNull(list) will return true.

Do these function calls add a significant enough overhead that it is worth avoiding this method of programming?

Since the method doesn't do the same thing as obj == null, comparing its performance makes no real sense. The caller of isNull uses this method because it is convenient when checking for, say, a null or empty list, or a null, empty or whitespace string.

Obviously, if the only thing you need is to check whether the variable is null, just do obj == null; Validator.isNull is not for that (despite its name).

Note that the isNull(Object) overload does an additional job of comparing the type of the object and eventually doing a cast. This means that when using the validator library, you should try to always work with typed variables. For instance:

Object obj = this.loadSomethingFromProxy();
if (Validator.isNotNull(obj))
{
    something = (Long)obj;
    this.doStuff(something);
}

should be refactored into:

Long something = (Long)this.loadSomethingFromProxy();
if (Validator.isNotNull(obj))
{
    this.doStuff(something);
}

because in the later case, you are doing the cast only once (instead of twice) and then call the isNotNull(Long) overload, skipping type checking.


问:
How did desktop applications communicate with remote server before webservices?
I don't have lot of expierence with desktop applications, but if I had to create a client server desktop app, the data access would be done through a webservice. I believe data access through a webservice provides security - I don't need to pass in the db server user name and password etc.

Before webservices, how did database applications do this? Was all the important db information passed into the installlation of the desktop app? If so how did programmers manage the security aspect? Or did programmers use something similar to webservices?

答:
Depending on what you call a web service.

Before WSDL and REST, there was still HTTP, so basically everything you can do now could be done before as well.

There was a lack of uniformity (which is why WSDL and REST were created in the first place), but it provided the same level of data confidentiality and security you are talking about.

You can actually avoid using HTTP as well: you can draft your own protocol, and use a custom server and custom clients which would open a socket to this server and get the data they need (or post the data). Here, you lose all the standardization benefit of HTTP, but once again, you don't give access to the database to the clients.


答:
Ah, back when we had sticks and stones.

Before the Internet, we had something called "client/server" architecture and Local Area Networks.  If you weren't trying to establish a connection with a server several miles away, these networks worked perfectly fine to accomplish most anything.  You could even establish drive letters and use connections to file servers like a remote hard drive, if you wanted to.  If you were several miles away, you could use a Wide Area Network to do essentially the same thing, albeit at a slower speed and at greater expense.

The cheap way to talk remotely was to pass information across telephone lines using devices called modems, and if you wanted to rig up something where two computers talked to each other through computer applications, you did it the same way you do it today: by establishing a communications protocol. There's nothing magical at all about that; both sides just have to agree on what all the bytes mean.

From the very early stages of the Internet, there were ways for machines to communicate across it.  Web Services are just the latest flavor of the week.

Title: How did desktop applications communicate with remote server before webservices?

Body:
I don't have lot of expierence with desktop applications, but if I had to create a client server desktop app, the data access would be done through a webservice. I believe data access through a webservice provides security - I don't need to pass in the db server user name and password etc.

Before webservices, how did database applications do this? Was all the important db information passed into the installlation of the desktop app? If so how did programmers manage the security aspect? Or did programmers use something similar to webservices?


问:
Don't repeat yourself vs do only one thing in a method
I am currently writing some test cases in python. I often end up calling the same two or three lines of code at the start of a test case in order to get the program I am testing going. For example:

```<code>test_something_foo():
    call_method_a(x)
    call_method_b(y)
    # test some stuff

test_something_bar():
    call_method_a(x)
    call_method_b(y)
    # test some other stuff
</code>```

This means I am repeating those two lines together over and over. So I thought to extract like so:

```<code>test_something_foo():
    call_method_a_and_b(x,y)
    # test some stuff

test_something_bar():
    call_method_a_and_b(x,y)
    # test some other stuff

call_method_a_and_b(x, y):
    call_method_a()
    call_method_b()
</code>```

But I am not sure if this is a good idea. On the one hand it solves the "don't repeat yourself" principle, but doesn't my method "call_method_a_and_b()" violate the principle of "a method should do one thing, and one thing only". How do you reconcile those two seemingly conflicting design principles??

答:
This is what setUp is for. It is executed automatically before running each test, and can be used to initialize class fields and properties or set up the environment (in a case of integration and system tests).

As for the one thing principle, it is perfectly fine to have a method A which calls methods B and C if the method A is acting on a different level of abstraction than B and C.

What would be a violation of one thing principle is to put the bodies of the method B and C inside the method A.

Example: in order to create a product, you need to:

Store the product in the database,

Store the product image on disk.

Those two actions can be put in a method createProduct implemented like this:

```<code>def createProduct(self):
    self.db.storeProduct(product_model)
    self.moveImage(product_model.image_upload_path)
</code>```

The method createProduct performs one thing: it creates a product. On the other hand, if the method actually went in the details of database manipulation and files storage, then it would be doing multiple things.

Body:
This is what setUp is for. It is executed automatically before running each test, and can be used to initialize class fields and properties or set up the environment (in a case of integration and system tests).

As for the one thing principle, it is perfectly fine to have a method A which calls methods B and C if the method A is acting on a different level of abstraction than B and C.

What would be a violation of one thing principle is to put the bodies of the method B and C inside the method A.

Example: in order to create a product, you need to:

Store the product in the database,

Store the product image on disk.

Those two actions can be put in a method createProduct implemented like this:

def createProduct(self):
    self.db.storeProduct(product_model)
    self.moveImage(product_model.image_upload_path)

The method createProduct performs one thing: it creates a product. On the other hand, if the method actually went in the details of database manipulation and files storage, then it would be doing multiple things.


问:
How to write a new annotation that behaves precisely like an existing one?
Here is my use case. Suppose annotations did have inheritance and would automatically inherit the entire behaviour of the base class. Then I would do the following (note the two package statements):

```<code>package cdiswitcher.precdi;
public @interface SessionScoped extends javax.faces.bean.SessionScoped {}
public @interface ManagedBean extends javax.faces.ManagedBean {}

package cdiswitcher.cdi;
public @interface SessionScoped extends javax.enterprise.context.SessionScoped {}
public @interface ManagedBean extends javax.inject.Named {}
</code>```

The same for various other annotation pairs such as @ejb and @inject. This would simplify switching between the two bean injection systems: Just replace every instance of cdiswitcher.precdi by cdiswitcher.cdi, or vice versa.

Another use case might be extending the behaviour of an annotation, perhaps even creating a single new annotation that has the same effect as two existing ones.

答:
For your particular problem, you can write a CDI extension to find beans with your custom annotation (or the base annotation you're find-and-replacing) and use it to modify the bean definitions in the deployment. For example, the CODI library (as I recall) does this to re-use @javax.faces.bean.ViewScoped for its own custom view scope.

With this theoretical extension you could write classes using JSF 2 annotations and run them in a CDI project without modifying the code.

Switching between @EJB and @Inject is not quite as simple as they work differently in some ways and don't really work as direct replacements for each other.

If possible, it would be much simpler to write the shared classes as simple POJOs, then write a CDI wrapper and a JSF wrapper as separate JARs, so the implementation isn't tied to any container in particular.


答:
Just to clear up some concepts first...

I believe data access through a webservice provides security - I don't need to pass in the db server user name and password etc.

I think you are conflating the concepts of (1) Transport Layer Security (TLS) and (2) access controls in the above statement... Whether a user name and password needs to be supplied or not is unrelated to whether a web service is provided through (1) an encrypted channel and (2) authentication (e.g. an API key).

An extremely poorly written web service may still require passwords to be sent in plaintext over HTTP. A poorly written one may do that over HTTPS (secure, but once broken, e.g. through a man-in-the-middle attack, open to abuse). A better-written web service should handle database connectivity internally based on other inputs, e.g. session IDs, after authentication and entitlement controls are validated.

Back to the main point, @marcus's comment on your question is essentially it. Security aspects are dealt with no differently from "modern" technologies, and that covers implementation questions such as:

Whether your communications protocol (borrowing a little bit from @RobertHarvey's answer) supports the transmission of encrypted data.

The message payload structure that is relayed between the server and client.

Does the client simply tell the server to persist this user's residential address, or to connect to a database at IP X.X.X.X with a user name and password, and then run the query INSERT INTO user_address ...?

How the server manages its database connectivity (which really is isolated from the client, see first paragraph).

For more information:

Web Service Security Cheat Sheet (from OWASP)

Common Object Request Broker Architecture

Remote Procedure Call


问:
Should I extend an interface or keep it independent?
I'm trying to decide whether to extend a base interface with additional methods or create several independent interfaces. I have a Task interface that looks like this

```<code>interface Task
{
    public function name();
    public function run(array $args);
}
</code>```

Now I want to add optional description and dependencies methods. Should I create a new DetailedTask interface like this?

```<code>interface DetailedTask extends Task
{
    public function description();
    public function dependencies();
}
</code>```

This way I could choose to implement either the base Task interface for a basic task class, or the DetailedTask interface if I needed a description and dependencies. Alternately I could create separate interfaces for the extra methods like this.

```<code>interface Describable
{
    public function description();
}

interface TaskDependent
{
    public function dependencies();
}
</code>```

According to the interface segregation principle, the second is better because it is more flexible. However, I don't ever anticipate using Describable and TaskDependent on anything besides a Task instance. The extra interfaces just seem to add extra complexity. Which technique should I use?

答:
First of all, with your question details:

Now I want to add optional description and dependencies methods.

If you want an optional method, then you should not go for interface, because as per interface rules, you MUST need to define methods in implementation class. See PHP interface.

So according to that rule, your first solution will not work because if you define class that implements DetailedTask, then that class must define both method description and dependencies.

The second way will give you freedom to choose whatever interface you want to implement.


答:
Always go for separate interfaces in this case. As the task part is mandatory and the second part is optional.

Interface always forces to override all the methods mentioned in it.

Now think if you don't want to use the optional part. Still you will have to override it. Even if it doesn't do anything.

Title: Should I extend an interface or keep it independent?

Body:
I'm trying to decide whether to extend a base interface with additional methods or create several independent interfaces. I have a Task interface that looks like this

```<code>interface Task
{
    public function name();
    public function run(array $args);
}
</code>```

Now I want to add optional description and dependencies methods. Should I create a new DetailedTask interface like this?

```<code>interface DetailedTask extends Task
{
    public function description();
    public function dependencies();
}
</code>```

This way I could choose to implement either the base Task interface for a basic task class, or the DetailedTask interface if I needed a description and dependencies. Alternately I could create separate interfaces for the extra methods like this.

```<code>interface Describable
{
    public function description();
}

interface TaskDependent
{
    public function dependencies();
}
</code>```

According to the interface segregation principle, the second is better because it is more flexible. However, I don't ever anticipate using Describable and TaskDependent on anything besides a Task instance. The extra interfaces just seem to add extra complexity. Which technique should I use?


答:
If you can think of a better name than call_method_a_and_b(), a name that is a single concept, then it isn't a violation of the 'one thing' principle.

If you are calling a and b in that order for different reasons in foo than in bar, so one of the two call sites might need to change while the other stays the same, then you aren't violating DRY.  (For instance, foo might need to change to call b and then a, while bar needs to keep the original order.)

So, evaluate whether it is a coincidence that you're calling a and b in that order, or whether the pair of them in that order represents an idea or concept.  Don't make a method if it's a coincidence, and do if it's an idea.  Just make sure not to name the method call_method_a_and_b().

Title: Don't repeat yourself vs do only one thing in a method

Body:
I am currently writing some test cases in python. I often end up calling the same two or three lines of code at the start of a test case in order to get the program I am testing going. For example:

```<code>test_something_foo():
    call_method_a(x)
    call_method_b(y)
    # test some stuff

test_something_bar():
    call_method_a(x)
    call_method_b(y)
    # test some other stuff
</code>```

This means I am repeating those two lines together over and over. So I thought to extract like so:

```<code>test_something_foo():
    call_method_a_and_b(x,y)
    # test some stuff

test_something_bar():
    call_method_a_and_b(x,y)
    # test some other stuff

call_method_a_and_b(x, y):
    call_method_a()
    call_method_b()
</code>```

But I am not sure if this is a good idea. On the one hand it solves the "don't repeat yourself" principle, but doesn't my method "call_method_a_and_b()" violate the principle of "a method should do one thing, and one thing only". How do you reconcile those two seemingly conflicting design principles??


问:
Web application security: Need a 2 phase check?
(Is this the best forum for this type of question?)

I'm writing a web application which allows approved users to login, and perform various tasks, depending on the security role(s) they have been assigned.

I'm guessing that to prevent users from performing tasks that their roles don't permit, this should probably entail 2 main phases:

Present web pages which contain only the options (menus, pages, buttons, fields, etc) that the user should be able to access, on the web pages.  (This is basically working, already.)

In case a user tries some hacking (e.g. posting fields/values which their webpage doesn't allow them to post), double check all actions before processing them.  (This sounds pretty complex in some areas, to me.)

Does this strategy sound appropriate/normal/necessary?  Any tips or links to pages which discuss this, before I possibly spend a lot of time going down the wrong track?

I'm using Perl/MySQL on Linux, though the principles might be generic.

Thanks.

答:
You're on the right track, but missing one key point: All validation/authentication must be done (or double-checked) by the server, because you cannot trust the client. Maybe you already had this in mind, but it's worth stating explicitly. And yes, you definitely need to do both 1 and 2.

In principle the logic for 1 and 2 should be exactly the same. A type 1 check determines whether a UI element is shown, and a type 2 check determines whether a command gets processed, but the actual checks should be identical. So I'm very curious why you think 2 would be significantly more complex; maybe this points to an architecture problem somewhere.


问:
2 Classes that share similar behaviours but unrelated.
I'm working on something at the moment and am a little confused.

I'm working on an enquiry system in PHP (it's Opencart Based, so MVC).

An enquiry comes in and depending on what form it was submitted from, depends on what folder it goes into to, folders pretty much mirror the categories, so an enquiry coming from TeeShirts for example would be in a folder called TeeShirts.
Folders aren't set up dynamically, they're manually set up by the admin.

I have something very similar at the moment, a Class for 'Status', the class can add/remove/modify status, tag status to enquiry, count status etc.

So.. The status class almost does exactly what I want the folder class to do, but the folder class is integral to the program, where as the enquiry class can be dropped, or replaced. The two things share lots similarities, enough so, that I'm thinking of creating a base class.

It's the fact that the folders are pretty much at the core of my application, I'm having second thoughts about tying them in together.

I'm looking for some advice just to get me started off, as I'm pretty new to programming, especially OOP, so ANY advice is welcome.

答:
The question is a little unclear, but it sounds like you need to revisit your class design. My analysis is that you are selling Products which belong to a Category and are stored in an Inventory (in your case a flat-file data store).

You will also need a ProductStatus class to hold stuff queried from the inventory e.g. Number in stock, isCurrentProduct() and perhaps details of variants (e.g. T shirt sizes).

Once you get the class hierarchy clean, code should automatically have one correct place to live. Some expectations:

Inventory needs to know about products, but products should have no knowledge of how they are stored. If you are lucky, your store may expand and need a proper SQL database to hold the inventory. If you design it right, you only need to replace the inventory implementation. In Java I would enforce this by defining an IInventory interface, but I'm not sure what your options are in PHP - perhaps an Inventory abstract base class?.

The ProductStatus class is likely to have almost no behavioural methods. Its job in life is to act as a data bucket transporting data beyween between the inventory and the GUI.

The Folder class may exist inside your Inventory implementation, but should not leak out into the GUI, as it is an implementation detail.

Good luck - I hope this gives you something to think about.


问:
In C++, how to call an 'init' routine as a class is loaded?
I have a program that loads a bunch of "addons" (different meters that measure and display system values).

The "addons" have "grown" over time and the code of what addons to "activate",
and how many of each (if there is more than one of the "device" in the
system (cpu's, net-interfaces, etc)  is hard-coded into the master.  Ug
(and ick).

What I want is for each addon-meter to place it's name and init-routine-addr
into an array as they are loaded.  Right now, what meters that are loaded
are fixed in the master at compile time.  What I want is for the possibility
of dynamic loading, but more importantly, for external "script-extensions"
(that could measure "almost anything" and rely on the master to display
the collected data (like a script that would read outdoor temperature via
some 3rd party device).  In other words -- long after the master has been
compiled, I want to provide the ability for other addon meters to be added
as long as they supply a specific callable API.

Thus, as a new extension is added, I need some init routine to be called
as it loads that will place the new meter-name and routine to be called
in a class-singleton that has an array of the extension names and
their init-routine addresses (as in a dynamically loaded extension).

Then when execution starts, each extension will already have have "registered"
itself with a central list that the "master" can look at and know what
to call.

In Perl, I've used something in a "BEGIN{...} block" in loaded extensions
to call a Plug_Common->register("plugin name", \%Plugin_Description_Data); so when the main routine started it would look in the plugin-registry to see
what was available, dynamically, at runtime.

The question is, how do I do this in C++?

I've setup register routine, but I've no idea how to have the extensions
get their "name & address" registered before the main-master runs.  Theoretically, since some of the extensions could be added via scripts long after the main-master was written -- it wouldn't be able to know their names in advance.

Off the top of my head, I can only think of a "user-edited" static text file, that might be able to have the master, "somehow(?!)" call each extensions init and 'get_config' routine.  Then I can get rid of all the 'extension/meter-specific'-knowledge out of the the master.  I don't like the text-file idea as it's too prone to user-error -- having something being able to automatically call a register-function as it is loaded, seems much less likely to have problems like the static-config file being out-of-sync with what extensions can be used on the system.

Any ideas? (I'd rather not have to build in a copy of something like Perl to handle the dynamic "loadability" of modules...to me, that would be 'ugly'...

Seem a bit unreliable for the master program to try to look through some
symbol table at runtime -- especially with C++'s strong typing.  I keep coming up with flaws in virtually every method I think of. :-(.  Anyone know a better way?  ;-)...

Update:

Had a thought (well more than one, but this one is a bit unconventional, but might work)  What if each of the plugins declared a shared pointer to a global list in the master?)  If the shared pointers were used in module level inits, then wouldn't the shared 'use count' be incremented as the modules were loaded?...hmmm... I don't know yet how to get the modules' addresses into the main array (without them getting any execution time), but if I can figure out a way for an initializer statement using the shared_ptr, then since loading it a non-multithreaded (at least at this point) if that pointer could be leveraged to increment and store the address of an init function, in a global array, that might give me my dynamic config?  Right now, the only thing I know for sure is that shared pointers do have an accessible 'use_count' -- which would only help me in determining how many plugins had registered.  Maybe there is no way to make this work, but just a thought (at 5:45am after I've been up all night... so, may be completely flawed and I just don't see it yet...;-))...   Anyway, thought I'd add my latest thoughts;  For scripts I'm thinking of splitting off that type of plugin into a separate handler that would have to read some config... I don't really like it, but it does isolate those things that wouldn't load @ program start time...  Anyone think it is possible to leverage the shared-pointer to do this?

答:
In most plugin systems in C and C++, the loading of plugins works like this:

The main application specifies a path where the plugins should be located (or allows such a path to be configured). On startup, the application looks for either dynamically loadable libraries (DLLs on Windows, .so on Linux, in case of compiled plugins) or scripts (in case of interpreted/scripted plugins) in the plugin path.

For each plugin that it finds, the application tries to call an init/registration function that allows the plugin to register itself with the application. For interpreted/scripted plugins, this could be the main body of the script.

To support interpreted/scripted plugins, the application needs to incorporate a scripting engine that understands the language that the plugin is written in.

When writing a compiled plugin, one of the rules is that you build it as a dynamically loadable library and that you provide the initialization function with the exact name and signature that the main application expects.

Furthermore, any classes that the plugin provides must be derived from an interface specified by the main application for plugins that provide a certain service.

For a scripted plugin, the requirement is that the initialization function performs the initializations and registrations that are expected by the main application.

ContentLicense: CC BY-SA 4.0


问:
Working with two different database types for one application
Software: Java J2EE Application hosted on Tomcat Server.

UPDATE

The current software is JAVA Web application containing just JSP and Servlets no frameworks or anything. Simple  JSP and Servlets communicating with Oracle DB

I have no issues in re-writing the application, but since the two
  copies of it will be maintained I want the code to be same and so when
  applying a change I need to apply them same on both places. Instead of
  writing two sets of different code I want to keep the code same while
  and intermediate layer to handle the DB communication

Software with same code is being hosted and run at two different locations miles away(two separate instances).
Initially the back-end database of the application was same(viz. Oracle).
Now one of the location has stopped the support on oracle and is switching to the Open Source Postgres.

So now the (to be) scenario is something like this

Software: Java J2EE Application hosted on Tomcat Server.

Database 1: Oracle

Database 2: Postgres

At any point of time the application will be using only one database as they are running different instances.

Can an intermediate be added that can interpret the request from application and query depending on the database which needs to be used to fetch data. if yes which is the best option for that.

All this so that every time there is a change in the application, the change takes place uniquely on each copies and an overhead of maintaining two different copies can be avoided.

答:
This is essentially what an Object/Relational Mapping Framework (such as Hibernate) can do for you. It provides a layer on top of the database that abstracts away the details of querying the database by providing a database-independent layer and query language. Hibernate provides (among other ways of querying the database) HQL for this:

```<code>from Cat as cat
left join cat.kittens as kitten
    with kitten.bodyWeight > 10.0
</code>```

While this looks a lot like regular SQL it is acutally an intermediary language that will be translated to the dialect of SQL the underlying database system uses.

Body:
This is essentially what an Object/Relational Mapping Framework (such as Hibernate) can do for you. It provides a layer on top of the database that abstracts away the details of querying the database by providing a database-independent layer and query language. Hibernate provides (among other ways of querying the database) HQL for this:

from Cat as cat
left join cat.kittens as kitten
    with kitten.bodyWeight > 10.0

While this looks a lot like regular SQL it is acutally an intermediary language that will be translated to the dialect of SQL the underlying database system uses.


问:
What about source code homogeneity?
As time passes I think that one valuable aspect of maintenable and escalable software is to be homogeneous. The same problem should be solved in the same way everywhere in the application. If there is a reason to change how you do something then it should be changed everywhere and if the effort is not worth it then you should continue doing it like in the past.

It is much easier to maintain (and write good code) and application when it's done like this than the other way around, when your first task when modifying a module is to understand how was structured the head of the developer that wrote it.

How can I properly manage and maintain my code base in a large project?

答:
Code style is indeed very important for overall readability, and part of code style means being consistent with said style, even to the extent of respecting the original intentions of the coder that created it or completely redoing it entirely.  However, refactoring code is notoriously difficult, and even moreso with projects that have had many project owners over several years.

This is why it is very important that the general practice of you following the style of the rest of the program.  Think about it for a second, would you inherit a project with inconsistent coding style and structure had every programmer that worked before you followed this simple rule?  No.  And since it is easier to add code that follows the general code style of the rest of the program than to refactor, best practice talks about preventative practices, not how best to refactor an already inconsistent project.

That said, you typically don't see articles written about why it is important to be consistent in your code style because it is sort of a given.  It would be like writing an article describing why the god object anti-pattern should be avoided whenever possible.  Obviously you are likely going to continue your project as you tend to write it, but others may not necessarily do so, so really if you inherit an inconsistent project, it's already too late on that front.

My advice to you would be to get a feel for the different code styles in your program, and pick the one most used in your program and/or the one that is the most straightforward.  Then, whenever you need to touch up a class that doesn't quite follow this norm, make a point to ask more time to make the change so that you can make an effort to refactor that class.  You'll eventually have something that is consistent throughout, and should another programmer take over your project, we can only hope that they'll continue where you left off.

Title: What about source code homogeneity?


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Definitely method overloading using type hinting to differentiate the method signatures. Even further, I would like to see some kind of ASP.NET style "attributes", so that my controller actions in a PHP MVC framework could look like this:</p>

```<code>/* [HttpGet] */
public function login() {}

/* [HttpPost] */
public function login() {}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Definitely method overloading using type hinting to differentiate the method signatures. Even further, I would like to see some kind of ASP.NET style "attributes", so that my controller actions in a PHP MVC framework could look like this:

/* [HttpGet] */
public function login() {}

/* [HttpPost] */
public function login() {}


问:
How is the facade pattern different from abstraction layers?
I just read about the facade pattern and found this example where a client (user of a computer) invokes a startComputer() method which calls on all the complex stuff:

Source: wikipedia

```<code>/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}

class Memory {
    public void load(long position, byte[] data) { ... }
}

class HardDrive {
    public byte[] read(long lba, int size) { ... }
}

/* Facade */

class Computer {
    private CPU cpu;
    private Memory memory;
    private HardDrive hardDrive;

    public Computer() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
    }

    public void startComputer() {
        cpu.freeze();
        memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
        cpu.jump(BOOT_ADDRESS);
        cpu.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        Computer facade = new Computer();
        facade.startComputer();
    }
}
</code>```

Here we can see the client class (You) creating a new facade, calling the startComputer() method. This method instantiates several objects and invokes their methods, encapsulating it inside the facade class where it 'glues it together'.

Question 1:

But exactly how is this different from layers of abstraction?

Yesterday I made login functionality for a web application where a doLogin($username, $password) encapsulated a 'complex' lower-layer method call that updated login info about the user, set sessions to log in with and instantiated several objects etc. to do this job.

This layer would also call another even lower level which would deal with CRUD-like operations such as checking activation status, account existance and other things like processing strings through hashing algorithms. This method (on model level, look 'layer overview' below) would return an array with either a 'success' key or a 'error_message' key, acting as a boolean of sorts to the layer calling it.

This is what I understand is known as 'abstraction layers', hiding complex procedures from the higher-level architecture, but when I read about the facade pattern it seems like I have been using it all along?

Question 2:

Would my approach to abstracting the login mechanism be a bad choice in a MVC architecture? (if not, please give examples why)

Taken into consideration it should be very easy to decide where the end result goes (HTML, AJAX, etc.), wouldn't this be a wise choice to avoid alot of IFs as this can be dealt with on a controller layer?

Layer overview:

Controller layer: $model->doLogin(POST VARIABLES HERE)

Model layer: (Is this a facade?) Sets sessions, updates login information in database etc., calls independent components for information: $user_id = $user->getId(); and $session->sessionExists();

Independent class layer: Each class on this layer is independent and has little to no coupling. After all, why would it? It's the layer above's job to build the application and lend an API to control it with.

Question 3:

Is the facade pattern only used for routing calls to sub-classes in an API-like form, or perhaps just most commonly?

With this I mean: Object A instantiates object B and lends a method to control object B's methods through a method of it's own:

```<code><?php

class A {
    private $_objectB;

    public function __construct()
    {
        $this->_objectB = new B();
    }

    public function callMethodB()
    {
        $this->_objectB->methodB();
    }
}

class B {
    public function methodB()
    {
        die('Wuhu!');
    }
}

// --------------------------
$objectA->callMethodB(); // Wuhu!
</code>```

instead of:

```<code>$objectA->objectB->methodB(); // Wuhu!
</code>```

答:
You are totally interpreting it wrong. To sum up in one line "A facade pattern gives a simplified interface wherein we can use functionalities of a complex sub system". Use case of Facade pattern is to provide an accessor to the underlying low level methods of a complex service/package/component etc.

Following things don't come in the use case of facade :

An abstraction for processes (This may be a part,but this should not be the sole purpose)

Encapsulate processes in one process

Facade is used only for providing one concrete implementation for all the low level methods

A facade pattern should generally be used when we are designing a complex package which goes deep down into sub-systems and complexity. A Facade is just an accessor to the underlying lopw level metjods of a complex service/package/component etc.

Eg:

Step 1

Create an interface.

Shape.java:

```<code>public interface Shape {
   void draw();
}
</code>```

Step 2

Create concrete classes implementing the same interface.

Rectangle.java

```<code>public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Rectangle::draw()");
   }
}
</code>```

Square.java

```<code>public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Square::draw()");
   }
}
</code>```

Circle.java

```<code>public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Circle::draw()");
   }
}
</code>```

Step 3

Create a facade class.

ShapeMaker.java

```<code>public class ShapeMaker {
   private Shape circle;
   private Shape rectangle;
   private Shape square;

   public ShapeMaker() {
      circle = new Circle();
      rectangle = new Rectangle();
      square = new Square();
   }

   public void drawCircle(){
      circle.draw();
   }
   public void drawRectangle(){
      rectangle.draw();
   }
   public void drawSquare(){
      square.draw();
   }
}
</code>```

Step 4

Use the facade to draw various types of shapes.

FacadePatternDemo.java

```<code>public class FacadePatternDemo {
   public static void main(String[] args) {
      ShapeMaker shapeMaker = new ShapeMaker();

      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();
   }
}
</code>```

Step 5

Verify the output.

```<code>Circle::draw()
Rectangle::draw()
Square::draw()
</code>```

This pattern involves a single class which provides simplified methods
  required by client and delegates calls to methods of existing system
  classes.

Body:
You are totally interpreting it wrong. To sum up in one line "A facade pattern gives a simplified interface wherein we can use functionalities of a complex sub system". Use case of Facade pattern is to provide an accessor to the underlying low level methods of a complex service/package/component etc.

Following things don't come in the use case of facade :

An abstraction for processes (This may be a part,but this should not be the sole purpose)

Encapsulate processes in one process

Facade is used only for providing one concrete implementation for all the low level methods

A facade pattern should generally be used when we are designing a complex package which goes deep down into sub-systems and complexity. A Facade is just an accessor to the underlying lopw level metjods of a complex service/package/component etc.

Eg:

Step 1

Create an interface.

Shape.java:

public interface Shape {
   void draw();
}

Step 2

Create concrete classes implementing the same interface.

Rectangle.java

public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Rectangle::draw()");
   }
}

Square.java

public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Square::draw()");
   }
}

Circle.java

public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Circle::draw()");
   }
}

Step 3

Create a facade class.

ShapeMaker.java

public class ShapeMaker {
   private Shape circle;
   private Shape rectangle;
   private Shape square;

   public ShapeMaker() {
      circle = new Circle();
      rectangle = new Rectangle();
      square = new Square();
   }

   public void drawCircle(){
      circle.draw();
   }
   public void drawRectangle(){
      rectangle.draw();
   }
   public void drawSquare(){
      square.draw();
   }
}

Step 4

Use the facade to draw various types of shapes.

FacadePatternDemo.java

public class FacadePatternDemo {
   public static void main(String[] args) {
      ShapeMaker shapeMaker = new ShapeMaker();

      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();
   }
}

Step 5

Verify the output.

Circle::draw()
Rectangle::draw()
Square::draw()

This pattern involves a single class which provides simplified methods
  required by client and delegates calls to methods of existing system
  classes.


答:
The question is, how do I do this in C++?

You will not be able to map the Perl initialization in C++ without making it explicit.

Components for a plugin system in C++:

define your plugin interface as a header file (will probably contain the declaration of a plugin initialization function/class, a configuration base class interface and class factory, a plugin base class interface and a plugin class factory (or similar)). This header file will be used by both plugins and the master application, to understand each other.

create an empty plugin that implements this interface fully and keep it for reference [good for maintenance, development of plugins, proof of concept and documentation example].

write high-level client library for the master application, for working with plugins. Test that it loads your empty plugin [good for making work with plugins easy in the master application].

describe plugins in a simple text/json/xml file. Keep the format as simple as possible. This will allow you to add different plugins into your application, at runtime (because it is much easier to edit a line in a configuration file and add a comment, than to remember where you have to move dynamic libraries on your hard drive.

Document steps for developing a new plugin based on the empty one, and keep the steps up to date in the docs.

Edit (addressing comments):

My prototype code already has the interface being pure-virtual, so I can use dynamic_casting at run time to get at the needed data

Don't do that (the dynamic_cast thing). Instead, define a richer protocol between the application and the plugins. Define (for example) an event-based protocol in the virtual interface, and call through that:

```<code>struct your_plugin_class
{
virtual void on_init() = 0; // called from the application, on initialization
};
</code>```

My main problem right now, is how to have plugins "register" themselves (in so much as to putting their init-function in a call-array, that the master can use to dynamically adapt to whatever list of plugins have been inserted on a given run -- without recompilation.

Create a plugin manager that opens files at a given location, with a pattern-matching name (for example, "do-this-and-that.your-app.plugin.so" - something that fits nicely into a regular expression). Within this library, simply call a custom class factory.

You could even have the plugin manager be an active object and keep an in-memory list of the loaded plugins. Periodically, you iterate the plugin files, and if there are differences, load them on the active object thread. Your application would pick plugins at run-time.

Title: In C++, how to call an 'init' routine as a class is loaded?

Body:
I have a program that loads a bunch of "addons" (different meters that measure and display system values).

The "addons" have "grown" over time and the code of what addons to "activate",
and how many of each (if there is more than one of the "device" in the
system (cpu's, net-interfaces, etc)  is hard-coded into the master.  Ug
(and ick).

What I want is for each addon-meter to place it's name and init-routine-addr
into an array as they are loaded.  Right now, what meters that are loaded
are fixed in the master at compile time.  What I want is for the possibility
of dynamic loading, but more importantly, for external "script-extensions"
(that could measure "almost anything" and rely on the master to display
the collected data (like a script that would read outdoor temperature via
some 3rd party device).  In other words -- long after the master has been
compiled, I want to provide the ability for other addon meters to be added
as long as they supply a specific callable API.

Thus, as a new extension is added, I need some init routine to be called
as it loads that will place the new meter-name and routine to be called
in a class-singleton that has an array of the extension names and
their init-routine addresses (as in a dynamically loaded extension).

Then when execution starts, each extension will already have have "registered"
itself with a central list that the "master" can look at and know what
to call.

In Perl, I've used something in a "BEGIN{...} block" in loaded extensions
to call a Plug_Common->register("plugin name", \%Plugin_Description_Data); so when the main routine started it would look in the plugin-registry to see
what was available, dynamically, at runtime.

The question is, how do I do this in C++?

I've setup register routine, but I've no idea how to have the extensions
get their "name & address" registered before the main-master runs.  Theoretically, since some of the extensions could be added via scripts long after the main-master was written -- it wouldn't be able to know their names in advance.

Off the top of my head, I can only think of a "user-edited" static text file, that might be able to have the master, "somehow(?!)" call each extensions init and 'get_config' routine.  Then I can get rid of all the 'extension/meter-specific'-knowledge out of the the master.  I don't like the text-file idea as it's too prone to user-error -- having something being able to automatically call a register-function as it is loaded, seems much less likely to have problems like the static-config file being out-of-sync with what extensions can be used on the system.

Any ideas? (I'd rather not have to build in a copy of something like Perl to handle the dynamic "loadability" of modules...to me, that would be 'ugly'...

Seem a bit unreliable for the master program to try to look through some
symbol table at runtime -- especially with C++'s strong typing.  I keep coming up with flaws in virtually every method I think of. :-(.  Anyone know a better way?  ;-)...

Update:

Had a thought (well more than one, but this one is a bit unconventional, but might work)  What if each of the plugins declared a shared pointer to a global list in the master?)  If the shared pointers were used in module level inits, then wouldn't the shared 'use count' be incremented as the modules were loaded?...hmmm... I don't know yet how to get the modules' addresses into the main array (without them getting any execution time), but if I can figure out a way for an initializer statement using the shared_ptr, then since loading it a non-multithreaded (at least at this point) if that pointer could be leveraged to increment and store the address of an init function, in a global array, that might give me my dynamic config?  Right now, the only thing I know for sure is that shared pointers do have an accessible 'use_count' -- which would only help me in determining how many plugins had registered.  Maybe there is no way to make this work, but just a thought (at 5:45am after I've been up all night... so, may be completely flawed and I just don't see it yet...;-))...   Anyway, thought I'd add my latest thoughts;  For scripts I'm thinking of splitting off that type of plugin into a separate handler that would have to read some config... I don't really like it, but it does isolate those things that wouldn't load @ program start time...  Anyone think it is possible to leverage the shared-pointer to do this?

Body:
The question is, how do I do this in C++?

You will not be able to map the Perl initialization in C++ without making it explicit.

Components for a plugin system in C++:

define your plugin interface as a header file (will probably contain the declaration of a plugin initialization function/class, a configuration base class interface and class factory, a plugin base class interface and a plugin class factory (or similar)). This header file will be used by both plugins and the master application, to understand each other.

create an empty plugin that implements this interface fully and keep it for reference [good for maintenance, development of plugins, proof of concept and documentation example].

write high-level client library for the master application, for working with plugins. Test that it loads your empty plugin [good for making work with plugins easy in the master application].

describe plugins in a simple text/json/xml file. Keep the format as simple as possible. This will allow you to add different plugins into your application, at runtime (because it is much easier to edit a line in a configuration file and add a comment, than to remember where you have to move dynamic libraries on your hard drive.

Document steps for developing a new plugin based on the empty one, and keep the steps up to date in the docs.

Edit (addressing comments):

My prototype code already has the interface being pure-virtual, so I can use dynamic_casting at run time to get at the needed data

Don't do that (the dynamic_cast thing). Instead, define a richer protocol between the application and the plugins. Define (for example) an event-based protocol in the virtual interface, and call through that:

struct your_plugin_class
{
virtual void on_init() = 0; // called from the application, on initialization
};

My main problem right now, is how to have plugins "register" themselves (in so much as to putting their init-function in a call-array, that the master can use to dynamically adapt to whatever list of plugins have been inserted on a given run -- without recompilation.

Create a plugin manager that opens files at a given location, with a pattern-matching name (for example, "do-this-and-that.your-app.plugin.so" - something that fits nicely into a regular expression). Within this library, simply call a custom class factory.

You could even have the plugin manager be an active object and keep an in-memory list of the loaded plugins. Periodically, you iterate the plugin files, and if there are differences, load them on the active object thread. Your application would pick plugins at run-time.


答:
If you have time to spare to refactor code, then you should spend it DRYing the code rather than homogenising it.

Trying to get all developers in a team to do things the same way is not the problem to solve. The problem is that everyone has a different style in which they can think about code the most logically - that's what you want to optimise - give everyone freedom of expression. What you need to ensure is that each time a developer applies her style it is only used to write code suited to one problem once i.e. DRYness.

Title: What about source code homogeneity?

Body:
As time passes I think that one valuable aspect of maintenable and escalable software is to be homogeneous. The same problem should be solved in the same way everywhere in the application. If there is a reason to change how you do something then it should be changed everywhere and if the effort is not worth it then you should continue doing it like in the past.

It is much easier to maintain (and write good code) and application when it's done like this than the other way around, when your first task when modifying a module is to understand how was structured the head of the developer that wrote it.

How can I properly manage and maintain my code base in a large project?


问:
php Database operations in separate files?
I have a single page application. Select boxes need to be filled with select queries from the database.

How do I structure the application?

Currently I have a file add_details.php. It contains a HTML form with select queries to fill select boxes and if a user submits a form.

```<code>if ($_SERVER['REQUEST_METHOD'] == "POST") {
    // Code for inserting data
}
</code>```

The below code is executed all in one page.

Should I separate and create a PHP file for insert and a PHP file to get results from the database?

I find separating things makes things cleaner but results in far too many files being created for select queries and inserts.

I use require_once 'SELECT query file' to populate the select boxes is there any easier way to do the above? is it necessary to create a a separate select query file?

答:
Should I separate and create a PHP file for insert and a PHP file to get results from the database?

First, you may separate your data access from the business logic by moving data access code to a data access layer. For instance, if the select boxes are populated with the list of countries, then you'll have to call:

```<code>$this->db->listCountries();
</code>```

from your business logic instead of doing directly the PDO stuff and the actual select ... from.

The next step is to consider what should be done with the business logic which is processing the submission of the form. You might decide that this is totally independent from the code which populates the form, in which case a separate file makes sense; however, in most cases, you'll consider that both actions are related, and keep them in the same file.

From your question, I'm not sure how advanced you are in application architecture, so if you don't know the following concepts, make sure you learn them:

Three-tier architecture,

MVC.

You may also be interested in using a framework (especially in PHP). Laravel looks promising and encourages you to use MVC.

I use require_once 'SELECT query file' to populate the select boxes

While including files with require_once is a viable approach, it may be difficult to maintain the list of files to include. What if you rename a file which is included in a few dozen of files? What if you forget to remove an include to a file you don't use any longer?

This is why often autoloading is used instead: with autoloading, you don't have to import anything manually, and it just works, magically. You may also be interested by PSR-4 (or PSR-0 if you don't use namespaces in your project).

Body:
Should I separate and create a PHP file for insert and a PHP file to get results from the database?

First, you may separate your data access from the business logic by moving data access code to a data access layer. For instance, if the select boxes are populated with the list of countries, then you'll have to call:

$this->db->listCountries();

from your business logic instead of doing directly the PDO stuff and the actual select ... from.

The next step is to consider what should be done with the business logic which is processing the submission of the form. You might decide that this is totally independent from the code which populates the form, in which case a separate file makes sense; however, in most cases, you'll consider that both actions are related, and keep them in the same file.

From your question, I'm not sure how advanced you are in application architecture, so if you don't know the following concepts, make sure you learn them:

Three-tier architecture,

MVC.

You may also be interested in using a framework (especially in PHP). Laravel looks promising and encourages you to use MVC.

I use require_once 'SELECT query file' to populate the select boxes

While including files with require_once is a viable approach, it may be difficult to maintain the list of files to include. What if you rename a file which is included in a few dozen of files? What if you forget to remove an include to a file you don't use any longer?

This is why often autoloading is used instead: with autoloading, you don't have to import anything manually, and it just works, magically. You may also be interested by PSR-4 (or PSR-0 if you don't use namespaces in your project).


问:
How does the team ensure a good DB design?
We want to ensure that our team delivers a good performing DB design. But we are not quite sure how to achieve this.

Couple of solutions have been suggested within the team:

Adding DB indexes to our definition of done. Maybe a rule like: no new/altered queries should use a table scan.

Maybe we should disable table-scan on our development environment. This way developers are forced to add indexes while developing.

Or maybe it would be sufficient to monitor for slow queries on a QA environment?

So what is the a good way of achieving a good DB design when you don't have a DBA?

答:
You fix "So what is the a good way of achieving a good DB design when you don't have a DBA?" by getting a DBA.

DB design is not about indexing, that's just part of the overall design.

What columns are in your tables, how to split repeated data into normalised tables and when not to split them for performance reasons; what kind of queries they'll required. All these are DB design topics, indexes, primary and foreign keys, good set of constraints, which ones may be nullable, what kind of datatypes, everything goes in a good DB design and there's no way to answer without a lot of experience.

So get a DBA or start training one of your staff to be a part-time DBA.


问:
comparison of computer processing language vs protocol
how can explain the diference between programming languge and protocol?,
can protocol have extension?

we know that machines communicate with protocol, but they can also do so with expressive language.

so, I think the difference between these two is unclear. also, the references for defining these two are not clear.
so maybe protocol is superset of language, eg:
protocol equ communication language?,
assembly equ machine language?,
css equ styling language?,

can any body do explain what is a protocol compared to language?

答:
Technically, a formal language (programming languages are a subset of those) is a set of strings that are valid in that language. For a language to be useful, it also has to have semantics, i.e. what does a string in the language mean.

For example, print('hello') is a valid string in the language Python and { "name": "zukerman" } is a valid string in the language JSON.

On the other hand, a protocol describes how machines communicate with each other using messages. A protocol can define what messages can be sent when, what are the roles of the machines (e.g. client and server), etc. A protocol also defines the format of messages, which is a language, though it's not commonly called that.

For example, you can't really say that GET /index.html HTTP/1.0 is a valid string in the protocol HTTP, even though it's a valid HTTP client request.

If you're asking specifically about programming languages, then those are languages whose semantics describes computations. Protocols in general don't do that, though some specific protocols do, e.g. RPC protocols.

OwnerDisplayName: zukerman yoav

OwnerDisplayName: svick


答:
The distinction is a matter of degree.

Consider the security procedures at a major bank. Every morning the first employe to appear moves a certain potted plant to a subtly different location to signal all other employees "It's okay, there is NOT a criminal gang lurking in the back office trying to kidnap the first two employees to show up and to get them to open the four-eyes safe" (or so I've read in thriller novels). When the second employee arrives and the plant has not been moved, they know to call the police immediately.

This is a protocol. It uses well-specified signals to express well-specified meanings, but rather few of them (only two different meanings).

Now compare this to the use of the English language between two employees to coordinate their work, or to chat about their personal lives. This also uses signals to express meanings, but the spectrum of what can be said and understood is infinitely richer and more complicated.

That, in a nutshell, is the difference between a protocal and a language. Restricted languages, such as the one used by international airline pilots when communication with air traffic control, are closer to mere protocols than normal language is. Very complicated protocols, such as big programming languages, are nearer to being languages than very simple ones. Where to draw the line between the two, as always, is ultimately a matter of opinion.

Title: comparison of computer processing language vs protocol

Body:
how can explain the diference between programming languge and protocol?,
can protocol have extension?

we know that machines communicate with protocol, but they can also do so with expressive language.

so, I think the difference between these two is unclear. also, the references for defining these two are not clear.
so maybe protocol is superset of language, eg:
protocol equ communication language?,
assembly equ machine language?,
css equ styling language?,

can any body do explain what is a protocol compared to language?


问:
Why am I getting field visibility warnings in Sonar?
Some static analysis tools flag non-private fields with

Variable '[nameHere]' must be private and have accessor methods.

Sonar consistently presents such warnings and wants to change all protected variables in my code to private, why is this? I'm yet to see a protected variable in my work that hasn't raised this warning.

答:
The purpose of private variables is to hide implementation details from the users of the class so that the implementation can be changed without breaking all the code that uses it.

Inheritance creates a second set of "users" of your class - its subclasses. Leaving instance variables protected is equivalent to exposing them as public to the subclasses.


问:
How do you debug a complex application?
I have an application that is returning the wrong output, when it is run with a particular input choice.  I haven't been able to get anywhere near a diagnosis of the fault, despite spending about a day and a half on it. If it is run with Input A then it gets the correct output, if it has Input B then the output should be the same but is incorrect.  Input B goes through some slightly different processes to Input A, in an attempt to optimise it, although most of the steps are in common.

I am trying to compare side-by-side an invocation of the program with the two inputs.  Its a difficult way to debug as you have two application windows, two visual studio windows, and its easy to get mixed up.

The software is about 1 million lines of code, and some of the code is fiendishly complicated.  It has many nested loops and loops that run for a lot of iterations, with very complex variables.  It caches a lot of data, so when you find that values in one mode are different from the other you have to work out if the differences are significant, and then its hard to trap where the programs diverge since the values have already been calculated and you have to keep restarting the programs and going back.

I understand there is no silver bullet here but I just wondered if anyone had any tips?

答:
I have not much experience with Visual Studio, but in many IDEs you can keep a Watcher on a variable, and step through the code while keeping an eye on its value.  Here is the MSDN documentation on a feature that seems to be equivalent to what I remember from other IDEs.

Input B goes through some slightly different processes to Input A, in an attempt to optimise it, although most of the steps are in common

It seems to me you should put a big, fat breakpoint at step 1 of the first 'slightly different' processes, and then step from that point on when debugging input B.  (Compare its value to the value of input A at the previous step, i.e. before those 'slightly different' processes started, so as to be sure that the processing up to that point was the same.)

Another, quite subjective advice: if stepping through so many lines of code is really time-consuming, you may use a 'binary-search' approach once you know which set of code lines are involved (probably from line 1 of the 'slightly different' processing to the last line).  Put a breakpoint in the middle of that interval; check if A and B are different; if they are, put a breakpoint in the middle of the interval before that line; if they are not, put a breakpoint in the middle of the interval after that line.  If you do not know which lines of code are involved, then stepping ahead from the first point where processing is different is your only option.

Title: How do you debug a complex application?