问:
Is Ruby on Rails supposed to have a steep learning curve or is it just me?
I'm a self-taught programmer. I've been learning RoR since October with varying intensity (sometimes all day, sometimes nothing for several weeks). Before that I knew only Java, but knew it pretty well. I've heard so much hype about RoR and how it's supposed to make you happy, productive, etc. So far it's only made me frustrated.  I learned it out of the Agile book, and I suspect part of the difficulty might have to do with my not knowing JavaScript and CSS, and having only a shaky grasp of databases and HTML. But apparently it took me much longer to complete the project in the Agile book than other people, and I still don't remember much of it. There are some things about Rails that I just can't seem to get, e.g. when to use symbols and when NOT to, or how dynamic methods are called.

Recently I was given a small Rails assignment where I'm asked to make a small change to the interface. It's taken me around 25 hours and although I've made some progress in understanding the code, I still have no idea how to proceed. I can't even ask Stack Overflow because there is so much code I'll have to provide to give context.

So my question is in the title: is RoR supposed to take a long time to learn or am I just slow? Can it be that I've been learning from the wrong book? My learning style is such that I either understand nothing or understand everything, if that makes sense.

答: I also come from a Java background, and I had a pretty difficult time learning Rails. I had all the same issues you mentioned. I found that watching railscasts.com helped out in the beginning. Just seeing how someone else did things helped me catch on and I then started doing things on my own. I haven't touched Rails since Rails 3 came out though.</p>


问:
How meaningful is the Big-O time complexity of an algorithm?
Programmers often talk about the time complexity of an algorithm, e.g. O(log n) or O(n^2).

Time complexity classifications are made as the input size goes to infinity, but ironically infinite input size in computation is not used.

Put another way, the classification of an algorithm is based on a situation that algorithm will never be in: where n = infinity.

Also, consider that a polynomial time algorithm where the exponent is huge is just as useless as an exponential time algorithm with tiny base (e.g., 1.00000001^n) is useful.

Given this, how much can I rely on the Big-O time complexity to advise choice of an algorithm?

答:
Meaningful?  Yes.  But it doesn't tell the full story.

What the asymptotic complexity tells you is how well your program will scale with respect to the input size.  For example, let's say you have a program that runs within an acceptable time for the time being on small inputs.  Then the complexity will tell you a rough estimate of the time it takes to process something that's several factors larger.

What it doesn't tell you is how fast it will actually run, because you're still missing two critical bits of information:

The coefficient / constant factor: if your algorithm is O(1) but the coefficient is enormous, then it probably won't be of much benefit unless you work with equally enormous inputs.

The scaling for small inputs: asymptotic complexity describes the behavior as the input size approaches infinity.  The behavior of the algorithm at small input sizes can be drastically different, however.  Therefore, if your application involves primarily small inputs, then you should optimize for those instead of worrying about asymptotic complexity.

Asymptotic complexity is fine as a crude "zeroth-order estimate" for large inputs but what you really care is whether something performs acceptably on the inputs that matter to you.  That will involve a more complicated mathematical calculation and/or profiling.

ContentLicense: CC BY-SA 3.0


问:
Refactoring a Single Rails Model with large methods & long join queries trying to do everything
I have a working Ruby on Rails Model that I suspect is inefficient, hard to maintain, and full of unnecessary SQL join queries. I want to optimize and refactor this Model (Quiz.rb) to comply with Rails best practices, but I'm not sure how I should do it.

The Rails app is a game that has Missions with many Stages. Users complete Stages by answering Questions that have correct or incorrect Answers.  When a User tries to complete a stage by answering questions, the User gets a Quiz entry with many Attempts. Each Attempt records an Answer submitted  for that Question within the Stage. A user completes a stage or mission by getting every Attempt correct, and their progress is tracked by adding a new entry to the UserMission & UserStage join tables.

All of these features work, but unfortunately the Quiz.rb Model has been twisted to handle almost all of it exclusively.  The callbacks began at 'Quiz.rb', and because I wasn't sure how to leave the Quiz Model during a multi-model update, I resorted to using Rails Console to have the @quiz instance variable via self.some_method do all the heavy lifting to retrieve every data value for the game's business logic; resulting in large extended join queries that "dance" all around the Database schema.

The Quiz.rb Model that Smells:

```<code>class Quiz < ActiveRecord::Base
  belongs_to :user
  has_many :attempts, dependent: :destroy

  before_save :check_answer
  before_save :update_user_mission_and_stage

  accepts_nested_attributes_for :attempts, :reject_if => lambda { |a| a[:answer_id].blank? }, :allow_destroy => true

  #Checks every answer within each quiz, adding +1 for each correct answer
  #within a stage quiz, and -1 for each incorrect answer

  def check_answer
    stage_score = 0
    self.attempts.each do |attempt|
      if attempt.answer.correct? == true
        stage_score += 1
      elsif attempt.answer.correct == false
        stage_score - 1
      end
    end
    stage_score
  end

  def winner
   return true
  end

  def update_user_mission_and_stage
    #######
    #Step 1: Checks if UserMission exists, finds or creates one.
    #if no UserMission for the current mission exists, creates a new UserMission
      if self.user_has_mission? == false
        @user_mission = UserMission.new(user_id: self.user.id,
                          mission_id: self.current_stage.mission_id,
                          available: true)
        @user_mission.save
      else
        @user_mission = self.find_user_mission
      end

    #######
    #Step 2: Checks if current UserStage exists, stops if true to prevent duplicate entry
      if self.user_has_stage?
        @user_mission.save
        return true
      else

    #######
    ##Step 3: if step 2 returns false:
    ##Initiates UserStage creation instructions
      #checks for winner (winner actions need to be defined) if they complete last stage of last mission for a given orientation
        if self.passed? && self.is_last_stage? && self.is_last_mission?
          create_user_stage_and_update_user_mission
          self.winner

      #NOTE: The rest are the same, but specify conditions that are available to add badges or other actions upon those conditions occurring:
      ##if user completes first stage of a mission
        elsif self.passed? && self.is_first_stage? && self.is_first_mission?
          create_user_stage_and_update_user_mission

          #creates user badge for finishing first stage of first mission
          self.user.add_badge(5)
          self.user.activity_logs.create(description: "granted first-stage badge", type_event: "badge", value: "first-stage")

      #If user completes last stage of a given mission, creates a new UserMission
        elsif self.passed? && self.is_last_stage? && self.is_first_mission?
          create_user_stage_and_update_user_mission

          #creates user badge for finishing first mission
          self.user.add_badge(6)
          self.user.activity_logs.create(description: "granted first-mission badge", type_event: "badge", value: "first-mission")

        elsif self.passed?
          create_user_stage_and_update_user_mission

        else self.passed? == false
          return true
        end
      end
  end

  #Creates a new UserStage record in the database for a successful Quiz question passing
  def create_user_stage_and_update_user_mission
    @nu_stage = @user_mission.user_stages.new(user_id: self.user.id,
                                              stage_id: self.current_stage.id)
    @nu_stage.save
    @user_mission.save

    self.user.add_points(50)
  end

  #Boolean that defines passing a stage as answering every question in that stage correct
  def passed?
    self.check_answer >= self.number_of_questions
  end

  #Returns the number of questions asked for that stage's quiz
  def number_of_questions
    self.attempts.first.answer.question.stage.questions.count
  end

  #Returns the current_stage for the Quiz, routing through 1st attempt in that Quiz
  def current_stage
    self.attempts.first.answer.question.stage
  end

  #Gives back the position of the stage relative to its mission.
  def stage_position
    self.attempts.first.answer.question.stage.position
  end

  #will find the user_mission for the current user and stage if it exists
  def find_user_mission
    self.user.user_missions.find_by_mission_id(self.current_stage.mission_id)
  end

  #Returns true if quiz was for the last stage within that mission
  #helpful for triggering actions related to a user completing a mission
  def is_last_stage?
    self.stage_position == self.current_stage.mission.stages.last.position
  end

  #Returns true if quiz was for the first stage within that mission
  #helpful for triggering actions related to a user completing a mission
  def is_first_stage?
    self.stage_position == self.current_stage.mission.stages_ordered.first.position
  end

  #Returns true if current user has a UserMission for the current stage
  def user_has_mission?
    self.user.missions.ids.include?(self.current_stage.mission.id)
  end

  #Returns true if current user has a UserStage for the current stage
  def user_has_stage?
    self.user.stages.include?(self.current_stage)
  end

  #Returns true if current user is on the last mission based on position within a given orientation
  def is_first_mission?
     self.user.missions.first.orientation.missions.by_position.first.position == self.current_stage.mission.position
  end

  #Returns true if current user is on the first stage & mission of a given orientation
  def is_last_mission?
     self.user.missions.first.orientation.missions.by_position.last.position == self.current_stage.mission.position
  end

end
</code>```

My Question

Currently my Rails server takes roughly 500ms to 1 sec to process single @quiz.save action. I am confident that the slowness here is due to sloppy code, not bad Database ERD design.

What does a better solution look like?   And specifically:

Should I use join queries to retrieve values like I did here, or is it better to instantiate new objects within the model instead?  Or am I missing a better solution?

How should update_user_mission_and_stage be refactored to follow best practices?

Relevant Code for Reference:

quizzes_controller.rb w/ Controller Route Initiating Callback:

```<code>  class QuizzesController < ApplicationController
    before_action :find_stage_and_mission
    before_action :find_orientation
    before_action :find_question

  def show
  end

  def create
    @user = current_user
    @quiz = current_user.quizzes.new(quiz_params)
    if @quiz.save
      if @quiz.passed?
         if @mission.next_mission.nil? && @stage.next_stage.nil?
           redirect_to root_path, notice: "Congratulations, you have finished the last mission!"
         elsif @stage.next_stage.nil?
           redirect_to [@mission.next_mission, @mission.first_stage], notice: "Correct! Time for Mission #{@mission.next_mission.position}", info: "Starting next mission"
         else
           redirect_to [@mission, @stage.next_stage], notice: "Answer Correct! You passed the stage!"
         end
      else
       redirect_to [@mission, @stage], alert: "You didn't get every question right, please try again."
      end

    else
      redirect_to [@mission, @stage], alert: "Sorry.  We were unable to save your answer.  Please contact the admministrator."
    end
    @questions = @stage.questions.all

  end

  private

  def find_stage_and_mission
    @stage = Stage.find(params[:stage_id])
    @mission = @stage.mission
  end

  def find_question
    @question = @stage.questions.find_by_id params[:id]
  end

  def quiz_params
    params.require(:quiz).permit(:user_id, :attempt_id, {attempts_attributes: [:id, :quiz_id, :answer_id]})

  end

  def find_orientation
  @orientation = @mission.orientation
  @missions = @orientation.missions.by_position
  end

end
</code>```

Overview of Relevant ERD Database Relationships:

Mission -> Stage -> Question -> Answer -> Attempt <- Quiz <- User

Mission -> UserMission <- User

Stage -> UserStage <- User

Other Models:

Mission.rb

```<code>class Mission < ActiveRecord::Base
  belongs_to :orientation

  has_many :stages

  has_many :user_missions, dependent: :destroy
  has_many :users, through: :user_missions

  #SCOPES
  scope :by_position, -> {order(position: :asc)}

  def stages_ordered
    stages.order(:position)
  end

  def next_mission
    self.orientation.missions.find_by_position(self.position.next)
  end

  def first_stage
    next_mission.stages_ordered.first
  end

end
</code>```

Stage.rb:

```<code>class Stage < ActiveRecord::Base
  belongs_to :mission

  has_many :questions, dependent: :destroy

  has_many :user_stages, dependent: :destroy
  has_many :users, through: :user_stages

  accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true

  def next_stage
    self.mission.stages.find_by_position(self.position.next)
  end
end
</code>```

Question.rb

```<code>    class Question < ActiveRecord::Base
      belongs_to :stage
      has_many :answers, dependent: :destroy

      accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:body].blank? }, :allow_destroy => true
    end
</code>```

Answer.rb:

```<code>class Answer < ActiveRecord::Base
  belongs_to :question

  has_many :attempts, dependent: :destroy
end
</code>```

Attempt.rb:

```<code>class Attempt < ActiveRecord::Base
  belongs_to :answer
  belongs_to :quiz
end
</code>```

User.rb:

```<code>class User < ActiveRecord::Base

  belongs_to :school
  has_many :activity_logs

  has_many :user_missions, dependent: :destroy
  has_many :missions, through: :user_missions

  has_many :user_stages, dependent: :destroy
  has_many :stages, through: :user_stages

  has_many :orientations, through: :school

  has_many :quizzes, dependent: :destroy
  has_many :attempts, through: :quizzes

  def latest_stage_position
    self.user_missions.last.user_stages.last.stage.position
  end

end
</code>```

UserMission.rb

```<code>class UserMission < ActiveRecord::Base

  belongs_to :user
  belongs_to :mission

  has_many :user_stages, dependent: :destroy

end
</code>```

UserStage.rb

```<code>class UserStage < ActiveRecord::Base

  belongs_to :user
  belongs_to :stage
  belongs_to :user_mission
end
</code>```

答:
I would recommend looking at your SQL log to see what is getting executed.

Also try the free 'newrelic' http://newrelic.com/ruby to help out with a detailed breakdown of performance.

The problem will be that it's difficult to change when/how various queries are being executed when you call ActiveRecord associations so freely as you are now.

Also, you're not actually using joins, but simple "SELECT" loading based on the association.

Separate Data Retrieval and Logic
A good strategy to help with this is to try and fetch all the data you need first, then execute the logic on it with simple ruby (not active-record inheriting) classes.  This will require some thinking through of the pathways, and you will probably need to fetch data AGAIN throughout the flow, but at least each point is made explicit and can be optimized.

When the required data crosses over more than one ActiveRecord, or is sufficiently complicated, do the data fetch in a separate class - one per usecase.  I like to call these 'query' objects.

Data Structure

The code should not duplicate knowledge about data structure, but instead try to isolate each structure access into one place.

For example, you call "self.attempts.first.answer.question.stage" which means the code in quiz knows about attempts, that the first one is special (I think it's current, right?), that attempts have answers, that answers have questions, and the question has a stage.

Not only is it a lot to take in when reading it, it means that if anything around the structure changes you'll have lots of places to change.

It's also doing lots of SQL at each '.', and you can't optimize it without having to change each line. For example, we can probably optimize by using a number of joins via combining 'scopes'.

Other Points

In update_user_mission_and_stage

Try and reduce the branching if possible. Don't do if/else within if/else.

One way to fix this is with a 'state' machine.

Avoid callbacks like the plague -- it's so easy to lose track of them, and to not realise how much code is running unexpectedly. Limit them to maybe simple lookups for the core model in the controller.

You have 'check_answer' being called in 'before_save' of quiz, but it doesn't save anything, so appears to have no effect.

Extract out the entire method to a separate 'service' class.  That's just a plain ruby class to do the logic.

Read this for some more details/links/ideas:
http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/


问:
Algorithm to match items be value into sets base on total
Given n sets of items. Each item has a value. The items in a set have similar values but vary by a small amount. The goal is to create new sets containing three items selected from the original sets such that the total of the values is within a given range. Only one item a source set can be selected.

For example: If we have the following starting sets:

Set A -  { 4.0, 3.8, 4.2 }

Set B -  { 7.0, 6.8, 7.2 }

Set C -  { 1.0, 0.9, 1.1 }

Set D -  { 6.5, 6.4, 6.6 }

Set E -  { 2.5, 2.4, 2.6 }

Goal is to create sets containing three elements such that the total is between 11.9 and 12.1.

For example { 3.8, 7.2, 1.0 }

There can be unused elements.

Can someone suggest an algorithm for this problem?

答:
This looks like a knapsack-type problem. No shortcuts.

Form a permutation of each of the possible selectsions, enumerate them, and pick any that fall with the range.

The problem definition could be improved by specifying exactly how selections are made eg one of out each set?


答:
If you must use exactly 3 items, then it's at worst O(n^2 log n) problem.  Insert all elements into a sorted structure (O(n log n)).  Then iterate through all possible pair sums (O(n^2)).  For each pair sum search the tree to see if there is a suitable third element (O(log n)).

If you can use an arbitrary number of elements, but the values are positive and can be reduced to small integers (as above, just multiply all by 10), then you can use dynamic programming to get a solution in time O(n * s) where s is the desired sum.

See http://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming

Title: Algorithm to match items be value into sets base on total

Body:
Given n sets of items. Each item has a value. The items in a set have similar values but vary by a small amount. The goal is to create new sets containing three items selected from the original sets such that the total of the values is within a given range. Only one item a source set can be selected.

For example: If we have the following starting sets:

Set A -  { 4.0, 3.8, 4.2 }

Set B -  { 7.0, 6.8, 7.2 }

Set C -  { 1.0, 0.9, 1.1 }

Set D -  { 6.5, 6.4, 6.6 }

Set E -  { 2.5, 2.4, 2.6 }

Goal is to create sets containing three elements such that the total is between 11.9 and 12.1.

For example { 3.8, 7.2, 1.0 }

There can be unused elements.

Can someone suggest an algorithm for this problem?


问:
Is hashing of just "username + password" as safe as salted hashing
I want to hash "user + password".

[EDIT: prehashing "user" would be an improvement, so my question is also for hashing "hash(user) + password". If cross-site same user is a problem then the hashing changed to hashing "hash(serviceName + user) + password"]

From what I read about salted hash, using "user + password" as input to hash function will help us avoid problem with reverse hash table hacking. The same thing can be said about rainbow table.

Any reason why this is not as good as salted hashing?

答:
A salted hash has several advantages over the approach you mention.

Salt adds uniqueness. Since it is randomly generated each time a password is created or changed, it guarantees that two identical passwords have different hashes. Using the username would sort of achieve this goal, but the salt is more effective since it changes with the password while a username normally does not change. It is stronger over time.

Salt introduces more entropy. The number of bytes in a salt may be more or less than a username, but introduce more entropy. A salt is completely random in all eight bits per byte. A username is at best an email address with 52 letters (upper and lower case), 10 numbers, and a few punctuation. Let's say 64 characters, so 6 bits per byte (and typically less).

Assuming the username is known, the same password would hash to the same predictable value in multiple password records. Salt is random and not tied to the login, so the same username and password combination would still result in different hashed passwords when using random salt.

Salt can be arbitrary length and contain a lot of entropy, making the hashed password more secure.

For more information, I recommend you visit the information security stack exchange site.


问:
Designs for outputting to a spreadsheet
I'm working on a project where we are tasked to gather and output various data to a spreadsheet.

We are having tons of problems with the file that holds the code to write the spreadsheet. The cell that the data belongs to is hardcoded, so anytime you need to add anything to the middle of the spreadsheet, you have to increment the location for all the fields after that in the code. There are random blank rows, to add padding between sections, and subsections within the sections, so there's no real pattern that we can replicate. Essentially, anytime we have to add or change anything to the spreadsheet it requires a many long and tedious hours.

The code is all in this one large file, hacked together overtime in Perl. I've come up with a few OO solutions, but I'm not too familiar with OO programming in Perl and all my attempts at it haven't been great, so I've shied away from it so far. I've suggested we handle this section of the program with a more OO friendly language, but we can't apparently. I've also suggested that we scrap the entire spreadsheet idea, and just move to a webpage, but we can't do that either.

We've been working on this project for a few months, and every time we have to change that file, we all dread it. I'm thinking it's time to start some refactoring. However, I don't even know what could make this file easier to work with. The way the output is formatted makes it so that it has to be somewhat hardcoded.

I'm wondering if anyone has insight on any design patterns or techniques they have used to tackle a similar problem. I'm open to any ideas. Perl specific answers are welcome, but I am also interested in language-agnostic solutions.

答:
This problem is not so bad because the bad code only produces a single output.

The cell that the data belongs to is hardcoded, so anytime you need to add anything to the middle of the spreadsheet, you have to increment the location for all the fields after that in the code.

Ah.. the root of the problem.  This is a huge WTF.  The current code was written by a novice and is unmaintainable.  You have to eliminate the hard-coding and use some variables to keep track of where each datum goes.  If this were my problem, I would just rewrite the entire function from scratch using the existing code as a reference.  My first thought is to just fill the spreadsheet row by row keeping track of the current row.

Title: Designs for outputting to a spreadsheet


问:
How do you decide what kind of database to use?
I really dislike the name "NoSQL", because it isn't very descriptive.  It tells me what the databases aren't where I'm more interested in what the databases are.  I really think that this category really encompasses several categories of database.  I'm just trying to get a general idea of what job each particular database is the best tool for.

A few assumptions I'd like to make (and would ask you to make):

Assume that you have the capability to hire any number of brilliant engineers who are equally experienced with every database technology that has ever existed.

Assume you have the technical infrastructure to support any given database (including available servers and sysadmins who can support said database).

Assume that each database has the best support possible for free.

Assume you have 100% buy-in from management.

Assume you have an infinite amount of money to throw at the problem.

Now, I realize that the above assumptions eliminate a lot of valid considerations that are involved in choosing a database, but my focus is on figuring out what database is best for the job on a purely technical level.  So, given the above assumptions, the question is: what jobs are each database (including both SQL and NoSQL) the best tool for and why?

答:
SQL

Relational object. Stable servers with fine grain control over permissions.

NoSQL

Flexible storage. High scalability and sharding abilities.

ContentLicense: CC BY-SA 2.5


问:
When is type testing OK?
Assuming a language with some inherent type safety (e.g., not JavaScript):

Given a method that accepts a SuperType, we know that in most cases wherein we might be tempted to perform type testing to pick an action:

```<code>public void DoSomethingTo(SuperType o) {
  if (o isa SubTypeA) {
    o.doSomethingA()
  } else {
    o.doSomethingB();
  }
}
</code>```

We should usually, if not always, create a single, overridable method on the SuperType and do this:

```<code>public void DoSomethingTo(SuperType o) {
  o.doSomething();
}
</code>```

... wherein each subtype is given its own doSomething() implementation. The rest of our application can then be appropriately ignorant of whether any given SuperType is really a SubTypeA or a SubTypeB.

Wonderful.

But, we're still given is a-like operations in most, if not all, type-safe languages. And that suggests a potential need for explicit type testing.

So, in what situations, if any, should we or must we perform explicit type testing?

Forgive my absent mindedness or lack of creativity. I know I've done it before; but, it was honestly so long ago I can't remember if what I did was good! And in recent memory, I don't think I've encountered a need to test types outside my cowboy JavaScript.

答:
The only time I use is is in combination with reflection. But even then is dynamic checking mostly, not hard-coded to a specific class (or only hard-coded to special classes such as String or List).

By dynamic checking I mean:

```<code>boolean checkType(Type type, Object object) {
    if (object.isOfType(type)) {

    }
}
</code>```

and not hard-coded

```<code>boolean checkIsManaer(Object object) {
    if (object instanceof Manager) {

    }
}
</code>```

Title: When is type testing OK?

Body:
The only time I use is is in combination with reflection. But even then is dynamic checking mostly, not hard-coded to a specific class (or only hard-coded to special classes such as String or List).

By dynamic checking I mean:

boolean checkType(Type type, Object object) {
    if (object.isOfType(type)) {

    }
}

and not hard-coded

boolean checkIsManaer(Object object) {
    if (object instanceof Manager) {

    }
}


问:
When would you want two references to the same object?
In Java specifically, but likely in other languages as well: when would it be useful to have two references to the same object?

Example:

```<code>Dog a = new Dog();
Dob b = a;
</code>```

Is there a situation where this would be useful? Why would this be a preferred solution to using a whenever you want to interact with the object represented by a?

答: I used this when writing a Sudoku solver. When I know the number of a cell when processing rows, I want the containing column to know that cell's number too when processing columns. So both columns and rows are arrays of Cell objects that overlap. Exactly like the accepted answer showed.</p>


问:
How to change the state of a singleton in runtime
Consider I am going to write a simple file based logger AppLogger to be used in my apps, ideally it should be a singleton so I can call it via

```<code>public class AppLogger {
    public static String file = "..";

    public void logToFile() {
        // Write to file
    }

    public static log(String s) {
        AppLogger.getInstance().logToFile(s);
    }
}
</code>```

And to use it

```<code>AppLogger::log("This is a log statement");
</code>```

The problem is, what is the best time I should provide the value of file since it is a just a singleton?

Or how to refactor the above code (or skip using singleton) so I can customize the log file path? (Assume I don't need to write to multiple at the same time)

p.s. I know I can use library e.g. log4j, but consider it is just a design question, how to refactor the code above?

答:
I think you could just go ahead and provide a setter Method for the file path in the AppLogger. If you're using multiple threads in your application, make sure to keep the methods synchronized, as a Singleton is a shared object that can be accessed by all threads:

```<code>public static void synchronized setFile(String filePath) {...}

public static void synchronized log(String s) {...}
</code>```

Some other points:

AppLogger::log is not correct Java syntax

You have two methods for logging, and both are public. Make logToFile private and add a string argument

The actual singleton reference is missing in your class

The signature of log(String) is not correct. You have to add a return type (like I did)

Body:
I think you could just go ahead and provide a setter Method for the file path in the AppLogger. If you're using multiple threads in your application, make sure to keep the methods synchronized, as a Singleton is a shared object that can be accessed by all threads:

public static void synchronized setFile(String filePath) {...}

public static void synchronized log(String s) {...}

Some other points:

AppLogger::log is not correct Java syntax

You have two methods for logging, and both are public. Make logToFile private and add a string argument

The actual singleton reference is missing in your class

The signature of log(String) is not correct. You have to add a return type (like I did)


答:
If you got a large code base (over 100K lines of code) and are close to shipping or are working in a branch that will later have to be merge, and therefore there is a lot cost/risk to changing a lot of cope.

You then sometimes have the option of a large refractor of the system, or some simple localised “type testing”.   This creates a technical debt that should be paid back as soon as possible, but often is not.

(It is impossible to come up with an example, as any code that is small enough to be used as an example, is also small enough for the better design to be clearly visible.)

Or in other words, when the aim is to be paid your wage rather than to get “up votes” for the cleanness of your design.

The other common case is UI code, when for example you show a different UI for some types of employees, but clearly you don’t want the UI concepts to escape into all your “domain” classes.

You can you use “type testing” to decide what version of the UI to show, or have some fancy lookup table that converts from “domain classes” to “UI classes”.   The lookup table is just a way of hiding the “type testing” in one place.

(Database updating code can have the same issues as UI code, however you tend to only have one set of database updating code, but  you can have lots of different screens that must adapt to the type of object being shown.)

Title: When is type testing OK?

Body:
Assuming a language with some inherent type safety (e.g., not JavaScript):

Given a method that accepts a SuperType, we know that in most cases wherein we might be tempted to perform type testing to pick an action:

```<code>public void DoSomethingTo(SuperType o) {
  if (o isa SubTypeA) {
    o.doSomethingA()
  } else {
    o.doSomethingB();
  }
}
</code>```

We should usually, if not always, create a single, overridable method on the SuperType and do this:

```<code>public void DoSomethingTo(SuperType o) {
  o.doSomething();
}
</code>```

... wherein each subtype is given its own doSomething() implementation. The rest of our application can then be appropriately ignorant of whether any given SuperType is really a SubTypeA or a SubTypeB.

Wonderful.

But, we're still given is a-like operations in most, if not all, type-safe languages. And that suggests a potential need for explicit type testing.

So, in what situations, if any, should we or must we perform explicit type testing?

Forgive my absent mindedness or lack of creativity. I know I've done it before; but, it was honestly so long ago I can't remember if what I did was good! And in recent memory, I don't think I've encountered a need to test types outside my cowboy JavaScript.


问:
Generic Repositories with DI & Data Intensive Controllers
Usually, I consider a large number of parameters as an alarm bell that there may be a design problem somewhere. I am using a Generic Repository for an ASP.NET application and have a Controller with a growing number of parameters.

public class GenericRepository<T> : IRepository<T> where T : class
{
    protected DbContext Context { get; set; }
    protected DbSet<T> DbSet { get; set; }

    public GenericRepository(DbContext context)
    {
        Context = context;
        DbSet = context.Set<T>();
    }
    ...//methods excluded to keep the question readable

}
```

<p>I am using a DI container to pass in the DbContext to the generic repository. So far, this has met my needs and there are no other concrete implmentations of <code>IRepository<T></code>. However, I had to create a dashboard which uses data from many Entities. There was also a form containing a couple of dropdown lists. Now using the generic repository this makes the parameter requirments grow quickly.</p>

<p>The Controller will end up being something like</p>

<pre class="lang-cs prettyprint-override"><code>public HomeController(IRepository<EntityOne> entityOneRepository,
                      IRepository<EntityTwo> entityTwoRepository,
                      IRepository<EntityThree> entityThreeRepository,
                      IRepository<EntityFour> entityFourRepository,
                      ILogError logError,
                      ICurrentUser currentUser)
{
}
</code>```

It has about 6 IRepositories plus a few others to include the required data and the dropdown list options. In my mind this is too many parameters. From a performance point of view, there is only 1 DBContext per request and the DI container will serve the same DbContext to all of the Repositories. From a code standards/readability point of view it's ugly.

Is there a better way to handle this situation? Its a real world project with real world time constraints so I will not dwell on it too long, but from a learning perspective it would be good to see how such situations are handled by others.

答:
I've been playig around with using seperate query and command classes instead of using repositories with multiple methods.

Your UserRepository might a GetByEmail(string email) method. Instead of that, I have a GetUserByEmailQuery class and a GetUserByEmailQueryHandler class.

Your UserRepository might have a UpdatePassword(string newPassword) method. Instead of that, I have a UpdateUserPasswordCommand class and a UpdateUserPasswordCommandHandler class.

Everything comes together in my controllers through a QueryAndCommandDispatcher.

First some interfaces:

public interface IQueryHandler<in TQueryData, out TResult> where TQueryData : class
{
    TResult Execute(TQueryData query);
}

public interface ICommandHandler<in T> where T : class
{
    void Handle(T command);
}

public interface IQueryAndCommandDispatcher
{
    void ExecuteCommand<T>(T command) where T : class;
    TResult ExecuteQuery<TQueryData, TResult>(TQueryData query) where TQueryData : class;
}
```

<p>As you can see, a query is supposed to return something while a command isn't. A command should change data, a query shouldn't.</p>

<p>Here's how that query to get a user by his or her email would look like (<code>IDataContext</code> is an interface describing my custom <code>DbContext</code>):</p>

<pre class="lang-csharp prettyprint-override"><code>public class GetUserByEmailQuery
{
    public string Email { get; private set; }

    public GetUserByEmailQuery(string email)
    {
        Email = email;
    }
}

public class GetUserByEmailQueryHandler : IQueryHandler<GetUserByEmailQuery, User>
{
    private readonly IDataContext dataContext;

    public GetUserByEmailQueryHandler(IDataContext dataContext)
    {
        this.dataContext = dataContext;
    }

    public User Execute(GetUserByEmailQuery query)
    {
        return dataContext.Users.First(u => u.Email == query.Email);
    }
}
</code>```

Here's how that command to update a user's password would look like:

public class UpdateUserPasswordCommand
{
    public int UserId { get; private set; }
    public string Password { get; private set; }

    public UpdateUserPasswordCommand(int userId, string password)
    {
        UserId = userId;
        Password = password;
    }
}

public class UpdateUserPasswordCommandHandler : ICommandHandler<UpdateUserPasswordCommand>
{
    private readonly IDataContext dataContext;

    public UpdateUserPasswordCommandHandler(IDataContext dataContext)
    {
        this.dataContext = dataContext;
    }

    public void Handle(UpdateUserPasswordCommand command)
    {
        var user = dataContext.Users.Find(command.UserId);
        user.Password = command.Password;

        dataContext.SaveChanges();
    }
}
```

<p>And here's the implementation of the <code>IQueryAndCommandDispatcher</code> interface:</p>

<pre class="lang-csharp prettyprint-override"><code>public class QueryAndCommandDispatcher : IQueryAndCommandDispatcher
{
    private readonly IKernel kernel;

    public QueryAndCommandDispatcher(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public void ExecuteCommand<T>(T command) where T : class
    {
        var handler = kernel.Get<ICommandHandler<T>>();

        handler.Handle(command);
    }

    public TResult ExecuteQuery<TQueryData, TResult>(TQueryData query) where TQueryData : class
    {
        var handler = kernel.Get<IQueryHandler<TQueryData, TResult>>();

        return handler.Execute(query);
    }
}
</code>```

And everything comes together in a controller like this:

public class HomeController : Controller
{
    private readonly IQueryAndCommandDispatcher dispatcher;

    public HomeController(IQueryAndCommandDispatcher dispatcher)
    {
        this.dispatcher = dispatcher;
    }

    [HttpGet]
    public ActionResult Index(string email)
    {
        var userQuery = new GetUserByEmailQuery(email);
        var user = dispatcher.ExecuteQuery<GetUserByEmailQuery, User>(userQuery);

        return View(user);
    }

    [HttpPost]
    public ActionResult Update(int userId, string password)
    {
        var updateCommand = new UpdateUserPasswordCommand(userId, password);
        dispatcher.ExecuteCommand(updateCommand);

        return View();
    }
}
```

This reduces the number of dependencies your controllers need while still keeping everything testable.

Body:
I've been playig around with using seperate query and command classes instead of using repositories with multiple methods.

Your UserRepository might a GetByEmail(string email) method. Instead of that, I have a GetUserByEmailQuery class and a GetUserByEmailQueryHandler class.

Your UserRepository might have a UpdatePassword(string newPassword) method. Instead of that, I have a UpdateUserPasswordCommand class and a UpdateUserPasswordCommandHandler class.

Everything comes together in my controllers through a QueryAndCommandDispatcher.

First some interfaces:

public interface IQueryHandler<in TQueryData, out TResult> where TQueryData : class
{
    TResult Execute(TQueryData query);
}

public interface ICommandHandler<in T> where T : class
{
    void Handle(T command);
}

public interface IQueryAndCommandDispatcher
{
    void ExecuteCommand<T>(T command) where T : class;
    TResult ExecuteQuery<TQueryData, TResult>(TQueryData query) where TQueryData : class;
}

As you can see, a query is supposed to return something while a command isn't. A command should change data, a query shouldn't.

Here's how that query to get a user by his or her email would look like (IDataContext is an interface describing my custom DbContext):

public class GetUserByEmailQuery
{
    public string Email { get; private set; }

    public GetUserByEmailQuery(string email)
    {
        Email = email;
    }
}

public class GetUserByEmailQueryHandler : IQueryHandler<GetUserByEmailQuery, User>
{
    private readonly IDataContext dataContext;

    public GetUserByEmailQueryHandler(IDataContext dataContext)
    {
        this.dataContext = dataContext;
    }

    public User Execute(GetUserByEmailQuery query)
    {
        return dataContext.Users.First(u => u.Email == query.Email);
    }
}

Here's how that command to update a user's password would look like:

public class UpdateUserPasswordCommand
{
    public int UserId { get; private set; }
    public string Password { get; private set; }

    public UpdateUserPasswordCommand(int userId, string password)
    {
        UserId = userId;
        Password = password;
    }
}

public class UpdateUserPasswordCommandHandler : ICommandHandler<UpdateUserPasswordCommand>
{
    private readonly IDataContext dataContext;

    public UpdateUserPasswordCommandHandler(IDataContext dataContext)
    {
        this.dataContext = dataContext;
    }

    public void Handle(UpdateUserPasswordCommand command)
    {
        var user = dataContext.Users.Find(command.UserId);
        user.Password = command.Password;

        dataContext.SaveChanges();
    }
}

And here's the implementation of the IQueryAndCommandDispatcher interface:

public class QueryAndCommandDispatcher : IQueryAndCommandDispatcher
{
    private readonly IKernel kernel;

    public QueryAndCommandDispatcher(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public void ExecuteCommand<T>(T command) where T : class
    {
        var handler = kernel.Get<ICommandHandler<T>>();

        handler.Handle(command);
    }

    public TResult ExecuteQuery<TQueryData, TResult>(TQueryData query) where TQueryData : class
    {
        var handler = kernel.Get<IQueryHandler<TQueryData, TResult>>();

        return handler.Execute(query);
    }
}

And everything comes together in a controller like this:

public class HomeController : Controller
{
    private readonly IQueryAndCommandDispatcher dispatcher;

    public HomeController(IQueryAndCommandDispatcher dispatcher)
    {
        this.dispatcher = dispatcher;
    }

    [HttpGet]
    public ActionResult Index(string email)
    {
        var userQuery = new GetUserByEmailQuery(email);
        var user = dispatcher.ExecuteQuery<GetUserByEmailQuery, User>(userQuery);

        return View(user);
    }

    [HttpPost]
    public ActionResult Update(int userId, string password)
    {
        var updateCommand = new UpdateUserPasswordCommand(userId, password);
        dispatcher.ExecuteCommand(updateCommand);

        return View();
    }
}

This reduces the number of dependencies your controllers need while still keeping everything testable.


答:
In my opinion a controller should only be a thin layer around the businesslogic.

If the controller needs several repositories that might be an indicator that the controller is doing too much and
logic should be moved to servicelayers for seperation of concerns:

Instead of having

```<code>OrderController(productRepository, priceRepository,
                  availabilityRepository, orderRepository, orderLineRepository)
</code>```

i would have Services that know their own repository and subservices they use.

The Example above would become

```<code>priceCalculationService(productRepository, priceRepository)
orderService(orderRepository, orderLineRepository,
          availabilityService, priceCalculationService)

OrderController(orderService)
</code>```

Title: Generic Repositories with DI & Data Intensive Controllers

Body:
Usually, I consider a large number of parameters as an alarm bell that there may be a design problem somewhere. I am using a Generic Repository for an ASP.NET application and have a Controller with a growing number of parameters.

public class GenericRepository<T> : IRepository<T> where T : class
{
    protected DbContext Context { get; set; }
    protected DbSet<T> DbSet { get; set; }

    public GenericRepository(DbContext context)
    {
        Context = context;
        DbSet = context.Set<T>();
    }
    ...//methods excluded to keep the question readable

}
```

<p>I am using a DI container to pass in the DbContext to the generic repository. So far, this has met my needs and there are no other concrete implmentations of <code>IRepository<T></code>. However, I had to create a dashboard which uses data from many Entities. There was also a form containing a couple of dropdown lists. Now using the generic repository this makes the parameter requirments grow quickly.</p>

<p>The Controller will end up being something like</p>

<pre class="lang-cs prettyprint-override"><code>public HomeController(IRepository<EntityOne> entityOneRepository,
                      IRepository<EntityTwo> entityTwoRepository,
                      IRepository<EntityThree> entityThreeRepository,
                      IRepository<EntityFour> entityFourRepository,
                      ILogError logError,
                      ICurrentUser currentUser)
{
}
</code>```

It has about 6 IRepositories plus a few others to include the required data and the dropdown list options. In my mind this is too many parameters. From a performance point of view, there is only 1 DBContext per request and the DI container will serve the same DbContext to all of the Repositories. From a code standards/readability point of view it's ugly.

Is there a better way to handle this situation? Its a real world project with real world time constraints so I will not dwell on it too long, but from a learning perspective it would be good to see how such situations are handled by others.

Body:
In my opinion a controller should only be a thin layer around the businesslogic.

If the controller needs several repositories that might be an indicator that the controller is doing too much and
logic should be moved to servicelayers for seperation of concerns:

Instead of having

OrderController(productRepository, priceRepository,
                  availabilityRepository, orderRepository, orderLineRepository)

i would have Services that know their own repository and subservices they use.

The Example above would become

priceCalculationService(productRepository, priceRepository)
orderService(orderRepository, orderLineRepository,
          availabilityService, priceCalculationService)

OrderController(orderService)


答:
The implementation of LINQ uses lots of type checking for possible performance optimizations, and then a fallback for IEnumerable .

The most obvious example is probably the ElementAt method (tiny excerpt of .NET 4.5 source):

```<code>public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index) {
    IList<TSource> list = source as IList<TSource>;

    if (list != null) return list[index];
    // ... and then an enumerator is created and MoveNext is called index times
</code>```

But there are lots of places in the Enumerable class where a similar pattern is used.

So perhaps optimizing for performance for a commonly-used subtype is a valid use. I am not sure how this could have been designed better.

Title: When is type testing OK?

Body:
The implementation of LINQ uses lots of type checking for possible performance optimizations, and then a fallback for IEnumerable .

The most obvious example is probably the ElementAt method (tiny excerpt of .NET 4.5 source):

public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index) {
    IList<TSource> list = source as IList<TSource>;

    if (list != null) return list[index];
    // ... and then an enumerator is created and MoveNext is called index times

But there are lots of places in the Enumerable class where a similar pattern is used.

So perhaps optimizing for performance for a commonly-used subtype is a valid use. I am not sure how this could have been designed better.


答:
Dreading changes to a particular code base or module is usually a sign that refactoring needs to be seriously considered.

I'm not sure why you feel your output format requires that some hardcoding is required. It has always been my experience that templating (preferably as part of a larger effort to properly separate output format from code) is always possible, and that complications usually arise from bad code structuring and coding practices in the past, which again warrants fixing and/or refactoring.

A common problem with major refactoring jobs is that they often represent a considerable investment of resources that do not immediately translate in improved bottom lines for the client or employer. However, unless the projected future of your legacy code is limited, there is usually a case to be made for future savings on maintenance and expansion of the existing code base. YMMV of course, but in general it does pay to restructure and modularize major chunks of legacy code (even if that requires considerable refactoring) so as to make it future-proof in terms of maintenance and continued development.

Title: Designs for outputting to a spreadsheet

Body:
I'm working on a project where we are tasked to gather and output various data to a spreadsheet.

We are having tons of problems with the file that holds the code to write the spreadsheet. The cell that the data belongs to is hardcoded, so anytime you need to add anything to the middle of the spreadsheet, you have to increment the location for all the fields after that in the code. There are random blank rows, to add padding between sections, and subsections within the sections, so there's no real pattern that we can replicate. Essentially, anytime we have to add or change anything to the spreadsheet it requires a many long and tedious hours.

The code is all in this one large file, hacked together overtime in Perl. I've come up with a few OO solutions, but I'm not too familiar with OO programming in Perl and all my attempts at it haven't been great, so I've shied away from it so far. I've suggested we handle this section of the program with a more OO friendly language, but we can't apparently. I've also suggested that we scrap the entire spreadsheet idea, and just move to a webpage, but we can't do that either.

We've been working on this project for a few months, and every time we have to change that file, we all dread it. I'm thinking it's time to start some refactoring. However, I don't even know what could make this file easier to work with. The way the output is formatted makes it so that it has to be somewhat hardcoded.

I'm wondering if anyone has insight on any design patterns or techniques they have used to tackle a similar problem. I'm open to any ideas. Perl specific answers are welcome, but I am also interested in language-agnostic solutions.


答: Relational databases (SQL) are great for data that the underlying model remains stable. Many implementations have been around for a while (Oracle, DB2, SqlServer) and are stable and secure. Also, it's very easy to find experienced people to administrate them - and database admins are a must! The programmers should not have to deal with permissions, setup, and tuning. They should be able to concentrate on programming, and let the administrators worry about keeping the database up. Relational databases are also relatively easy to query, and there are many tools out there to assist with finding data from them.</p>

Title: How do you decide what kind of database to use?

Body:
I really dislike the name "NoSQL", because it isn't very descriptive.  It tells me what the databases aren't where I'm more interested in what the databases are.  I really think that this category really encompasses several categories of database.  I'm just trying to get a general idea of what job each particular database is the best tool for.

A few assumptions I'd like to make (and would ask you to make):

Assume that you have the capability to hire any number of brilliant engineers who are equally experienced with every database technology that has ever existed.

Assume you have the technical infrastructure to support any given database (including available servers and sysadmins who can support said database).

Assume that each database has the best support possible for free.

Assume you have 100% buy-in from management.

Assume you have an infinite amount of money to throw at the problem.

Now, I realize that the above assumptions eliminate a lot of valid considerations that are involved in choosing a database, but my focus is on figuring out what database is best for the job on a purely technical level.  So, given the above assumptions, the question is: what jobs are each database (including both SQL and NoSQL) the best tool for and why?


问:
How best to construct our test subjects in unit tests?
Some of our business logic classes require quite a few dependencies (in our case 7-10). As such when we come to unit test these the creation become quite complex.

In most tests these dependencies are often not required (only some dependencies are required for particular methods).

As a result unit tests often require a significant number of lines of code to mock up these useless dependencies (which can't be null because of null checks).

For example:

```<code>[Test]
public void TestMethodA()
{
  var dependency5 = new Mock<IDependency1>();
  dependency5.Setup(x => x. // some setup

  var sut = new Sut(new Mock<IDependency1>().Object,
    new Mock<IDependency2>().Object,
    new Mock<IDependency3>().Object,
    new Mock<IDependency4>().Object,
    dependency5);

  Assert.SomeAssert(sut.MethodA());
}
</code>```

In this example almost half the test is taken up creating dependencies which aren't used. I've investigated an approach where I have a helper method.

```<code>[Test]
public void TestMethodA()
{
  var dependency5 = new Mock<IDependency1>();
  dependency5.Setup(x => x. // some setup
  var sut = CreateSut(null, null, null, null, dependency5);

  Assert.SomeAssert(sut.MethodA());
}

private Sut CreateSut(IDependency1 d1, IDependency2 d2...)
{
  return new Sut(d1 ?? new Mock<IDependency1>().Object,
    d2 ?? new Mock<IDependency2>().Object,
}
</code>```

But these often grow very complicated very quickly.

What is the best way to create these BLL classes in test classes to reduce complexity and simplify tests?

答:
a few things:

1) 10 dependencies is too much. you are probably missing a layer of abstraction.
see:
https://stackoverflow.com/questions/2420193/how-to-avoid-dependency-injection-constructor-madness

http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices/

2)there are automocking frameworks like:

https://automock.codeplex.com/

3) theres also https://autofixture.codeplex.com/ to make your life easier


问:
How to avoid or minimise use of check/conditional statement in my scenario?
I have scenario, where I got stream and I need to check for some value. If I got any new value I have to store it in any of data structure.

It seems  very easy, I can place conditional statement if-else or can use contain method of set/map to check either received is new or not.

But the problem is checking will effect my application performance, in stream I will receive hundreds for value in second, if I start checking each and every value I received then for sure it effect performance.

Anybody can suggest me any mechanism or algorithm to solve my issue, either by bypassing checks or at least minimize them?

答: Use a HashSet which will not add an element if it is already there, its contains() implementation pretty well optimized provided you have a decent hashCode implementation.


问:
Nicest way to map RGB colors from HTML to LED
I have attached a RGB LED to a color picker on a webpage and have hit the obvious problem that though the LED takes 8-bit values (like HTML) the color rendering is very different so with the more subtle shades the LED values for the color are wildly different to the HTML values.

The brute-force method would be for me to have a lookup-table on the webserver to map the two sets of values but would ideally like to do it more elegantly.

Before I start listing all my 101 ideas for doing this I wondered if anyone else had come across the issue, the end-game would be to be able to abstract the color-rendering of different LEDs and make it available as a webservice (HTML value and device id in, LED value out).

答:
This would be impossible to do directly, because it depends heavily on calibration of the display and what kind of LED you are using. And also from different way human eye sees colors.

One way I think would be possible to provide your own "calibration". Display to the user multiple questions where each question will activate one color on LED and display multiple colors. Then have user pick the color, which is closes to the LED. Then you will have some data from which you can build calibration curve/table. It would also be good idea to make new questions based on previous calibration, so user will converge to calibration, that will represent his display.


问:
How can I set a time limit for a game?
I am learning the multi-threading and timer in C# now. But it seems I can't find a good solution.

For example, I would like to see how many addition problems that I can solve within 1 min. I would like my program to have

A digital clock to count for 60 seconds in the top of my Console.

Print a math problem in the middle of my console wait for my input.

When 60 seconds is done, stop the math problem challenges immediately (most of time, it is still waiting for my input, but we will stop it immediately).

Count how many correct problems that I have solved.

Two challenges of the program now.

a) how can we make sure the print time and math problem do not mess up.

b) how can we stop the math challenges part immediately after time is up

答:
I don't think console application is suitable for this kind of challenged UI controls.

I advice using much smarter objects. Anyway for making the timer you can use a Time and on the Tick event you can call the function to stop the game and show score.

And for time you can get DateTime.Now but this is not that dynamic result it will be just the time of starting.

If you really want to use a console you can make two console apps the first one is the game and the second is timer that sends window messages to the first when tick event pops out.

Title: How can I set a time limit for a game?


问:
Design for object with optional and modifiable attributtes?
I've been using the Builder pattern to create objects with a large number of attributes, where most of them are optional. But up until now, I've defined them as final, as recommended by Joshua Block and other authors, and haven't needed to change their values.

I am wondering what should  I do though if I need a class with a substantial number of optional but non-final (mutable) attributes?

My Builder pattern code looks like this:

```<code>public class Example {
    //All possible parameters (optional or not)
    private final int param1;
    private final int param2;

    //Builder class
    public static class Builder {
        private final int param1; //Required parameters
        private int param2 = 0;   //Optional parameters - initialized to default

        //Builder constructor
        public Builder (int param1) {
            this.param1 = param1;
        }

        //Setter-like methods for optional parameters
        public Builder param2(int value)
        { param2 = value; return this; }

        //build() method
        public Example build() {
            return new Example(this);
        }
    }

    //Private constructor
    private Example(Builder builder) {
        param1 = builder.param1;
        param2 = builder.param2;
    }
}
</code>```

Can I just remove the final keyword from the declaration to be able to access the attributes externally (through normal setters, for example)? Or is there a creational pattern that allows optional but non-final attributes that would be better suited in this case?

答:
You got it other way around.

The point of Builder is to allow creation of class, which has lots of final, but optional parameters. If you didn't use Builder, then you would have to use tons of different constructors.

But if your class doesn't need those fields to be final, then there is no need for a Builder. Just make them mutable and set them after you create the instance.


答:
Your issue is that you're trying to map 24-bit colors to 8-bit outputs (or inputs for your LED), where your color ranges are a lot more reduced - and probably provide only a segment of the actual code to your LED. To understand this better, please read this Wikipedia article and pay particular attention to "web-safe colors", because ultimately this is what you need to provide to your LED driver.

To actually provide your user with a realistic option, you could try and use this 8-bit color picker or a similar one you feel comfortable with, or even implement your own, and see if that does the trick.

Title: Nicest way to map RGB colors from HTML to LED

Body:
I have attached a RGB LED to a color picker on a webpage and have hit the obvious problem that though the LED takes 8-bit values (like HTML) the color rendering is very different so with the more subtle shades the LED values for the color are wildly different to the HTML values.

The brute-force method would be for me to have a lookup-table on the webserver to map the two sets of values but would ideally like to do it more elegantly.

Before I start listing all my 101 ideas for doing this I wondered if anyone else had come across the issue, the end-game would be to be able to abstract the color-rendering of different LEDs and make it available as a webservice (HTML value and device id in, LED value out).


答:
You construct them which ever way you need them constructed, and then you apply standard good practices to the resulting code - DRY, refactoring, single-responsibility, etc.

There is a widespread impression that it is bad to spend too much effort on testing code because of a vague belief that it isn't "real" code. This is very wrong.

Test code belongs to your code base and contributes to its excellence just as much as every other kind of deliverable. The fact that it isn't (normally) shipped to the customer is irrelevant. If it's worth writing test code because it saves time overall, then it's worth writing well-designed testing code because it saves even more time overall.

Therefore, there is absolutely nothing wrong with having helper classes only used in unit tests, or inventing mock objects more complicated than the mocking framework of your preference can auto-generate, if that's what's needed to get things under test. Indeed, this is the best way by definition.

Title: How best to construct our test subjects in unit tests?

Body:
Some of our business logic classes require quite a few dependencies (in our case 7-10). As such when we come to unit test these the creation become quite complex.

In most tests these dependencies are often not required (only some dependencies are required for particular methods).

As a result unit tests often require a significant number of lines of code to mock up these useless dependencies (which can't be null because of null checks).

For example:

```<code>[Test]
public void TestMethodA()
{
  var dependency5 = new Mock<IDependency1>();
  dependency5.Setup(x => x. // some setup

  var sut = new Sut(new Mock<IDependency1>().Object,
    new Mock<IDependency2>().Object,
    new Mock<IDependency3>().Object,
    new Mock<IDependency4>().Object,
    dependency5);

  Assert.SomeAssert(sut.MethodA());
}
</code>```

In this example almost half the test is taken up creating dependencies which aren't used. I've investigated an approach where I have a helper method.

```<code>[Test]
public void TestMethodA()
{
  var dependency5 = new Mock<IDependency1>();
  dependency5.Setup(x => x. // some setup
  var sut = CreateSut(null, null, null, null, dependency5);

  Assert.SomeAssert(sut.MethodA());
}

private Sut CreateSut(IDependency1 d1, IDependency2 d2...)
{
  return new Sut(d1 ?? new Mock<IDependency1>().Object,
    d2 ?? new Mock<IDependency2>().Object,
}
</code>```

But these often grow very complicated very quickly.

What is the best way to create these BLL classes in test classes to reduce complexity and simplify tests?


问:
When should a method of a class return the same instance after modifying itself?
I have a class that has three methods A(), B() and C(). Those methods modify the own instance.

While the methods have to return an instance when the instance is a separate copy (just as Clone()), I got a free choice to return void or the same instance (return this;) when modifying the same instance in the method and not returning any other value.

When deciding for returning the same modified instance, I can do neat method chains like obj.A().B().C();.

Would this be the only reason for doing so?

Is it even okay to modify the own instance and return it, too? Or should it only return a copy and leave the original object as before? Because when returning the same modified instance the user would maybe assume the returned value is a copy, otherwise it would not be returned? If it's okay, what's the best way to clarify such things on the method?

答:
Those methods modify the own instance.

Depending on the language, having methods that return void/unit and modify their instance or parameters is non-idiomatic. Even in languages that used to do that more (C#, C++), it is going out of fashion with the shift towards more functional style programming (immutable objects, pure functions). But let's assume there's a good reason for now.

Would this be the only reason for doing so?

For certain behaviors (think x++) it is expected that the operation returns the result, even though it modifies the variable. But that's largely the only reason to do it on your own.

Is it even okay to modify the own instance and return it, too? Or should it only return a copy and leave the original object as before? Because when return the same modified instance the user would maybe admit the returned value is a copy, otherwise it would not be returned? If it's okay, what's the best way to clarify such things on the method?

It depends.

In languages where copy/new and return is common (C# LINQ and strings) then returning the same reference would be confusing. In languages where modify and return is common (some C++ libraries) then copying would be confusing.

Making the signature unambiguous (by returning void or using language constructs like properties) would be the best way to clarify. After that, making the name clear like SetFoo to show that you're modifying the existing instance is good. But the key is to maintain the idioms of the language/library you're working with.

ContentLicense: CC BY-SA 4.0


答:
(I assumed C++ as your programming-language)

For me this is mostly a readability aspect. If A, B, C are modifiers, especially if this is a temporary object passed as a parameter to some function, e.g.

```<code>do_something(
      CPerson('name').age(24).height(160).weight(70)
      );
</code>```

compared to

```<code>{
   CPerson person('name');
   person.set_age(24);
   person.set_height(160);
   person.set_weight(70);
   do_something(person);
}
</code>```

Regrading if it's ok to return a reference to the modified instance, I'd say yes, and point you for example to the stream operators '>>' and '<<' (http://www.cprogramming.com/tutorial/operator_overloading.html)

Title: When should a method of a class return the same instance after modifying itself?

Body:
I have a class that has three methods A(), B() and C(). Those methods modify the own instance.

While the methods have to return an instance when the instance is a separate copy (just as Clone()), I got a free choice to return void or the same instance (return this;) when modifying the same instance in the method and not returning any other value.

When deciding for returning the same modified instance, I can do neat method chains like obj.A().B().C();.

Would this be the only reason for doing so?

Is it even okay to modify the own instance and return it, too? Or should it only return a copy and leave the original object as before? Because when returning the same modified instance the user would maybe assume the returned value is a copy, otherwise it would not be returned? If it's okay, what's the best way to clarify such things on the method?

Body:
(I assumed C++ as your programming-language)

For me this is mostly a readability aspect. If A, B, C are modifiers, especially if this is a temporary object passed as a parameter to some function, e.g.

do_something(
      CPerson('name').age(24).height(160).weight(70)
      );

compared to

{
   CPerson person('name');
   person.set_age(24);
   person.set_height(160);
   person.set_weight(70);
   do_something(person);
}

Regrading if it's ok to return a reference to the modified instance, I'd say yes, and point you for example to the stream operators '>>' and '<<' (http://www.cprogramming.com/tutorial/operator_overloading.html)


答:
Instead of using a table to store the mapping, consider building a "curve" for it: a mathematical function to calculate the conversions.  There are infinitely many ways to do this, but you can probably pick something simple like Béziers or polynomials.  The curve will have some unknown parameters that you'll need to fiddle with in order to produce the right results ("calibration").

For example, a really simple curve would be:

```<code>R = r ^ a
</code>```

where r is the original red component (scaled to the range from 0 to 1) and R is the new red component (scaled to the same range from 0 to 1).  The number a is a parameter that can be used for calibration (can range from 0 to ∞).

Note that HTML colors are 24-bits, whereas your LEDs are 8-bits, so you will need to do some downsampling.  Doing this just adds a minor complication to the conversion formula earlier.  You'll need to figure out the palette used by the 8-bit system, and round your values to those colors (no lookup tables are necessary unless the palette is really whacky).

Body:
Instead of using a table to store the mapping, consider building a "curve" for it: a mathematical function to calculate the conversions.  There are infinitely many ways to do this, but you can probably pick something simple like Béziers or polynomials.  The curve will have some unknown parameters that you'll need to fiddle with in order to produce the right results ("calibration").

For example, a really simple curve would be:

R = r ^ a

where r is the original red component (scaled to the range from 0 to 1) and R is the new red component (scaled to the same range from 0 to 1).  The number a is a parameter that can be used for calibration (can range from 0 to ∞).

Note that HTML colors are 24-bits, whereas your LEDs are 8-bits, so you will need to do some downsampling.  Doing this just adds a minor complication to the conversion formula earlier.  You'll need to figure out the palette used by the 8-bit system, and round your values to those colors (no lookup tables are necessary unless the palette is really whacky).


问:
Data Access Objects old fashioned?
A couple of weeks ago I delivered some work for a university project. After a code review with some teachers I got some snarky remarks about the fact that I was (still) using Data Access Objects. The teacher in question who said this mentions the use of DAO's in his classes and always says something along the lines of "Back then we always used DAO's". He's a big fan of Object Relational Mapping, which I also think is a great tool. When I was talking about this with some of my fellow students, they also mentioned that they prefer the use of ORM, which I can understand.

It did make me wonder though, is using DAO's really so old fashioned? I know that at my work DAO's are still being used, but this is due to the fact that some of the code is rather old and therefor can't be coupled with ORM. We also do use ORM at my work.

Trying to find some more information on Google or Stack Exchange sites didn't really enlighten me.

Should I step away from the use of DAO's and only start implementing ORM? I just feel that ORM's can be a bit overkill for some simple projects. I'd love to hear your opinions (or facts) about this.

答:
It is more "fashionable" but that doesn't mean it isn't more functional. There are some developers who have only interacted with data storage using an ORM.

Determine why you think an ORM is "over-kill" for a simple project. Do a little research and find out why they were created. Does it only make larger/more complex tasks easier or does it make basic/repetitive/mundane tasks easier? Does it require the inclusion of more code that you don't really need? Does it require more lines of code or does it obscure what is really happening so much that you can't trouble-shoot it? You may find that your skill set with one method is more fluent than another.

I think formatting code is similar. Once you get familiar and fluent with something (e.g. code indentation) it becomes more difficult to not do it. Working with legacy code can sometimes hinder gaining fluency with new technologies.

Title: Data Access Objects old fashioned?


答:
I think it depends on the project. Both have their place.

DAOs will give you greater level of control and can do things an ORM cannot do. TVFs in MS SQL Server for example are not available in EF. If you need to work across mulitple databases in one stored procedure, that cannot be done in cleanly in EF. So for low level control of your T-SQL, DAOs have their place.

On the other hand, for basic/straight-forward data access I would use an ORM. Its less time consuming for me to do so, so less cost to my client. It also displays the database schema and relationships in a clean easy to pick up and understand manner. This minimises time for other developers to pick up the project and understand it

Title: Data Access Objects old fashioned?

Body:
A couple of weeks ago I delivered some work for a university project. After a code review with some teachers I got some snarky remarks about the fact that I was (still) using Data Access Objects. The teacher in question who said this mentions the use of DAO's in his classes and always says something along the lines of "Back then we always used DAO's". He's a big fan of Object Relational Mapping, which I also think is a great tool. When I was talking about this with some of my fellow students, they also mentioned that they prefer the use of ORM, which I can understand.

It did make me wonder though, is using DAO's really so old fashioned? I know that at my work DAO's are still being used, but this is due to the fact that some of the code is rather old and therefor can't be coupled with ORM. We also do use ORM at my work.

Trying to find some more information on Google or Stack Exchange sites didn't really enlighten me.

Should I step away from the use of DAO's and only start implementing ORM? I just feel that ORM's can be a bit overkill for some simple projects. I'd love to hear your opinions (or facts) about this.


答:
You could also do the method chaining thing with copy return rather than modify return.

A good C# example is string.Replace(a,b) which doesn't change the string on which it was invoked but instead returns a new string allowing you to chain merrily away.


答:
When to use chaining

Function chaining is mostly popular with languages where an IDE with auto-complete is common place. For example, almost all C# developers use Visual Studio. Therefore, if you're developing with C# adding chaining to your methods can be a time saver for users of that class because Visual Studio will assist you in building the chain.

On the other hand, languages like PHP that are highly dynamic in nature and often don't have auto-complete support in IDEs will see fewer classes that support chaining. Chaining will only be appropriate when correct phpDocs are employed to expose the chainable methods.

What is chaining?

Given a class named Foo the following two methods are both chainable.

```<code>function what() { return this; }
function when() { return new Foo(this); }
</code>```

The fact that one is a reference to the current instance, and one creates a new instance doesn't change that these are chainable methods.

There is no gold rule that a chainable method must only reference the current object. Infact, chainable methods can be across two different classes. For example;

```<code>class B { function When() { return true; } };
class A { function What() { return new B(); } };

var a = new A();
var x = a.What().When();
</code>```

There is no reference to this in any of the above example. The code a.What().When() is an example of a chaining. What's interesting is that the class type B is never assigned to a variable.

A method is chained when it's return value becomes used as the next component of an expression.

Here are some more example

```<code> // return value never assigned.
 myFile.Open("something.txt").Write("stuff").Close();

// two chains used in expression
int x = a.X().Y() * b.X().Y();

// a chain that creates new strings
string name = str.Substring(1,10).Trim().ToUpperCase();
</code>```

When to use this and new(this)

Strings in most languages are immutable. So chaining method calls always results in new strings being created. Where as an object like StringBuilder can be modified.

Consistency is best practice.

If you have methods that modify the state of an object and return this, then don't mix in methods that return new instances. Instead, create a specific method called Clone() that will do this explicitly.

```<code> var x  = a.Foo().Boo().Clone().Foo();
</code>```

That is a lot clearer as to what is going on inside a.

The Step Outside And Back Trick

I call this the step out and back trick, because it solves a lot of common problems related to chaining. It basically means that you step out of the original class into a new temporary class and then back to the original class.

The temporary class exists only to provide special features to the original class, but only under special conditions.

There are often times when a chain needs to change state, but class A can not represent all of those possible states. So during a chain a new class is introduced that contains a reference back to A. This allows the programmer to step into a state and back to A.

Here is my example, let the special state be known as B.

```<code>class A {
    function Foo() { return this; }
    function Boo() { return this; }
    function Change() return new B(this); }
}

class B {
    var _a;
    function (A) { _a = A; }
    function What() { return this; }
    function When() { return this; }
    function End() { return _a; }
}

var a = new A();
a.Foo().Change().What().When().End().Boo();
</code>```

Now that is a very simple example. If you wanted to have more control, then B could return to a new super-type of A that has different methods.

Body:
When to use chaining

Function chaining is mostly popular with languages where an IDE with auto-complete is common place. For example, almost all C# developers use Visual Studio. Therefore, if you're developing with C# adding chaining to your methods can be a time saver for users of that class because Visual Studio will assist you in building the chain.

On the other hand, languages like PHP that are highly dynamic in nature and often don't have auto-complete support in IDEs will see fewer classes that support chaining. Chaining will only be appropriate when correct phpDocs are employed to expose the chainable methods.

What is chaining?

Given a class named Foo the following two methods are both chainable.

function what() { return this; }
function when() { return new Foo(this); }

The fact that one is a reference to the current instance, and one creates a new instance doesn't change that these are chainable methods.

There is no gold rule that a chainable method must only reference the current object. Infact, chainable methods can be across two different classes. For example;

class B { function When() { return true; } };
class A { function What() { return new B(); } };

var a = new A();
var x = a.What().When();

There is no reference to this in any of the above example. The code a.What().When() is an example of a chaining. What's interesting is that the class type B is never assigned to a variable.

A method is chained when it's return value becomes used as the next component of an expression.

Here are some more example

 // return value never assigned.
 myFile.Open("something.txt").Write("stuff").Close();

// two chains used in expression
int x = a.X().Y() * b.X().Y();

// a chain that creates new strings
string name = str.Substring(1,10).Trim().ToUpperCase();

When to use this and new(this)

Strings in most languages are immutable. So chaining method calls always results in new strings being created. Where as an object like StringBuilder can be modified.

Consistency is best practice.

If you have methods that modify the state of an object and return this, then don't mix in methods that return new instances. Instead, create a specific method called Clone() that will do this explicitly.

 var x  = a.Foo().Boo().Clone().Foo();

That is a lot clearer as to what is going on inside a.

The Step Outside And Back Trick

I call this the step out and back trick, because it solves a lot of common problems related to chaining. It basically means that you step out of the original class into a new temporary class and then back to the original class.

The temporary class exists only to provide special features to the original class, but only under special conditions.

There are often times when a chain needs to change state, but class A can not represent all of those possible states. So during a chain a new class is introduced that contains a reference back to A. This allows the programmer to step into a state and back to A.

Here is my example, let the special state be known as B.

class A {
    function Foo() { return this; }
    function Boo() { return this; }
    function Change() return new B(this); }
}

class B {
    var _a;
    function (A) { _a = A; }
    function What() { return this; }
    function When() { return this; }
    function End() { return _a; }
}

var a = new A();
a.Foo().Change().What().When().End().Boo();

Now that is a very simple example. If you wanted to have more control, then B could return to a new super-type of A that has different methods.


问:
Approaching SICP in Clojure instead of Scheme
I am a third year bachelor student in a software engineering program, and I brought up the idea of reading SICP to an adviser to gain a deeper and more fundamental understanding of the principles behind all this software we engineer.

He suggested not to learn Scheme to complete the book (because it's not as common as modern dialects of Lisp) but to do the exercises in Clojure instead.

It's an already difficult book, if I do attempt the book's exercises in the more modern Clojure, how would that work? For example, I can't find any real solutions, the syntax they teach for Scheme is different, etc.

答:
In my first year at the university the first programming course I took was using SICP (that was 1988). However, I had a similar problem like you: for my own computer (actually a Commodore Amiga), there was no Scheme implementation available at that time, only a different Lisp dialect (I don't remember its name).

However, given the flexibility of Lisp, it was pretty simple to "emulate" Scheme syntax just by adding the missing lisp macros and functions in a few scripts. This was actually enough to implement all the exercises from chapter 1 to 3 required during the course (note that SICP does actually not require the full Scheme stack, a small subset is all you need).

So since Clojure is AFAIK a modern Lisp dialect, I guess you could just do something similar, which gives you the fully free choice to write things either in Scheme or Clojure or a mixture of both.

Of course, solving the exercises directly in Clojure will also be possible, both languages are very similar. More important, SICP is not about programming language syntax, it is about the right use of abstractions in programming (for example, with functions, data, and objects). So don't think too much of possible syntax problems, these are not in the focus of this book and most probably of minor concern.


问:
What to Return with Async CRUD methods
While there is a similar question focused on Java, I've been in debates with utilizing Task objects. What's the best way to handle returns on CRUD methods (and similar)?

Common returns we've seen over the years are:

Void (no return unless there is an exception)

Boolean (True on Success, False on Failure, exception on unhandled failure)

Int or GUID (Return the newly created objects Id, 0 or null on failure, exception on unhandled failure)

The updated Object (exception on failure)

Result Object (Object that houses the manipulated object's ID, Boolean or status field to with success or failure indicated, Exception information if there was one, etc)

The concern comes into play as we've started moving over to utilizing C# 5's Async functionality, and this brought the question up of how we should handle CRUD returns large-scale. In our systems we have a little of everything in regards to what we return, we want to make these returns standardized...

Now the question is what is the recommended standard? Is there even a recommended standard yet? (I realize we need to decide our standard, but typically we do so by looking at best practices, see if it makes sense for us and go from there, but here we're not finding much to work with)

答:
You may find that certain methods are more common because certain data saving requirements are more common in applications than any type of standardization. We don't have error checks because it was mandated by some coding authority, we have error checks because we run into problems when errors aren't handled. "Of course the application crashed, you entered a null."

Being consistent is important, but that doesn't mean do everything the same. This depends on the functional requirements of your application. Differentiate what is truly different.

Example:  Save v. Save & Close

Obviously these are different, but do you consider the "Save" part of the functionality to be the same? If so, they both do the same thing on the Save part, and then the close. What about from the data storage perspective? Are they the same?

If I'm going to Save and it is a new record, it would be convenient to return the newly generated primary key/id from the database (Assuming all saves do that, which they may not.) so the application can stick with that record and do any updates as necessary. However, if I'm going to save and close, is returning the ID: necessary, a waste of resources or no different for all practical purposes, so let's be consistent with our saves.

There are times (way too many) when we don't have perfect data. You'll have hours of fun playing "Who changed the db?" You can decide to have the application check to make sure only one record was updated and throw a false if not. Maybe your app isn't handling concurrency (that will never happen) in the best way, so you just updated a record another user deleted.

Return things you need when you need them. Requirements will change. Try to decide upfront if you're going to throw your own exceptions-nobody likes surprises. If things are truly the same, be consistent, but don't try to handle different requirements the same way.

Title: What to Return with Async CRUD methods


答:
The short answer is that when it comes to security, and especially when it comes to cryptography, don't roll your own. Use vetted schemes that meet the approval of the security community in general. Your home-grown method is practically guaranteed to have flaws that you haven't thought of.

For a longer answer, read Thomas Pornin's excellent treatise on how to securely hash passwords. Most of what I'll write here is contained in that answer.

For password hashing, there are three generally-approved hashing functions: PBKDF2, bcrypt and scrypt. I won't compare them in this answer; none of these is a wrong choice. Several threads on Security Stack Exchange compare them, in particular Do any security experts recommend bcrypt for password storage? and Are there more modern password hashing methods than bcrypt and scrypt?.

Now, getting to the technical answer to your question, there are two things wrong with using e.g. SHA-256(username + password) as the password hash. The first thing is that user names are not unique. This has several implications:

In particular, this makes it obvious when a user has picked the same password on different sites, which can help for some targeted attacks.

Using a weak, predictable “salt” also facilitates non-targeted attacks that focus on the most common user names, e.g. a rainbow table with the 1000 most common user names and the 1,000,000 most common passwords has the same size as a rainbow table with the 1,000,000,000 most common passwords for unsalted hashes, and still catches quite a few weak passwords. A truly unique salt makes precomputed table useless.

The salt technically doesn't have to be random, but it needs to be unique, and using a random string is the easiest way of meeting this requirement.

For more details about salts, see Why are salted hashes more secure? and Convincing my manager to use salts. A pepper may optionally be combined with the salt — it's a good defense against some common attacks (database dump by SQL injection).

A second problem with your approach is that something like SHA-2(salt+password) is not good either. A hash function must be slow — legitimate servers only compute one authentication value, whereas attackers must make a lot of failed attempts, so slowness penalizes the attacker more. General-purpose hash functions like SHA-1 and SHA-2 are designed to be fast, they are no good for password hashing. You can turn them into a good password hash function by repeating them many times — but don't roll your own, because the devil is in the details: PBKDF2 is based on this principle.

Title: Is hashing of just "username + password" as safe as salted hashing

Body:
I want to hash "user + password".

[EDIT: prehashing "user" would be an improvement, so my question is also for hashing "hash(user) + password". If cross-site same user is a problem then the hashing changed to hashing "hash(serviceName + user) + password"]

From what I read about salted hash, using "user + password" as input to hash function will help us avoid problem with reverse hash table hacking. The same thing can be said about rainbow table.

Any reason why this is not as good as salted hashing?


问:
Requesting feedback on my OO design
I'm working on an application that creates music by itself. I'm seeking feedback for my OO design so far. This question will focus on one part of the program.

The application produces Tune objects, that are the final musical products. Tune is an abstract class with an abstract method play. It has two subclasses: SimpleTune and StructuredTune.

SimpleTune owns a Melody and a Progression (chord sequence). It's play implementation plays these two objects simultaneously. StructuredTune owns two Tune instances. It's own play plays the two Tunes one after the other according to a pattern (currently only ABAB).

Melody is an abstract class with an abstract play method. It has two subclasses: SimpleMelody and StructuredMelody.

SimpleMelody is composed of an array of notes. Invoking play on it plays these notes one after the other. StructuredMelody is composed of an array of Melody objects. Invoking play on it plays these Melodyies one after the other.

I think you're starting to see the pattern. Progression is also an abstract class with a play method and two subclasses: SimpleProgression and StructuredProgression, each composed differently and played differently.

SimpleProgression owns an array of chords and plays them sequentially. StructuredProgression owns an array of Progressions and it's play implementation plays them sequentially.

Every class has a corresponding Generator class. Tune, Melody and Progression are matched with corresponding abstract TuneGenerator, MelodyGenerator and ProgressionGenerator classes, each with an abstract generate method. For example MelodyGenerator defines an abstract Melody generate method.

Each of the generators has two subclasses, Simple and Structured. So for example MelodyGenerator has a subclasses SimpleMelodyGenerator, with an implementation of generate that returns a SimpleMelody.

(It's important to note that the generate methods encapsulate complex algorithms. They are more than mere factory method. For example SimpleProgressionGenerator.generate() implements an algorithm to compose a series of Chord objects, which are used to instantiate the returned SimpleProgression).

Every Structured generator uses another generator internally. It is a Simple generator be default, but in special cases may be a Structured generator.

Parts of this design are meant to allow the end-user through the GUI to choose what kind of music is to be created. For example the user can choose between a "simple tune" (SimpleTuneGenerator) and a "full tune" (StructuredTuneGenerator). Other parts of the system aren't subject to direct user-control.

My question regarding this design is rather specific:

When I look at my design, it looks like the design-equivalent of 'code duplication': 'class-duplication' or 'design-duplication'. You can clearly see what I'm referring to if you look at the above diagram.

My question is split into two:

Is my intuition correct? Is this duplication, or reoccuring pattern in the design, a bad thing?

If it is, how can I design this differently and more efficiently?

答:
Are those really subclasses? I don't think you need all those subclasses.

As you've already pointed out:

SimpleMelody is composed of an array of notes. Invoking play on it plays these notes one after the other. StructuredMelody is composed of an array of Melody objects. Invoking play on it plays these Melodies one after the other.

In other words, SimpleMelody is an Array of Notes, not an "is a" melody.   StructuredMelody is an array of melody objects, not an elaboration of Melody.

They are just collections, in other words.  If you want to wrap those collections in their own classes and give them additional properties or methods, use composition, not inheritance.

There's nothing wrong with having one-for-one generator classes.  If that makes you uncomfortable, put static factory methods in the actual classes, as in

```<code>var melody = Melody.Create(foo);
</code>```

In general, I think you're creating a lot of abstraction for not much benefit.  Just stick with Note, Melody and collection classes at first, and add the additional abstractions if you need them.

Title: Requesting feedback on my OO design

Body:
Are those really subclasses? I don't think you need all those subclasses.

As you've already pointed out:

SimpleMelody is composed of an array of notes. Invoking play on it plays these notes one after the other. StructuredMelody is composed of an array of Melody objects. Invoking play on it plays these Melodies one after the other.

In other words, SimpleMelody is an Array of Notes, not an "is a" melody.   StructuredMelody is an array of melody objects, not an elaboration of Melody.

They are just collections, in other words.  If you want to wrap those collections in their own classes and give them additional properties or methods, use composition, not inheritance.

There's nothing wrong with having one-for-one generator classes.  If that makes you uncomfortable, put static factory methods in the actual classes, as in

var melody = Melody.Create(foo);

In general, I think you're creating a lot of abstraction for not much benefit.  Just stick with Note, Melody and collection classes at first, and add the additional abstractions if you need them.