答:
After reviewing some of the information posted by @Amon, I think I've got something a little neater. It's more verbose, but it seems to be cleaner.

CommonApi

```<code>public abstract class CommonApi<T, TResponse>
    where TResponse : GroupResponseBase
{
    protected abstract TResponse GetInitialResponse();
    protected abstract List<T> ItemsFromResponse(TResponse response);
    protected abstract TResponse GetPageByUrl(string url);

    public ZendeskApi Api = new ZendeskApi(
        GlobalVariables.ZendeskUrl,
        GlobalVariables.ZendeskUser,
        GlobalVariables.ZendeskPass);

    public List<T> GetData()
    {
        var response = GetInitialResponse();
        var allItems = new List<T>(ItemsFromResponse(response));

        while (response.NextPage != null)
        {
            response = GetPageByUrl(response.NextPage);
            allItems.AddRange(ItemsFromResponse(response));
        }

        allItems = SortData(allItems);

        return allItems;
    }

    private List<T> SortData(List<T> list)
    {
        return list;
    }

    public List<User> SortData(List<User> list)
    {
        return list.OrderBy(n=>n.Name).ToList();
    }

    public List<Group> SortData(List<Group> list)
    {
        return list.OrderBy(n => n.Name).ToList();
    }

    public List<Organization> SortData(List<Organization> list)
    {
        return list.OrderBy(n => n.Name).ToList();
    }
}
</code>```

UserListApi

```<code>public class UserListApi : CommonApi<User, GroupUserResponse>
{
    protected override GroupUserResponse GetInitialResponse()
    {
        return Api.Users.GetAllUsers();
    }

    protected override List<User> ItemsFromResponse(GroupUserResponse response)
    {
        return response.Users.ToList();
    }

    protected override GroupUserResponse GetPageByUrl(string url)
    {
        return Api.Users.GetByPageUrl<GroupUserResponse>(url);
    }
}
</code>```

OrganizationListApi

```<code>public class OrganizationListApi : CommonApi<Organization, GroupOrganizationResponse>
{
    protected override GroupOrganizationResponse GetInitialResponse()
    {
        return Api.Organizations.GetOrganizations();
    }

    protected override List<Organization> ItemsFromResponse(GroupOrganizationResponse response)
    {
        return response.Organizations.ToList();
    }

    protected override GroupOrganizationResponse GetPageByUrl(string url)
    {
        return Api.Organizations.GetByPageUrl<GroupOrganizationResponse>(url);
    }
}
</code>```

GroupListApi

```<code>public class GroupListApi : CommonApi<Group, MultipleGroupResponse>
{
    protected override MultipleGroupResponse GetInitialResponse()
    {
        return Api.Groups.GetGroups();
    }

    protected override List<Group> ItemsFromResponse(MultipleGroupResponse response)
    {
        return response.Groups.ToList();
    }

    protected override MultipleGroupResponse GetPageByUrl(string url)
    {
        return Api.Groups.GetByPageUrl<MultipleGroupResponse>(url);
    }
}
</code>```

ZendeskCache

```<code>public class ZendeskCache
{
    public class Users : Cache<Users, List<User>>
    {
        protected override List<User> GetData()
        {
            var users = new UserListApi();

            return users.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Organizations : Cache<Organizations, List<Organization>>
    {
        protected override List<Organization> GetData()
        {
            var orgs = new OrganizationListApi();

            return orgs.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Groups : Cache<Groups, List<Group>>
    {
        protected override List<Group> GetData()
        {
            var groups = new GroupListApi();
            return groups.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromSeconds(1);
        }
    }
}
</code>```

I think it may be possible to reduce the ZendeskCache even a bit further, but I'll keep tinkering. I'm trying to figure out methods to make my future coding practices cleaner and more maintainable.

Body:
After reviewing some of the information posted by @Amon, I think I've got something a little neater. It's more verbose, but it seems to be cleaner.

CommonApi

public abstract class CommonApi<T, TResponse>
    where TResponse : GroupResponseBase
{
    protected abstract TResponse GetInitialResponse();
    protected abstract List<T> ItemsFromResponse(TResponse response);
    protected abstract TResponse GetPageByUrl(string url);

    public ZendeskApi Api = new ZendeskApi(
        GlobalVariables.ZendeskUrl,
        GlobalVariables.ZendeskUser,
        GlobalVariables.ZendeskPass);

    public List<T> GetData()
    {
        var response = GetInitialResponse();
        var allItems = new List<T>(ItemsFromResponse(response));

        while (response.NextPage != null)
        {
            response = GetPageByUrl(response.NextPage);
            allItems.AddRange(ItemsFromResponse(response));
        }

        allItems = SortData(allItems);

        return allItems;
    }

    private List<T> SortData(List<T> list)
    {
        return list;
    }

    public List<User> SortData(List<User> list)
    {
        return list.OrderBy(n=>n.Name).ToList();
    }

    public List<Group> SortData(List<Group> list)
    {
        return list.OrderBy(n => n.Name).ToList();
    }

    public List<Organization> SortData(List<Organization> list)
    {
        return list.OrderBy(n => n.Name).ToList();
    }
}

UserListApi

public class UserListApi : CommonApi<User, GroupUserResponse>
{
    protected override GroupUserResponse GetInitialResponse()
    {
        return Api.Users.GetAllUsers();
    }

    protected override List<User> ItemsFromResponse(GroupUserResponse response)
    {
        return response.Users.ToList();
    }

    protected override GroupUserResponse GetPageByUrl(string url)
    {
        return Api.Users.GetByPageUrl<GroupUserResponse>(url);
    }
}

OrganizationListApi

public class OrganizationListApi : CommonApi<Organization, GroupOrganizationResponse>
{
    protected override GroupOrganizationResponse GetInitialResponse()
    {
        return Api.Organizations.GetOrganizations();
    }

    protected override List<Organization> ItemsFromResponse(GroupOrganizationResponse response)
    {
        return response.Organizations.ToList();
    }

    protected override GroupOrganizationResponse GetPageByUrl(string url)
    {
        return Api.Organizations.GetByPageUrl<GroupOrganizationResponse>(url);
    }
}

GroupListApi

public class GroupListApi : CommonApi<Group, MultipleGroupResponse>
{
    protected override MultipleGroupResponse GetInitialResponse()
    {
        return Api.Groups.GetGroups();
    }

    protected override List<Group> ItemsFromResponse(MultipleGroupResponse response)
    {
        return response.Groups.ToList();
    }

    protected override MultipleGroupResponse GetPageByUrl(string url)
    {
        return Api.Groups.GetByPageUrl<MultipleGroupResponse>(url);
    }
}

ZendeskCache

public class ZendeskCache
{
    public class Users : Cache<Users, List<User>>
    {
        protected override List<User> GetData()
        {
            var users = new UserListApi();

            return users.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Organizations : Cache<Organizations, List<Organization>>
    {
        protected override List<Organization> GetData()
        {
            var orgs = new OrganizationListApi();

            return orgs.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Groups : Cache<Groups, List<Group>>
    {
        protected override List<Group> GetData()
        {
            var groups = new GroupListApi();
            return groups.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromSeconds(1);
        }
    }
}

I think it may be possible to reduce the ZendeskCache even a bit further, but I'll keep tinkering. I'm trying to figure out methods to make my future coding practices cleaner and more maintainable.


问:
Should defects be raised during sprints or just noted in the stories and assigned to developers?
I have heard that when testing stories developed in the current sprint, no issues are raised they are not completed (i.e. definition of done was not fulfilled) and that you should only raise issues when you find another, unrelated issue etc. While it does make sense not to raise issues on something that developers still can work on till the end of the sprint, I fail to find some "best practices". Is that a correct approach?</p>

答:
One of the key values of agile development is that you want to deliver working software, which means that it has been verified that the features you are delivering have been verified to be working correctly (according to your team's understanding of the feature).

If you find a problem while testing, then there are a few possibilities:

The problem is related to one of the features/stories you are currently developing and is severe enough that you would not be able to deliver the story according to your quality standards if the problem isn't fixed.

The problem is related to one of the features/stories you are currently developing and is not so severe that you are still able to deliver the story according to your quality standards if the problem isn't fixed.

The problem is unrelated to the stories you are currently developing and doesn't impact them.

In case of #1, you should, as a team, try to fix the problem before the end of the sprint. Otherwise, you won't be able to say that you have finished the work. Whether or not a ticket in the bug-tracking system is needed depends on your local conventions and requirements for traceability.

In case of #2 or #3, the problem should be reported to the Product Owner, so that it can be put on the product backlog and prioritized. Whether or not a ticket in the bug-tracking system is needed again depends on your local conventions and how your product backlog is being managed.

(Be prepared that especially items under #2 might get the priority "do when hell freezes over" aka never.)

ContentLicense: CC BY-SA 3.0


答:
It depends on your process. In my world, a defect is something that escapes your quality practices. But its up for you to define exactly what those are.

Some processes have a clear separation between the development team and the test / quality team. This is the world that I live in now. The development team is responsible for unit and integration tests and the quality team is responsible for deliverable-level (application and system level) regression and acceptance tests. In this environment, any issue that was not found by the development team in their testing would be recorded as a defect as it escaped the development team's quality activities - code reviews and tests.

The agile methods promote a highly integrated cross-functional team. In this environment, the quality activities also also integrated. Different people may be leading different activities, but everyone's involved every step of the way. Because of that, there's not always a clear hand-off from a development team to a quality team. As such, I would consider a defect to be something that makes it through to the end of the iteration and into the release.

However, something to consider is communication. In my first example, I may note an issue that I find in testing that is minor, but don't have the necessary path to fix in the development cycle. I may log a defect to communicate that I found an issue and allow it to be dispositioned. The project lead or quality team may say that it's actually a big deal (to the customer or from a product quality perspective) and demand it get fixed in the development cycle, or it may be planned for a later release.

In the end, you do need to do the right thing to enable you to understand your product quality and communicate the current state of the development effort to the appropriate stakeholders.

Title: Should defects be raised during sprints or just noted in the stories and assigned to developers?

Body: I have heard that when testing stories developed in the current sprint, no issues are raised they are not completed (i.e. definition of done was not fulfilled) and that you should only raise issues when you find another, unrelated issue etc. While it does make sense not to raise issues on something that developers still can work on till the end of the sprint, I fail to find some "best practices". Is that a correct approach?</p>


问:
What is this algorithm?
I would like to implement an algorithm but I guess it's a well-known problem and it has been implemented yet, but I am unable to verify that without its name.

Here is what I am willing to do :

I have a list of assertions that can be either true or false

I have an "oracle" that can tell me how many assertions are true among a specified list, but which is unable to tell explicitly which ones are valid or not

My goal is to know for each assertion if it is true or false

The "oracle" can only check lists with at least a huge number of assertions (it is not possible to test each assertion one by one)

My approach is to work on subsets (dichotomy seems to be the most efficient way) on my assertion list to divide it in two parts, and submit both parts to the "oracle".
After this, I would change the way my assertion list is split and make another test and so on ...

For those who know the game Mastermind this is somehow the idea.

Well, is there any "official" name for this problem and reputed way of solving it ?

答:
I would do it this way:

ask the oracle for the list of all assertions. Than you know how many are false

Than make a kind of binary search to find each of the failing assertions. You follow each partition in which is still at least one failed assertion until you narrowed down each failing assertion.

Example: 10 assertion

Oracle(0,1,2,3,4,5,6,7,8,9) = 3 failing assertions

Oracle(0,1,2,3,4) = 2  | Oracle(5,6,7,8,9) = 1

Oracle(0,1) = 0  | Oracle(2,3,4) = 2  | Oracle(5,6) = 1  | Oracle(7,8,9) = 0

Oracle(2) = 1  | Oracle(3,4) = 1  | Oracle(5) = 0  | Oracle(6) = 1

Oracle (3) = 0  | Oracle(4) = 1

So we know assertion 2,4,6 are the failing assertions

If is there is a minimum size for the list to request, you can request subsets by switching one element until the number changes. If it increases you added a failing assertion. But as a first step I would follow the approach above until you reached the minimal allowed request size.

Title: What is this algorithm?


答:
By answering, I'm assuming that when you say the "oracle" can't tell you if a single assertion is either true o false, it still does know its truth value (e.g. randomly generated truth values for generic assertions).

Let A be the set of your assertions. If A contains n items, its cardinality is: |A| = n. You first ask the oracle how many assertions in the starting set A are true:

true(A) = true(a1,a2,...,an) = c.

Now you calculate every subset of cardinality n - 1, thus those subsets containing only n - 1 items; every subset can be defined as follow:

Ak = {a1,a2,...,ak-1,ak+1,...,an-1,an}.

The number of subsets you get is n because you remove one item out of n from time to time.

Again, you ask the oracle how may true assertions are in every subset:

true(A1) = c1;

true(A2) = c2;

...

true(An) = cn.

And finally, the last operation is... Subtraction. You compute the difference between c and every ck you have, and figure out which assertions are true and which false.

Example: Let's say the set A has 10 items, and true(A) = 5. Half the assertions are true, the other half false. Now we pop out the first assertion a1 from A obtaining the subset A1, and then ask the oracle the value of true(A1).

If true(A1) = 5, it means no true assertion was removed from starting set A: a1 is false;

If true(A1) = 4, there's a missing true assertion than before: a1 is true.

Going on with A2, A3, ..., An and subtracting c to every ck will tell you what assertions are true and what false.

Notes: I'm assuming the function true() is linear, because it depends only on the size of input: if the argument size is 50 values, there will be only 50 reading operations. You can implement the function so that its argument is a data structure instead of writing every single variable - that's good for scalability of the input.

The math I used is very simple, and the data structure you need can be whatever you consider appropriate.

Also, you were constrained to ask the oracle for a great number of assertions per time: the smallest sets I dealt with contains n - 1 items, which is very close to the total number of assertions whose value you want to figure out.

Title: What is this algorithm?

Body:
I would like to implement an algorithm but I guess it's a well-known problem and it has been implemented yet, but I am unable to verify that without its name.

Here is what I am willing to do :

I have a list of assertions that can be either true or false

I have an "oracle" that can tell me how many assertions are true among a specified list, but which is unable to tell explicitly which ones are valid or not

My goal is to know for each assertion if it is true or false

The "oracle" can only check lists with at least a huge number of assertions (it is not possible to test each assertion one by one)

My approach is to work on subsets (dichotomy seems to be the most efficient way) on my assertion list to divide it in two parts, and submit both parts to the "oracle".
After this, I would change the way my assertion list is split and make another test and so on ...

For those who know the game Mastermind this is somehow the idea.

Well, is there any "official" name for this problem and reputed way of solving it ?


问:
Abstract Syntax Tree with parent or not?
My question is as simple as the title says -- should I implement AST with parent or not?

Currently I implemented it with parent -- the benefit of that approach is, that whatever I use, I can go up or down without any problem, all I need is some node. And modifications to the tree are also easy, because they are local to given branch.

However... when I look at the profiles, I see, that over 40% of the time is spent on cloning nodes. Clone is necessary, because with parent I cannot attach given node to multiple parents.

The opposite -- no parent -- would eliminate the need for cloning (at least such heavy usage), the tree would be more compact (actually it would be no tree no more, because of shared nodes), but would force me to use some kind navigator class to keep track of nodes when traversing them, and will add a little burden to modifying branches (first I would have to make a local clone :-) and then modify it).

It is hard for me to estimate which approach is better. Oh well, maybe there is some third way? Thank you in advance for help.

答: Your immediate problem can be solved by not storing types of expressions as AST nodes. Create a separate type for types. This can be immutable and without parent references so you never have to clone it. There should be no reason to want to navigate from a type to its parent type. It also avoids having your expression types carry around information like token position which makes sense for AST nodes, but not for the type of an expression.</p>


问:
complexity of an algorithm, sorting 5% out
I have been asked the following question..

An algorithm considers n elements, sorts 5% of n out, considers the remain elements(95%), sorts 5% of the remain elements, and so on until finally one last element is left. Which complexity does the algorithm have and why?

答:
Big O time complexity of divide and conquer algorithms is not affected by what fraction you divide things into.  This is because logs of different bases differ by only a constant factor.  So the Big O time complexity in your case is the same as if you separate 50% out.

So you should get the usual nLogn sort.


问:
Write C line by line
Is there any conceptual limitation that would make impossible to create a C program line by line as in 'Mathematica notebooks'[1]?

[1] One key aspect of Mathematica is that you can create your code line by line in a format called 'notebook'. This makes it much easier to debug the code during the development phase. After most of the code has been developed and debugged, is just a matter of copy and paste your code from the notebook format to a batch format (currently it's not possible to compile Mathematica codes).

答:
There is an open source project called Jupyter that is basically a notebook-like format like mathematica with many pluggable kernels that support various languages on the back end.  C++ is listed as one of the kernels, using the Cling REPL.  So, yes.  It's not only possible, it's been done.

Granted, C++ is not precisely C, but it's close enough to prove the concept.  Also, I wouldn't really call it writing a program.  It's more suited for the kinds of things you do with mathematica:  presenting code snippets together with formatted text and graphics.

I haven't personally used the C++ backend, but together with the RISE extension, jupyter made for a very effective presentation tool for a programming tech talk I taught in Scala.  When people have questions about the code, you can make changes and show its effect on the fly, without leaving your presentation.

I wouldn't use it for day-to-day development work, though.  I think most C programmers who like the rapid feedback of a REPL have adopted processes like test driven development, which actually avoids your copy and paste step.

Title: Write C line by line


问:
Using websockets for server “broadcasting”?
I want to make it possible to edit shared todo lists in real time.

There's already a REST interface, and it's possible to send updates to the server - add items, mark items as done, etc.

For the client to get these updates immediately, I did some research, and it seems that the best approach would be websockets, as they are quick and reliable. Push notifications on the other side can take "a few seconds" and are not reliable. I think I also saw something about "HTTP broadcasting" which did look more suitable for videos and things like that. Can't find it again.

So I was wondering, first, if websockets are really the best fit for this, second, if it's a good practice to use this in combination with REST - that is, I do the "push" from client A to server using a REST call, and then do the "push" from the server to client B using a websocket. Of course client B can also send updates to the server which have to be pushed to A (and other possible participants). So maybe it would be simpler to open websocket connections for both and throw out my REST code. On the other side a list can also have only 1 participant (the current user), in which case a websocket is not necessary, so maybe I could let these users use REST and switch to websockets only when there are more than 1 participants?

Does a mix of REST/websockets make sense for this application? Or should I stick to one or the other?

答:
You could use all 3.  Use the REST API for posting information to the server, websockets for immediate updates, and fall back to push notifications to the end user if the app isn't running (and the user wasn't notified over the websocket connection).

Of course, the REST API isn't strictly needed since you can perform the same server-side actions using websockets that you could with the REST API.  But whether that makes sense or not really depends on your server piece.  Since you already have the REST API, there's no major urgency for you to rewrite it for websockets.  But you can certainly start migrating the functionality to use websockets with the goal of eventually removing the use of the REST API.


问:
Ruby: if variable vs if variable.nil?
I'm new to Ruby and I was surprised when I found out that all objects are true apart from nil and false. Even 0 is true.

A nice thing about that property of the language is that you can write:

```<code>if !variable
  # do stuff when variable is nil
end
</code>```

My colleagues, who are more seasoned Ruby developers, insist I should choose that instead of using .nil? like so:

```<code>if variable.nil?
  # do stuff when variable is nil
end
</code>```

However I believe that the latter is a better option for two reasons:
1. I think it's more object oriented, especially in a language like Ruby where everything is an object and message exchange.
2. It is more readable, in my subject opinion, even if it is less compact.

Am I making a "newbie" mistake here?

答:
Consider the following:

response = responses.to_a.first

This will return the first element of responses, or nil. Then because conditional statements treat nil as false we can write:

```<code>response = responses.to_a.first
if response
  # do something ('happy path')
else
  # do something else
end
</code>```

Which is more readable than:

```<code>if response.nil?
  # do something else
else
  # do something ('happy path')
end
</code>```

The if (object) pattern is very common in Ruby code. It also leads nicely to refactoring, e.g.:

```<code>if response = responses.to_a.first
  do_something_with(response)
else
  # response is equal to nil
end
</code>```

Remember also that a Ruby method returns nil by default. So:

```<code>def initial_response
  if @condition
    @responses.to_a.first
  else
    nil
  end
end
</code>```

can be simplified to:

```<code>def initial_response
  if @condition
    @responses.to_a.first
  end
end
</code>```

So we can further refactor:

```<code>if response = initial_response
  do_something_with(response)
else
  # response is equal to nil
end
</code>```

Now you can argue that returning nil is not always the best idea, since it means checking for nil everywhere. But that is another kettle of fish. Given that testing for object "presence or absence" is such a frequent requirement, the truthiness of objects is a useful aspect of Ruby, albeit surprising for newcomers to the language.

Title: Ruby: if variable vs if variable.nil?

Body:
Consider the following:

response = responses.to_a.first

This will return the first element of responses, or nil. Then because conditional statements treat nil as false we can write:

response = responses.to_a.first
if response
  # do something ('happy path')
else
  # do something else
end

Which is more readable than:

if response.nil?
  # do something else
else
  # do something ('happy path')
end

The if (object) pattern is very common in Ruby code. It also leads nicely to refactoring, e.g.:

if response = responses.to_a.first
  do_something_with(response)
else
  # response is equal to nil
end

Remember also that a Ruby method returns nil by default. So:

def initial_response
  if @condition
    @responses.to_a.first
  else
    nil
  end
end

can be simplified to:

def initial_response
  if @condition
    @responses.to_a.first
  end
end

So we can further refactor:

if response = initial_response
  do_something_with(response)
else
  # response is equal to nil
end

Now you can argue that returning nil is not always the best idea, since it means checking for nil everywhere. But that is another kettle of fish. Given that testing for object "presence or absence" is such a frequent requirement, the truthiness of objects is a useful aspect of Ruby, albeit surprising for newcomers to the language.


问:
Object Oriented Design Question
I have long experience in procedural world and been programming/maintaining OO code in various languages too. Now getting into OO design and feeling the pains of identifying objects from scratch. Been reading several books, articles, etc. on OO. Often times they stop with Person, Employee examples. Identifying and doing it the right way in a real world projects raises several questions.

This is sort of a follow up question from my earlier design review question. Say, I have an object like below:

```<code>public class AddressRecord {
  protected long RecordID;
  protected String AddressLine1;
  protected String AddressLine2;
  protected String City;
  protected String State;
  protected String PostalCode;
  protected String Country;
  protected String FirstName;
  protected String LastName;
  protected String FullName;
  protected String PhoneNumber;
  protected String EmailAddress;
  protected String CompanyName;
  ..
  /* related to my question below */
  public String extractXml() {}
  public HashMap extractHash() {}
  public String extractJson() {}
  ...
}
</code>```

Now, I want to extract the field/values into a hashtable or a XML (proprietary format) or JSON structure without resorting to any libraries like JAXB. I will write some methods (for e.g., extractXml, extrachHash, extractJson) to extract specific fields into the target format.

My question is where should such extraction/conversion methods be? Based on some exposure to OO design books and advice, I was assuming I could have these methods right inside this class.

@Vladislav mentioned that they should actually be outside, like in the controller. I kind of get it, but I am curious to know why? Also, if I want to isolate this extraction logic from the controller code, can I create a class doing just that? Like,

```<code>public class AddressRecordXml {

   public static String extractXml(AddressRecord rec)
   {

   }

   ...
}
</code>```

and then use it in the controller as,

```<code>...
AddressRecord rec = new AddressRecord();
String xmlStr = AddressRecordXml(rec);
...
String resp = transport.process(xmlStr);
...
</code>```

Note: I know there are libraries like JAXB etc to help serialize objects to XML etc. I cannot use those, yet. I am working with Java 1.4 inside an old Sybase EAServer (main programming language being PowerBuilder) and it puts a lots of restrictions. Same reason for HashMap, no Generics etc.

答:
It depends on the complexity, but I would usually create one or more input/output classes.

I would typically create an AddressRecordInput interface that provides a read() method that returns an AddressRecord and an AddressRecordOutput interface that provides a write(AddressRecord) method. I would then provide implementations of these interfaces, such as AddressRecordXMLInput, AddressRecordXMLOutput, AddressRecordJSONInput, and AddressRecordJSONOutput, each with an appropriate constructor. For the constructor, I would consider some kind of existing reader, writer, or IO stream.

I would repeat this for every of your data models classes. These IO classes can leverage third-party libraries, such as JAXB (for XML) or Apache POI (for IO to and from Microsoft Office formats).

The downside is that for large data models, there are a lot of classes. However, they tend to be easy to understand and test.

Title: Object Oriented Design Question


答:
The OO examples tend to stop with Person, Employee because their goal is to demonstrate the principle of modeling real-world entities.  Of course, these entities are fairly pointless on their own: in order to do anything useful with them you will need to use them within some greater system, and designing such a system in an OO way is not easy to describe in terms of simple, easy to swallow examples.

There is no clear cut answer to the question of where these methods should go. A purist might say that the xml extraction method should go into some kind of manager which deals specifically with xml, and which is only included in a system which deals with xml. So, a different system, which would not be dealing with xml, would not include any xml generation code. Also, yet a different system, which would require a different xml representation, would only include code dealing with that representation, instead of being complicated with one default and unused xml extraction routine in the data object and a different xml extraction routine elsewhere.

But of course that's highly academic. Putting the xml extraction routine in the data object is a fine pragmatic compromise, which keeps things simple right from the beginning, and if you ever encounter the need for a different system configuration, you can easily refactor it out of the data object and into some manager.

Note 1: The current trend is to avoid calling things "managers".  So they call them "controllers" instead. That's actually laughable.

Note 2: I really hope you have significant monetary compensation for the unhealthy occupational conditions of having to work with java 1.4; if not, please do consider leaving that job. Personally, I would not even consider any version of java prior to 1.8.

Title: Object Oriented Design Question

Body:
I have long experience in procedural world and been programming/maintaining OO code in various languages too. Now getting into OO design and feeling the pains of identifying objects from scratch. Been reading several books, articles, etc. on OO. Often times they stop with Person, Employee examples. Identifying and doing it the right way in a real world projects raises several questions.

This is sort of a follow up question from my earlier design review question. Say, I have an object like below:

```<code>public class AddressRecord {
  protected long RecordID;
  protected String AddressLine1;
  protected String AddressLine2;
  protected String City;
  protected String State;
  protected String PostalCode;
  protected String Country;
  protected String FirstName;
  protected String LastName;
  protected String FullName;
  protected String PhoneNumber;
  protected String EmailAddress;
  protected String CompanyName;
  ..
  /* related to my question below */
  public String extractXml() {}
  public HashMap extractHash() {}
  public String extractJson() {}
  ...
}
</code>```

Now, I want to extract the field/values into a hashtable or a XML (proprietary format) or JSON structure without resorting to any libraries like JAXB. I will write some methods (for e.g., extractXml, extrachHash, extractJson) to extract specific fields into the target format.

My question is where should such extraction/conversion methods be? Based on some exposure to OO design books and advice, I was assuming I could have these methods right inside this class.

@Vladislav mentioned that they should actually be outside, like in the controller. I kind of get it, but I am curious to know why? Also, if I want to isolate this extraction logic from the controller code, can I create a class doing just that? Like,

```<code>public class AddressRecordXml {

   public static String extractXml(AddressRecord rec)
   {

   }

   ...
}
</code>```

and then use it in the controller as,

```<code>...
AddressRecord rec = new AddressRecord();
String xmlStr = AddressRecordXml(rec);
...
String resp = transport.process(xmlStr);
...
</code>```

Note: I know there are libraries like JAXB etc to help serialize objects to XML etc. I cannot use those, yet. I am working with Java 1.4 inside an old Sybase EAServer (main programming language being PowerBuilder) and it puts a lots of restrictions. Same reason for HashMap, no Generics etc.


答:
I was assuming I could have these methods right inside this class, but ...  mentioned that they should actually be outside, like in the controller.

Both designs are possible, and which one is better suited to your case, depends. For smaller programs, with only a handful of data objects, where you only need one conversion function like extractXml and none of the others, you may decide to put this function directly into the class. When your program becomes bigger, and your class AddressRecord might have several other functions, putting functions like extractXml or extractJson into a separate class like AddressRecordXml will help you to give your program more structure, and to keep your AddressRecord more universal.

However, when you have a lot of such data classes, your design will really improve if you can implement a generic version of extractXml(object), not specificially a method of AdressRecordXml, but of a universal class like XmlExtractor. Even in Java 1.4, there is reflection available, which will allow you to implement such a class in a generic way.

To your comment: when you start with a small program, you might place extractXml into AddressRecord directly. When your program grows over time, you need to refactor any parts of the code into separate classes which become otherwise "too complex". The trick is not to miss the point when to refactor, and to start with that as soon as your code starts to violate the SOLID principles. That is IMHO the only way to deal with "the future" correctly - creating a design for "the future" without knowing the future always leads to wrong design decisions.

Title: Object Oriented Design Question


问:
Java Object Oriented Question - 2
This is yet another follow up question about Object oriented design in general. I am trying to break them down to separate questions per advice I got from @Jay earlier.

I get a new question, almost every step of the OO design process. I tried to get the ideas from books, articles and the web. It just gets more muddied up. I would like to get some advice from the experts here, so I can get my concepts right.

Say I have the below Objects:

```<code>public class AddressRecord {
  protected String addressLine1;
  protected String addressLine2;
  protected String city;
  protected String state;
  protected String postalCode;
  protected String country;
  ....
}

public class AddressValidationRequest {
  private AddressRecord addresses[];
  protected ArrayList      actions;
  protected ArrayList      columns;
  protected Properties     options;
  ...
}
</code>```

Should I keep AddressRecord completely hidden inside Request (is it Aggregation?) or expose and access the AddressRecord from outside (Composition)?

(To me, even inheritance seemed like an option to extend AddressRecord to a Request, though I feel they are distinct entities in real world, so I dropped that idea).

What I mean is, should I have AddressRecord as a private object inside Request and add getters/setters in the Request itself for each field in AddressRecord?

Or just add getter/setter to get/set AddressRecord[] from the Request and then set it up outside, say in a controller code?

(This later idea I got when I tried to extract the AddressRecord class from Request in Eclipse like below:

```<code>public class AddressSearchRequest {

    AddressRecord address;

    public AddressSearchRequest(String format, String customerId, String addressLine1, String suite,
      String city, String state, String postalCode) {
        this.format = format;
        this.customerId = customerId;
        this.address.setAddressLine1(addressLine1);
        this.address.setAddressLine2(Suite);
        this.address.setCity(city);
        this.address.setState(state);
        this.address.setPostalCode(postalcode);
    }

    public void setAddressLine1(String addressLine1) {
        this.address.setAddressLine1(addressLine1);
    }
    public String getSuite() {
        return address.getAddressLine2();
    }
    public void setSuite(String suite) {
        this.address.setAddressLine2(suite);
    }
    public String getCity() {
        return address.getCity();
    }
    public void setCity(String city) {
        this.address.setCity(city);
    }
    public String getState() {
        return address.getState();
    }
    public void setState(String state) {
        this.address.setState(state);
    }
    public String getPostalCode() {
        return address.getPostalCode();
    }
    public void setPostalCode(String postalCode) {
        this.address.setPostalCode(postalCode);
    }
}
</code>```

UPDATE:

There are actually 2 different types of Requests I am dealing with - a Search Request - takes only one address and may return multiple matches.

A Validation Request may take one or more addresses.

I had them both as Request causing some confusion. corrected it.

Note: I am using AddressRecord also in other types of Request(s) and Response classes.

答:
The difference between aggregation and composition is ownership. Composition is stronger. If Request is composed of AddressRecords, then AddressRecord cannot exist outside of a Request. If Request aggregates AddressRecords, then you can create AddressRecord without the existence of a Request.

I don't have a full understanding of your system, but it seems like an AddressRecord can exist outside of your Request. This would mean that the approach where you provide an accessor and mutator for your collection of AddressRecords. This could take many forms: you can provide a get/set by index, a get/set for the entire collection (in this case, the array), add/remove methods, and so on. Either way, I would recommend that you create AddressRecords outside of Request and use them (along with other data) to populate the Request.

Title: Java Object Oriented Question - 2


答:
There are two different cases: either your Request contains one AddressRecord, or it contains multiple ones.  (The question is a bit confusing in this regard.)

If your Request is to contain multiple AddressRecords, then the answer is clearly that it has to expose methods to obtain AddressRecords by index or by some other key, so that the caller obtains an AddressRecord and works with it.  The Request might then also offer methods to add or delete AddressRecords, and specifically the add() method might either accept an existing AddressRecord to add to the Request, in which case the Request does not own the AddressRecords that it contains, so you have aggregation, or it might create an AddressRecord internally, in which case it owns its contents.  The choice is yours.

If your Request is to contain a single AddressRecord, the same principles apply, you can think of it as being a collection of one item, so there is no need to add or delete items, and the accessor does not need an index or a key. But if I were in your shoes I would definitely use an accessor, so the caller would have to invoke the accessor to obtain a reference to the one and only AddressRecord object contained within Rquest, and then the caller would have to invoke the AddressRecord object directly.

Adding mutator methods to Request which delegate to a contained AddressRecord is a lot of unnecessary work, it makes your classes hard to maintain, and it gives the false appearance that Request is derived from AddressRecord, since it exposes a superset of its methods, but without actually having inheritance, since you cannot pass a Request there where an AddressRecord is expected.

Note: another strategy commonly followed in more modern versions of java and in languages with more complete and more flexible collection models (like C#) would have Request expose an actual List<AddressRecord> getAddressRecords(), but with java 1.4 I would not try such a thing, due to the lack of type safety.

Title: Java Object Oriented Question - 2

Body:
This is yet another follow up question about Object oriented design in general. I am trying to break them down to separate questions per advice I got from @Jay earlier.

I get a new question, almost every step of the OO design process. I tried to get the ideas from books, articles and the web. It just gets more muddied up. I would like to get some advice from the experts here, so I can get my concepts right.

Say I have the below Objects:

```<code>public class AddressRecord {
  protected String addressLine1;
  protected String addressLine2;
  protected String city;
  protected String state;
  protected String postalCode;
  protected String country;
  ....
}

public class AddressValidationRequest {
  private AddressRecord addresses[];
  protected ArrayList      actions;
  protected ArrayList      columns;
  protected Properties     options;
  ...
}
</code>```

Should I keep AddressRecord completely hidden inside Request (is it Aggregation?) or expose and access the AddressRecord from outside (Composition)?

(To me, even inheritance seemed like an option to extend AddressRecord to a Request, though I feel they are distinct entities in real world, so I dropped that idea).

What I mean is, should I have AddressRecord as a private object inside Request and add getters/setters in the Request itself for each field in AddressRecord?

Or just add getter/setter to get/set AddressRecord[] from the Request and then set it up outside, say in a controller code?

(This later idea I got when I tried to extract the AddressRecord class from Request in Eclipse like below:

```<code>public class AddressSearchRequest {

    AddressRecord address;

    public AddressSearchRequest(String format, String customerId, String addressLine1, String suite,
      String city, String state, String postalCode) {
        this.format = format;
        this.customerId = customerId;
        this.address.setAddressLine1(addressLine1);
        this.address.setAddressLine2(Suite);
        this.address.setCity(city);
        this.address.setState(state);
        this.address.setPostalCode(postalcode);
    }

    public void setAddressLine1(String addressLine1) {
        this.address.setAddressLine1(addressLine1);
    }
    public String getSuite() {
        return address.getAddressLine2();
    }
    public void setSuite(String suite) {
        this.address.setAddressLine2(suite);
    }
    public String getCity() {
        return address.getCity();
    }
    public void setCity(String city) {
        this.address.setCity(city);
    }
    public String getState() {
        return address.getState();
    }
    public void setState(String state) {
        this.address.setState(state);
    }
    public String getPostalCode() {
        return address.getPostalCode();
    }
    public void setPostalCode(String postalCode) {
        this.address.setPostalCode(postalCode);
    }
}
</code>```

UPDATE:

There are actually 2 different types of Requests I am dealing with - a Search Request - takes only one address and may return multiple matches.

A Validation Request may take one or more addresses.

I had them both as Request causing some confusion. corrected it.

Note: I am using AddressRecord also in other types of Request(s) and Response classes.


答:
As the OP has correctly surmised, sometimes OO is just OO for OO's sake.  You see this "antipattern" every time you see a "util" package.  aaaaannnd....they're in EVERY project.  Sometimes it just makes sense to extract common mundane static-ish functions into collections of utils, that bear a striking resemblance to functional programming.  If it's not labeled "util" it is probably labeled "helper."

Also, I cringe a bit when people eschew using library code for this stuff...what part of "this code has undergone 500,000 hours of unit testing in the user community" is not appealing to you?

Title: Object Oriented Design Question


问:
How can I go about testing this javascript?
I'm working on a project that has me responsible for testing out some software that scrapes a web-page representing an input form, and generates a mobile friendly version of that page. This is particularly useful for form data, since not all websites have mobile-enabled browsers, and the aim of this project is to ultimately take these mobile-unfriendly pages, do some parsing on them, and then create a mobile-friendly version of said web-pages.

The code responsible for generating these mobile-friendly documents is more or less in javascript, which is the most untested portion of our code base. I want to find a way to test this code, and an idea came up amongst the team to see if there is some way to "record" a user's interaction with a web-site to disk such that locally, on the file system, there will be a series of N web-pages, each linking to one another on the file system. This way, we can generate test data rather easily for our project. There are several types of forms that we have to handle, such as forms that span across different web-pages, forms that have some javascript to hide aways certain fields, etc...

I'm not at all a web-developer; I'm more of a backend engineer. I think the greater goal we have is to find a way to test javascript that depends on the existence of specific types of forms; this latest requirement I have sort of grew out of that. Getting to the point, I have a couple of questions:

1) Is the creation and maintenance of this tool even a good idea? It would help create test data trivially assuming this was a browser plugin, but something about it seems kinda off to me.

2) What is the best way to do what I need to do, which is to find a way to test out some parser-javascript?

答:
Answers

1. is this a good idea?

I didn't know all details of your project, but sometimes there is no other way to provide testing, excepting writing user behavior scripts. It is hard enough to maintain such tests (because they depends on the UI, on names of css-classes, on ids of elements..), but on other hand they could give you confidence, that UI works as expected.

So, probably, yes — it is not a bad idea.

2. Best way to do ...

There are several tools, that could help you with this task

A) Selenium

You could try to use Selenium tests, they allow to automate user actions in the browser. So you could record simple scenario of user's actions, and later run it as a test so many times as you need.

Selenium is a Firefox extension, check it out: http://www.seleniumhq.org/

B) Headless browsers

There are a lot of headless browsers — almost the same browser as you use daily, but without UI. They could load webpage and interact  with it through scripting interface (depends on implementation)

Take a look at CasperJS — it is a scripting wrapper around famous PhantomJS (and SlimmerJS)


问:
Which data store is best for my scenario?
I'm working on an application that involves very high execution of update / select queries in the database.

I have a base table (A) which will have about 500 records for an entity for a day. And for every user in the system, a variation of this entity is created based on some of the preferences of the user and they are stored in another table (B). This is done by a cron job that runs at midnight everyday.

So if there are 10,000 users and 500 records in table A, there will be 5M records in table B for that day. I always keep data for one day in these tables and at midnight I archive historical data to HBase. This setup is working fine and I'm having no performance issues so far.

There has been some change in the business requirements lately and now some attributes in base table A ( for 15 - 20 records) will change every 20 seconds and based on that I have to recalculate some values for all of those variation records in table B for all users. Even though only 20 master records change, I need to do recalculation and update 200,000 user records which takes more than 20 seconds and by then the next update occurs eventually resulting in all Select queries getting queued up. I'm getting about 3 get request / 5 seconds from online users which results in 6-9 Select queries. To respond to an api request, I always use the fields in table B.

I can buy more processing power and solve this situation but I'm interested in having a properly scaled system which can handle even a million users.

Can anybody here suggest a better alternative? Does nosql + relational database help me here? Are there any platforms / datastores which will let me update data frequently without locking and at the same time give me the flexibility of running select queries on various fields in an entity?

答:
Looks like the table B is some kind of cache. But that kind of cache which lowers productivity..

Even if you have 25 queries per second you could refuse the usage of the table B, and calculate answer for each request.

Anyway, if you have 30 sec delay on updating 20 records - it is a fail in a software architecture (I am wrong, if your DB calculates first 10^100 signs of PI for every record).

As I know, relational DB without ugly SQL-queries, with indexes, and with less than 1 000 000 records will work perfectly for almost all queries.

Try to refuse of usage of table B and add appropriate indexes to your table A (most modern databases have a helper tool). Next: try to optimize the structure of data (table A) and a query (using query analyzer, or with SQL-experts) to speed up the calculation. If you will update just 20 records - the existence of indexes will not harm productivity of a update process, but significantly improves select speed.


问:
Internal API to public API - versioning
We have an internal API that is specifically for our website and internal applications, and we are planning to release a public api exposing some of the endpoints in our internal API.

We are using semantic versioning and our internal API is at version 6, would it make sense to just create a new project and start at version 1?

答:
Since you said "some" of the endpoints, that means the internal API and the public API are already meaningfully different interfaces, in addition to having completely different user bases. Therefore, it's entirely possible that one may need to change in ways that should not have any effect on the other. So yes, it makes perfect sense to use separate version numbers for each API.

Just make sure that the way you expose these endpoints is sufficiently flexible that you will be able to make changes to the public API or the internal API without affecting the other, if you so choose. And you should have two completely distinct "public API declarations" (whether that means header files or API documentation or something else for your project).

Title: Internal API to public API - versioning


问:
Comparing two large strings to see how much they match
Is there an easy way of comparing any two different size of string text to see how much percentage they're alike?

I'm trying this but I'm running into to this issue below.  The left text area is the text to copy.  The right is the user trying to copy the text ( in this example the user didn't get everything typed correctly, there's misspelled words and some words that the user forgot to type in).

After a countdown expires I try to calculate the percentage of how much the user correctly copied the given text in the left. And below on the left I have the text of the upper left text box put into an array using the split(" ") command on the text field.  And the bottom right I do the same for the user entered text.

Before calculating how much percentage the user typed correctly I try to have a summation of how much words the user typed correctly as my code below shows:

```<code>for(var counter = 0; counter < userArr.length; counter++)
{
    if(userArr[counter] === textArr[counter])
    {
        correct++;
    }
}
</code>```

At index 3 in the array the user mistyped something which is ok.  But at index 6 the user completely missed typing a word.  So that throws the rest of the indexes off by at least one to get the amount of words typed correctly.  Without that I can't calculate the percentage typed correctly.

To me it seems I'd have to create a bunch of conditional checks within the for loop to account for that.  But seems to be a bit messy.

So back to my original question, is there an easy way to so this calculations without creating a big mess of if statements? i.e. Is there an open source method, or built in javascript method to handle this?

答:
If you're not using an existing library function (like the Linux command-line utility diff, the T-SQL word NEAR, or even the PHP function array_intersect()), you can develop your own algorithm for this...and there are many variations possible...although some can be complex.  Here's a rough draft of one solution I came up with.  It has a time complexity of O(log(n)) (which means a decreasing amount of looping within a loop, which isn't particularly fast).

Break the words in the strings into array elements based on whitespace and other punctuation, as the author above did.

Begin iterating the 1st array.

Compare its 1st element to the 1st element of the 2nd array.

If the elements match, bump up your pointers (2nd to 2nd, etc.) and continue to do this as long as you find consecutive matches.

When you reach a mismatch, store the starting and ending points of the series of consecutive matches (which we'll call a "common section") in a separate array.  For example, array elements 4 through 12 in the 1st array might match elements 7 through 15 in the 2nd array.

At that first instance of a mismatch, reset your pointers and go back to iterating the arrays at points that haven't yet been included in a "common section"...and skip over ones that are already marked as "covered" (either flagged in a sub-element or covered by a range of one of the existing "common sections").

Once you're done iterating the arrays, "untangle" any out-of-order "common sections" by favoring the longest ones and/or ones that result in the greatest coverage area.

Count up your elements matched versus unmatched by your final set of "common sections" and calculate a percentage covered.


答:
The other answers go into some good details about different approaches to relating the classes to one another, which is central to what the question asked.  But I would just reinforce the notion that the ultimate best choice of design approaches can and will naturally flow from an understanding of what the application does and what data is in it.

For example, are the Request records simply "log entries" whenever a request is made?  Or are they API "messages" that need to be tracked and resolved?  And what about the Validation Requests?  And so on.

The most important advantage of object-oriented design isn't any programming power or functionality it might provide to reuse code.  OOP's great advantage is that it helps conceptually clarify the code (with fewer comments) for developers who read it.  If an OO design devolves into a muddle of obtuse relationships (which it quickly can)...then it has defeated its main purpose.

Title: Java Object Oriented Question - 2


答:
In general, trees should not know about their parents.

As you traverse the tree, you can see all children (and their children, and so on) to know if you need to do some work. Deciding once you get to the children that you need to go back is sloppy, and makes many algorithms more difficult/complex. And by keeping the knowledge in one direction, you reduce coupling, with all of the benefits that entails.

Title: Abstract Syntax Tree with parent or not?

Body:
My question is as simple as the title says -- should I implement AST with parent or not?

Currently I implemented it with parent -- the benefit of that approach is, that whatever I use, I can go up or down without any problem, all I need is some node. And modifications to the tree are also easy, because they are local to given branch.

However... when I look at the profiles, I see, that over 40% of the time is spent on cloning nodes. Clone is necessary, because with parent I cannot attach given node to multiple parents.

The opposite -- no parent -- would eliminate the need for cloning (at least such heavy usage), the tree would be more compact (actually it would be no tree no more, because of shared nodes), but would force me to use some kind navigator class to keep track of nodes when traversing them, and will add a little burden to modifying branches (first I would have to make a local clone :-) and then modify it).

It is hard for me to estimate which approach is better. Oh well, maybe there is some third way? Thank you in advance for help.


问:
Turning an HTML template into a Django template
When you purchase an HTML template, usually everything is mixed in together... html, css, images and js.

An example template may look like this:

account.html
category.html
contact.html
/fonts
/img
item-detail.html
media.html
register.html
style.css
author.html
category-tile.html
/css
/images
index.html
/js
new.html
shortcodes.html
submit.php

Django has static files and templates in separate folders in most cases. Is there a proper way of going about this?

答:
I would start by moving all the /fonts, /css, and other static files to my static dir.

Then I'd look at the various html files, try to figure out what common elements are shared, and extract those common elements to a base template that can be imported by the various children (this page gives a nice starting point for approaching template style & inheritance). Hopefully by starting with the base template, I could change the paths to static assets in that file alone, and avoid having to change them in each individual child template, but there's always sed, vim macros, or similar tools.

Then I'd go through all the html files and convert each of them to child templates extending the base template. Presumably this would involve some looping between "edit the base" and "edit the children," possibly with some intermediate or unrelated "base" templates if the theme is complicated enough.


答: I believe you are looking for Edit Distance it provides a numerical way to analyze the closeness of two words, which of course can be extrapolated onto full sentences. </p>

Title: Comparing two large strings to see how much they match

Body:
Is there an easy way of comparing any two different size of string text to see how much percentage they're alike?

I'm trying this but I'm running into to this issue below.  The left text area is the text to copy.  The right is the user trying to copy the text ( in this example the user didn't get everything typed correctly, there's misspelled words and some words that the user forgot to type in).

After a countdown expires I try to calculate the percentage of how much the user correctly copied the given text in the left. And below on the left I have the text of the upper left text box put into an array using the split(" ") command on the text field.  And the bottom right I do the same for the user entered text.

Before calculating how much percentage the user typed correctly I try to have a summation of how much words the user typed correctly as my code below shows:

```<code>for(var counter = 0; counter < userArr.length; counter++)
{
    if(userArr[counter] === textArr[counter])
    {
        correct++;
    }
}
</code>```

At index 3 in the array the user mistyped something which is ok.  But at index 6 the user completely missed typing a word.  So that throws the rest of the indexes off by at least one to get the amount of words typed correctly.  Without that I can't calculate the percentage typed correctly.

To me it seems I'd have to create a bunch of conditional checks within the for loop to account for that.  But seems to be a bit messy.

So back to my original question, is there an easy way to so this calculations without creating a big mess of if statements? i.e. Is there an open source method, or built in javascript method to handle this?


问:
Best Multiple tables product with categories
I was looking to create an EAV structure for an inventory management system. But I read this answer and decided against it. I am looking to create multiple tables for all my products. But the trouble now have is that all the products will have categories and sub categories( only two tiers ). How can I create tables to reflect the categories for the products. Do I create tables for each category and sub categories. The categories and sub categories need to be searchable.

For example
I will have a product table

```<code>Product:
str:name
str:description
</code>```

a batter table to contain the information of the battery

```<code>Battery:
str:volt
str:size
fr:product_id

Doll:
str:material
str:stuffing
fr:product_id
</code>```

But how do I handle the case when doll and the battery have categories and sub categories of their own? The sub categories and sub categories also needs to be relatable to the particular product while adding a product.

Do I create doll_categories, doll_sub_categories, battery_categories, battery_categories? I feel like as products are added. Every product should have 3 tables and it may grow to a lot of tables.

What is the best way to handle this situation?

答:
First things first, I'm not sure I agree with your choice of one table per product type. I'm not saying it's wrong, but... It could cause you a lot of grief down the road. It's a fragile schema. You know best. Just get some rest and think on it a bit more.

Regarding category -> sub category, the most straightforward plan of attack is probably two tables with a relationship table that links a product. Using your convention:

```<code>Category:
int: id
str: name

SubCategory:
int: id
str: name
fk: Category_id

ProductSubCategory:
fk: product_id
fk: SubCategory_id
</code>```

So, a category might be computers. Sub-categories are ultrabooks, workstations, and tablets. A product might be a Samsung tablet. Assign said product to the "tablets" sub-category via the relationship table. From that, you can determine it's also a "computer".

If you're lazy and you're 100% sure your schema won't change, you can just drop the SubCategory_id directly on a product. No relationship table required. That means you can only ever have one sub-category, though. Not sure if that's what you want.

In another universe, consider a self-referencing category table. That allows any number of sub-category levels:

```<code>Category:
int: id
str: name
fk: Category_id (null if top level)
</code>```

The data:

```<code>id: 1, name: "Computers", Category_id: null
id: 2, name: "Laptops", Category_id: 1
id: 3, name: "Tablets", Category_id: 1
id: 4, name: "Ultrabooks", Category_id: 2
id: 5, name: "Chromebooks", Category_id: 2
</code>```

If products can be in multiple bottom-level sub-categories, use a relationship table. Otherwise, just drop the id on the product table. Easy squeezy.

Body:
First things first, I'm not sure I agree with your choice of one table per product type. I'm not saying it's wrong, but... It could cause you a lot of grief down the road. It's a fragile schema. You know best. Just get some rest and think on it a bit more.

Regarding category -> sub category, the most straightforward plan of attack is probably two tables with a relationship table that links a product. Using your convention:

Category:
int: id
str: name

SubCategory:
int: id
str: name
fk: Category_id

ProductSubCategory:
fk: product_id
fk: SubCategory_id

So, a category might be computers. Sub-categories are ultrabooks, workstations, and tablets. A product might be a Samsung tablet. Assign said product to the "tablets" sub-category via the relationship table. From that, you can determine it's also a "computer".

If you're lazy and you're 100% sure your schema won't change, you can just drop the SubCategory_id directly on a product. No relationship table required. That means you can only ever have one sub-category, though. Not sure if that's what you want.

In another universe, consider a self-referencing category table. That allows any number of sub-category levels:

Category:
int: id
str: name
fk: Category_id (null if top level)

The data:

id: 1, name: "Computers", Category_id: null
id: 2, name: "Laptops", Category_id: 1
id: 3, name: "Tablets", Category_id: 1
id: 4, name: "Ultrabooks", Category_id: 2
id: 5, name: "Chromebooks", Category_id: 2

If products can be in multiple bottom-level sub-categories, use a relationship table. Otherwise, just drop the id on the product table. Easy squeezy.


问:
Why do you need "self." in Python to refer to instance variables?
I have been programming into a number of languages like Java, Ruby, Haskell and Python. I have to switch between many languages per day due to different projects I work on. Now, the issue is I often forget to write self as the first parameter in the function definitions in Python same is with calling methods on the same object.

That said, I am quite amazed by this approach of Python. Basically we have to type more to get the things done, in the languages like Java and Ruby things are made simple by automatically referencing the variables in the current object.

My question is why is this self necessary? Is it purely a style choice, or is there a reason why Python can't let you omit self the way Java and C++ let you omit this?

答:
Here are my conclusions based on above answers and reading the Guido's own rambling on this topic:

The big idea

Functions are the important building blocks in Python (or we should say the only one), in fact we are kind of emulating OOP by using functions.

Given that a class is nothing but a dictionary of functions hence, we can attach any function to any class at run time. Basically it is because of this need to toss the functions around at run time we can do stuffs like Monkey Patching. Here the self parameter supporting the parametric Polymorphism.


问:
Why Garbage Collection if smart pointers are there
These days, so many languages are garbage collected. It is even available for C++ by third parties. But C++ has RAII and smart pointers. So what's the point of using garbage collection? Is it doing something extra?

And in other languages like C#, if all the references are treated as smart pointers(keeping RAII aside), by specification and by implementation, will there still be any need of garbage collectors? If no, then why is this not so?

答:
So, what's the point of using garbage collection?

I'm assuming you mean reference counted smart pointers and I'll note that they are a (rudimentary) form of garbage collection so I'll answer the question "what are the advantages of other forms of garbage collection over reference counted smart pointers" instead.

Accuracy. Reference counting alone leaks cycles so reference counted smart pointers will leak memory in general unless other techniques are added to catch cycles. Once those techniques are added, reference counting's benefit of simplicity has vanished. Also, note that scope-based reference counting and tracing GCs collect values at different times, sometimes reference counting collects earlier and sometimes tracing GCs collect earlier.

Throughput. Smart pointers are one of the least efficient forms of garbage collection, particularly in the context of multi-threaded applications when reference counts are bumped atomically. There are advanced reference counting techniques designed to alleviate this but tracing GCs are still the algorithm of choice in production environments.

Latency. Typical smart pointer implementations allow destructors to avalanche, resulting in unbounded pause times. Other forms of garbage collection are much more incremental and can even be real time, e.g. Baker's treadmill.

ContentLicense: CC BY-SA 2.5


问:
Super classes that represent a wordly hierarchy: naming conventions
I'm unsure whether this post is allowed, considering it may be subjective. However, I have seen many posts concerning naming conventions (on programmers, as well as on StackOverflow - where I'm a more active member) so I think it should be valid. (Though it seems that sometimes topic with naming conventions are quickly closed and sometimes they aren't, so we'll see.)

I'm currently working on a JAVA project, though the problem would arise in basically any functional language. In my programme, I create a fictional world. This means that I'd like to create characters, objects, entities, and what not, with many classes extending the other. For example: entity would be a super class which only knows whether an element is moveable or not, and where it's currently located (i.e. its coordinates). In another class, this could be refined to characters that also contain a name and a gender. Another class would then distinguish as objects, in that they could hold a "type" (e.g. tree, car and so on). For this latter type, it seems overhead to create Class for each type, considering there are many possible types in the world, with which I mean "typical objects in the world, not further defined by any hierarchy".

Starting from Entity as a class, I'd go down to Character and Object classes. However, I've been told a couple of times that I definitely should not use Character and Object as name classes, because they are inherent to Java's collections. The question I ask then is:

Shouldn't we do so, because it's confusing for us as a programmer, or does it have programmatical consequences?

Is this discouraged in all programming languages? Or are there any languages in which this isn't such a big deal?

My IDE (Eclipse) doesn't throw any errors, not even a warning - so is it really that big of a deal?

Are there any conventions to represent persons, or objects (the referents in the real world) with a class name? For the life of me, I can't figure out a good synonym for "Object". Character can be replaced by Person I guess, but for Object it's much harder.

I wouldn't want this question to get labelled as "not a real question" or "subjective" because of that last question. My main questions are 1 & 2 & 3. An answer on 3 is optional, and could also be posted as a comment. It's the one I'm least interested in.

答:
It is not a problem in a language with different namespaces as java, it may be confusing thought.

Same as 1.

Same as 2.

A real problem would arise only in languages with a global namespace for some kind of objects, as function in C: in C functions are all in the same global namespace and are not overloadable, so you can not declare two functions with the same name or there would no way to distinguish between the two versions. It is for this problem that usually libraries use some prefix/suffix.
In Java there is no problem if they are in different namespaces: if there is a conflict in names you can always use the full name.


问:
Is there a point to unit tests that stub and mock everything public?
When doing unit tests the "proper" way, i.e. stubbing every public call and return preset values or mocks, I feel like I'm not actually testing anything. I'm literally looking at my code and creating examples based on the flow of logic through my public methods. And every time the implementation changes, I have to go and change those tests, again, not really feeling that I'm accomplishing anything useful (be it mid- or long-term). I also do integration tests (including non-happy-paths) and I don't really mind the increased testing times. With those, I feel like I'm actually testing for regressions, because they have caught multiple, while all that unit tests do is show me that the implementation of my public method changed, which I already know.

Unit testing is a vast topic, and I feel like I'm the one not understanding something here. What's the decisive advantage of unit testing vs integration testing (excluding the time overhead)?

答:
I was experiencing a similar question -  until I discovered the power of component tests. In short, they are the same as unit tests except that you don't mock by default but use real objects (ideally via dependency injection).

That way, you can quickly create robust tests with a good code coverage. No need for updating your mocks all the time. It might be a bit less precise than unit tests with 100% mocks, but the time and money you save compensate for that. The only thing you really need to use mocks or fixtures for are storage backends or external services.

Actually, excessive mocking is an anti-pattern: TDD Anti-Patterns and Mocks are evil.


问:
Should I strictly follow every single HTML and CSS Standard?
A few years ago I considered myself somewhat of a web developer, knowing the basic 3 languages (HTML, CSS, JS) and lots of PHP. Moving on from simple text to actual websites was a pain because of the so called "standards" out there, which at the time were ridiculously complicated for me. It pretty much boiled down to this (minus the IE related stuff):

Standards are there to replace old ways of doing things in a simpler way. However when trying to actually implement some of the stuff (Entirely CSS based layout for example), it took me 10x longer to actually do it then if I did the simpler and still working solution. If it rendered the same, then why should I use the more complicated example that takes 10x longer and breaks once you change browsers? This sparked many long religious debates in ##php, ##css, and ##js in Freenode IRC and actually got me banned from ##css because I messed with their little world over there.

My question: Should I follow every single standard and coding conventions even if they take me 10x longer but get me the same result as the simple one?

For the poll tag, those of you who have websites of any size (huge or small), do you follow all the standards?

答:
Your first consideration should be supporting the browsers that your customers use. Secondly you should adhere to standards when applicable.

For example, in a recent project the only browser we had to support was Firefox 3.5. This meant we could use the -moz css properties without worrying what the page would look like in another browser. Would it really have been worth doing rounded corners the long way, just so we were using standard css?

Having said that, when creating sites for multiple browsers, standards will usually help you, rather than hinder you. I would try to adhere to most standards, but not lose any sleep if I had to deviate for browser compatibility.

For the poll, the answer from me is No.


问:
Is there any reason to use "plain old data" classes?
In legacy code I occasionally see classes that are nothing but wrappers for data. something like:

```<code>class Bottle {
   int height;
   int diameter;
   Cap capType;

   getters/setters, maybe a constructor
}
</code>```

My understanding of OO is that classes are structures for data and the methods of operating on that data. This seems to preclude objects of this type. To me they are nothing more than structs and kind of defeat the purpose of OO. I don't think it's necessarily evil, though it may be a code smell.

Is there a case where such objects would be necessary? If this is used often, does it make the design suspect?

答:
Definitely not evil and not a code smell in my mind. Data containers are a valid OO citizen. Sometimes you want to encapsulate related information together. It's a lot better to have a method like

```<code>public void DoStuffWithBottle(Bottle b)
{
    // do something that doesn't modify Bottle, so the method doesn't belong
    // on that class
}
</code>```

than

```<code>public void DoStuffWithBottle(int bottleHeight, int bottleDiameter, Cap capType)
{
}
</code>```

Using a class also allows you to add an additional parameter to Bottle without modifying every caller of DoStuffWithBottle. And you can subclass Bottle and further increase the readability and organization of your code, if needed.

There are also plain data objects that can be returned as a result of a database query, for example. I believe the term for them in that case is "Data Transfer Object".

In some languages there are other considerations as well. For example, in C# classes and structs behave differently, since structs are a value type and classes are reference types.

Body:
Definitely not evil and not a code smell in my mind. Data containers are a valid OO citizen. Sometimes you want to encapsulate related information together. It's a lot better to have a method like

public void DoStuffWithBottle(Bottle b)
{
    // do something that doesn't modify Bottle, so the method doesn't belong
    // on that class
}

than

public void DoStuffWithBottle(int bottleHeight, int bottleDiameter, Cap capType)
{
}

Using a class also allows you to add an additional parameter to Bottle without modifying every caller of DoStuffWithBottle. And you can subclass Bottle and further increase the readability and organization of your code, if needed.

There are also plain data objects that can be returned as a result of a database query, for example. I believe the term for them in that case is "Data Transfer Object".

In some languages there are other considerations as well. For example, in C# classes and structs behave differently, since structs are a value type and classes are reference types.


问:
Keeping git repositories on different hosts in sync
I am thinking about starting a small project and I want to make its versioning with git.

Bitbucket seems a good option for me with their free plan. I want to use it as the main tool for working with git since they have nice tools  like a web-interface, Mac OS client, and so on. But, in order to have higher protection from any accidental damages that can be caused by using a third-party service, I want also to install git on my NAS as a second back-up copy of the repository.

Now my question is, whether it is possible to create a repository on two different hosts and then keep them in sync? For example, suppose once per week I update the repository on my NAS to match the one on Bitbucket.  Then, in case something happens with Bitbucket, I will still have the full repository with full history of development on my local NAS storage.

And is there a way to import an existing repository with full history to another git-service?

I think that mirroring is what I need.
This article seems to describe exactly what I need.
And this one as well.

I believe that it will make full copy with full history and even automatically commit new versions to the repositories on both hosts automatically.

Am I right?

答:
Here's a tested solution for the issue: Automatic Sync 2 Remote Git Repositories

A simple script for synching 2 remote Git repositories

I've searched the web for a simple script that will sync. 2 remote repositories but I couldn't find such script even that many seems to look for it! So I've created 2 simple test repositories and started testing and building such script.

What such script should do?

Well, in general, the steps for doing it are simple:

Clone the first repository

Add the second one as an additional remote repository

Fetch all there is in the second repository

Push the updated local repository onto the 2 remote repositories.

The remained issue is - what are the correct switches for all the above git commands?

So here it is...

2repos-sync.sh gisp script

```<code># Clear the folder first - please use this carefully
rm -rf $REPO_NAME
# clone the reposotory
git clone --bare $ORIGIN_URL

# add a remote repository
cd $REPO_NAME
git remote add --mirror=fetch repo1 $REPO1_URL

# update the local copy from the first repository
git fetch origin --tags

# update the local copy with the second repository
git fetch repo1 --tags

# sync back the 2 repositories
git push origin --all
git push origin --tags
git push repo1 --all
git push repo1 --tags
</code>```

NOTE - this script is not solving cases of conflicts between the repository content!

ContentLicense: CC BY-SA 4.0

Body:
Here's a tested solution for the issue: Automatic Sync 2 Remote Git Repositories

A simple script for synching 2 remote Git repositories

I've searched the web for a simple script that will sync. 2 remote repositories but I couldn't find such script even that many seems to look for it! So I've created 2 simple test repositories and started testing and building such script.

What such script should do?

Well, in general, the steps for doing it are simple:

Clone the first repository

Add the second one as an additional remote repository

Fetch all there is in the second repository

Push the updated local repository onto the 2 remote repositories.

The remained issue is - what are the correct switches for all the above git commands?

So here it is...

2repos-sync.sh gisp script

# Clear the folder first - please use this carefully
rm -rf $REPO_NAME
# clone the reposotory
git clone --bare $ORIGIN_URL

# add a remote repository
cd $REPO_NAME
git remote add --mirror=fetch repo1 $REPO1_URL

# update the local copy from the first repository
git fetch origin --tags

# update the local copy with the second repository
git fetch repo1 --tags

# sync back the 2 repositories
git push origin --all
git push origin --tags
git push repo1 --all
git push repo1 --tags

NOTE - this script is not solving cases of conflicts between the repository content!


问:
Adding a complex check constraint
I am working on a table that has a compound primary key that includes a date.

```<code>Faculty

PersonId    StartDate    EndDate    Title ....

-------------------------------------------------
</code>```

I will add a compound key consisting of the PersonID and StartDate. The business rule I am thinking about is allowing a person added as faculty, removed, and then added again later if needed. I am thinking a visiting professor. Or an adjunct who teaches an occasional course, but is not an active member of the faculty from one semester to the the next.

The end date will allow nulls, indicating a person is currently a faculty member.

I want to further constrain the data so a person can have only one row with an end date that is null.

Things I have considered:

UDF in a check constraint

Trigger (I hate triggers)

Application layer constraint (most likely what I will do at this point)

Note:

This is a hobby, work on this weekends kind of project

The intended data store is Azure SQL Database

答:
At least for SQL Server you can use a unique constraint

Just put a unique constraint on PersonID, EndDate

You can use null in a unique constraint and it enforces allow one null but not more

I tested this out and it does exactly what you are asking for

The only possible problem is this would not allow two identical non-null EndDate also - but I suspect that is what you want

Unique Constraints and Check Constraints

Unlike PRIMARY KEY constraints, UNIQUE constraints allow for the value
  NULL. However, as with any value participating in a UNIQUE constraint,
  only one null value is allowed per column. A UNIQUE constraint can be
  referenced by a FOREIGN KEY constraint.

Fiddle is down

```<code>CREATE TABLE [t1](
    [col1] [int] NOT NULL,
    [col2] [datetime] NOT NULL,
    [col3] [datetime] NULL,
 CONSTRAINT [PK_t1] PRIMARY KEY CLUSTERED
(
    [col1] ASC,
    [col2] ASC
)
CREATE UNIQUE NONCLUSTERED INDEX [IX_t1] ON [dbo].[t1]
(
    [col1] ASC,
    [col3] ASC
)
insert into t1 (1,1900-01-01,1900-01-01)
             , (1,1901-01-01,null)
             , (2,1900-01-01,1900-01-01)
             , (2,1902-01-01,1902-02-01)
</code>```

Title: Adding a complex check constraint

Body:
At least for SQL Server you can use a unique constraint

Just put a unique constraint on PersonID, EndDate

You can use null in a unique constraint and it enforces allow one null but not more

I tested this out and it does exactly what you are asking for

The only possible problem is this would not allow two identical non-null EndDate also - but I suspect that is what you want

Unique Constraints and Check Constraints

Unlike PRIMARY KEY constraints, UNIQUE constraints allow for the value
  NULL. However, as with any value participating in a UNIQUE constraint,
  only one null value is allowed per column. A UNIQUE constraint can be
  referenced by a FOREIGN KEY constraint.

Fiddle is down

CREATE TABLE [t1](
    [col1] [int] NOT NULL,
    [col2] [datetime] NOT NULL,
    [col3] [datetime] NULL,
 CONSTRAINT [PK_t1] PRIMARY KEY CLUSTERED
(
    [col1] ASC,
    [col2] ASC
)
CREATE UNIQUE NONCLUSTERED INDEX [IX_t1] ON [dbo].[t1]
(
    [col1] ASC,
    [col3] ASC
)
insert into t1 (1,1900-01-01,1900-01-01)
             , (1,1901-01-01,null)
             , (2,1900-01-01,1900-01-01)
             , (2,1902-01-01,1902-02-01)


答:
You are looking for one of the various forms of edit distance.  The formal definition of the edit distance is:

Given two strings a and b on an alphabet Σ (e.g. the set of ASCII characters, the set of bytes [0..255], C T A G, etc.), the edit distance d(a, b) is the minimum-weight series of edit operations that transforms a into b.

From this, you don't have 26 or 28 strings, you have one string. Its a big one - but you look at it in its entirety.

There are many types of edit distance that are focused on different transformations and alphabets.  For example, the Levenshtein distance works on the transformations of insert, delete, and substitute on an arbitrary string, where as the Hamming distance is the number of locations where two strings differ.  The Damerau–Levenshtein distance adds the transposition of two adjacent characters to the Levenshtein distance (so it that hte to the is a distance of 1, not 2) and is more useful for spell checking and DNA variation (though the Needleman–Wunsch algorithm may work better for strings of DNA).


问:
How to avoid violating the SRP in a class to manage caching?
Note: The code sample is written in c#, but that shouldn't matter. I've put c# as a tag because I can't find a more appropiate one. This is about the code structure.

I'm reading Clean Code and trying to become a better programmer.

I often find myself struggling to follow the Single Responsibility Principle (classes and functions should do only one thing), specially in functions. Maybe my problem is that "one thing" is not well-defined, but still...

An example: I have a list of Fluffies in a database. We don't care what a Fluffy is. I want a class to recover fluffies. However, fluffies can change according to some logic. Depending on some logic, this class will return the data from cache or get the latest from the database.
We could say that it manages fluffies, and that is one thing.
To make it simple, let's say loaded data is good for an hour, and then it must be reloaded.

```<code>class FluffiesManager
{
    private Fluffies m_Cache;
    private DateTime m_NextReload = DateTime.MinValue;
    // ...
    public Fluffies GetFluffies()
    {
        if (NeedsReload())
            LoadFluffies();

        return m_Cache;
    }

    private NeedsReload()
    {
        return (m_NextReload < DateTime.Now);
    }

    private void LoadFluffies()
    {
        GetFluffiesFromDb();
        UpdateNextLoad();
    }

    private void UpdateNextLoad()
    {
        m_NextReload = DatTime.Now + TimeSpan.FromHours(1);
    }
    // ...
}
</code>```

GetFluffies() seems ok to me. The user asks for some fluffies, we provide them. Going to recover them from the DB if needed, but that could be considered a part of getting the fluffies (of course, that's somewhat subjective).

NeedsReload() seems right, too. Checks if we need to reload the fluffies.
UpdateNextLoad is fine. Updates the time for the next reload. that's definitely one single thing.

However, I feel what LoadFluffies() do can't be described as one single thing. It's getting the data from the Database, and it's scheduling the next reload. It's hard to argue that calculating the time for the next reload is part of getting the data. However, I can't find a better way to do it (renaming the function to LoadFluffiesAndScheduleNextLoad may be better, but it just makes the problem more obvious).

Is there an elegant solution to really write this class according to the SRP?
Am I being too pedantic?

Or maybe my class isn't really doing just one thing?

答:
I believe your class is doing one thing; it's a data cache with a timeout. LoadFluffies seems like a useless abstraction unless you call it from multiple places. I think it would be better to take the two lines from LoadFluffies and put them in the NeedsReload conditional in GetFluffies. This would make the implementation of GetFluffies a lot more obvious and is still clean code, as you're composing single responsibility subroutines to accomplish a single goal, a cached retrieval of data from the db. Below is the updated get fluffies method.</p>

```<code>public Fluffies GetFluffies()
{
    if (NeedsReload()) {
        GetFluffiesFromDb();
        UpdateNextLoad();
    }

    return m_Cache;
}
</code>```

OwnerDisplayName: raven

Body:
I believe your class is doing one thing; it's a data cache with a timeout. LoadFluffies seems like a useless abstraction unless you call it from multiple places. I think it would be better to take the two lines from LoadFluffies and put them in the NeedsReload conditional in GetFluffies. This would make the implementation of GetFluffies a lot more obvious and is still clean code, as you're composing single responsibility subroutines to accomplish a single goal, a cached retrieval of data from the db. Below is the updated get fluffies method.

public Fluffies GetFluffies()
{
    if (NeedsReload()) {
        GetFluffiesFromDb();
        UpdateNextLoad();
    }

    return m_Cache;
}

OwnerDisplayName: Patrick Goley


答:
There are even much strange creatures exist in the OOP world. I've once created a class, which is abstract, and contains nothing, it just for to be a common parent of other two classes... it's the Port class:

```<code>SceneMember
Message extends SceneMember
Port extends SceneMember
InputPort extends Port
OutputPort extends Port
</code>```

So SceneMember is the base class, it does all the job, which required to appear on the scene: add, delete, get-set ID, etc. Message is the connection between ports, it has its own life. InputPort and OutputPort contain the i/o specific functions of their own.

Port is empty. It is just used to group InputPort and OutputPort together for, say, a portlist. It's empty because SceneMember contains all stuff which are for acting as a member, and InputPort and OutputPort contain the port-specified tasks. InputPort and OutputPort are such different, that they have no common (except SceneMember) functions. So, Port is empty. But it's legal.

Maybe it's an antipattern, but I like it.

(It's like the word "mate", which is used for both "wife" and "husband". You never use the "mate" word for a concrete person, because you know the sex of him/her, and it does not matter if he/she is married or not, so you use "someone" instead, but it still exists, and is used in rare, abstract situations, e.g. a law text.)

Title: Is there any reason to use "plain old data" classes?

Body:
In legacy code I occasionally see classes that are nothing but wrappers for data. something like:

```<code>class Bottle {
   int height;
   int diameter;
   Cap capType;

   getters/setters, maybe a constructor
}
</code>```

My understanding of OO is that classes are structures for data and the methods of operating on that data. This seems to preclude objects of this type. To me they are nothing more than structs and kind of defeat the purpose of OO. I don't think it's necessarily evil, though it may be a code smell.

Is there a case where such objects would be necessary? If this is used often, does it make the design suspect?

Body:
There are even much strange creatures exist in the OOP world. I've once created a class, which is abstract, and contains nothing, it just for to be a common parent of other two classes... it's the Port class:

SceneMember
Message extends SceneMember
Port extends SceneMember
InputPort extends Port
OutputPort extends Port

So SceneMember is the base class, it does all the job, which required to appear on the scene: add, delete, get-set ID, etc. Message is the connection between ports, it has its own life. InputPort and OutputPort contain the i/o specific functions of their own.

Port is empty. It is just used to group InputPort and OutputPort together for, say, a portlist. It's empty because SceneMember contains all stuff which are for acting as a member, and InputPort and OutputPort contain the port-specified tasks. InputPort and OutputPort are such different, that they have no common (except SceneMember) functions. So, Port is empty. But it's legal.

Maybe it's an antipattern, but I like it.

(It's like the word "mate", which is used for both "wife" and "husband". You never use the "mate" word for a concrete person, because you know the sex of him/her, and it does not matter if he/she is married or not, so you use "someone" instead, but it still exists, and is used in rare, abstract situations, e.g. a law text.)