سؤال

I'm fairly new at event driven programming and using MVC so forgive me if this question seems like a non-question.

I'm trying to assign values to my singleton model class (Client). I have 2 options:

  1. I can use the model class constructor to assign to itself like so:

    Class Client{

         public var name;
         public var email;
    
         public function Client(arg_name, arg_email){
             this.name = arg_name;
             this.email = arg_email;
           } 
      }
    
  2. I can use the controller to assign my values for me like so:

    Class Controller{
         public var client:Client = new Client();
    
         public function assign(){
            client.name = "booo";
            client.email = "blaaah@email.com";
         }
    

    }

Which one of these is a better solution? :) The reason why I'm so confused is cause I've seen examples that just pass values to the model class and do #1 (and setting new variables such as [var fullname = fname + lname], yet I know for a fact that it is the controller's job to assign values to the model.

هل كانت مفيدة؟

المحلول

Better is relative.

The second example is what is commonly called "property injection".

Basically the first option is quicker, smaller, and much less code.

The second option is more readable and flexible.

Regardless of the Controller, injection has the benefit that you can create getters and setters for each property.

So basically you can have something happen such as dispatching an event whenever you change the value of the "name" property.

The flex source code is filled with this concept. For example whenever you change the width of a group, it doesn't just change the value, it performs checks and then sets the group as dirty so that other things can react to it.

Basically it makes it simple to have everything do it's own thing, and it's more Object oriented.

All that doesn't mean that it's actually better, but it is more common now to write code in the second option style.

Hope that helps.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top