EzDevInfo.com

model-view-controller interview questions

Top model-view-controller frequently asked interview questions

What is the difference between MVC and MVVM? [closed]

Is there a difference between the standard "Model View Controller" pattern and Microsoft's Model/View/ViewModel pattern?


Source: (StackOverflow)

MVC pattern in Android?

Is it possible to implement the Model-View-Controller pattern in Java for Android? Or is it already implemented through Activities? Or is there a better way to implement the MVC pattern for Android?


Source: (StackOverflow)

Advertisements

what is Data Transfer Object?

what is a Data Transfer Object?

In MVC are the model classes DTO, and if not what are the differences and do we need both?


Source: (StackOverflow)

How does differential execution work?

I've seen a few mentions of this on Stack Overflow, but staring at Wikipedia (the relevant page has since been deleted) and at an MFC dynamic dialog demo did nothing to enlighten me. Can someone please explain this? Learning a fundamentally different concept sounds nice.


Based on the answers: I think I'm getting a better feel for it. I guess I just didn't look at the source code carefully enough the first time. I have mixed feelings about differential execution at this point. On the one hand, it can make certain tasks considerably easier. On the other hand, getting it up and running (that is, setting it up in your language of choice) is not easy (I'm sure it would be if I understood it better)...though I guess the toolbox for it need only be made once, then expanded as necessary. I think in order to really understand it, I'll probably need to try implementing it in another language.


Source: (StackOverflow)

ngRepeat - limiting number of displayed results

I'm a huge AngularJS n00b and am finding even the tutorials hard to understand. This tutorial is walking me through building an app that displays phones. I'm on step 5 and I thought as an experiment I'd try to allow users to specify how many they'd like to be shown. The view looks like this:

<body ng-controller="PhoneListCtrl">

  <div class="container-fluid">
    <div class="row-fluid">
      <div class="span2">
        <!--Sidebar content-->

        Search: <input ng-model="query">
        How Many: <input ng-model="quantity">
        Sort by:
        <select ng-model="orderProp">
          <option value="name">Alphabetical</option>
          <option value="age">Newest</option>
        </select>

      </div>
      <div class="span10">
        <!--Body content-->

        <ul class="phones">
          <li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
            {{phone.name}}
            <p>{{phone.snippet}}</p>
          </li>
        </ul>

      </div>
    </div>
  </div>
</body>

I've added this line that users can enter how many results they want shown:

How Many: <input ng-model="quantity">

Here's my controller:

function PhoneListCtrl($scope, $http) {
  $http.get('phones/phones.json').success(function(data) {
    $scope.phones = data.splice(0, 'quantity');
  });

  $scope.orderProp = 'age';
  $scope.quantity = 5;
}

The important line is: $scope.phones = data.splice(0, 'quantity');

I can hard-code in a number to represent how many phones should be shown. If I put 5 in, 5 will be shown. All I want to do is read the number in that input from the view, and put that in the data.splice line. I've tried with and without quotes, and neither work. How do I do this?


Source: (StackOverflow)

FLOW3 action parameters and arrays of objects

FLOW3 provides a convenient way to pass entities by ID in the URL, and get them automatically instantiated in the controller action's parameters:

class PostController extends \TYPO3\FLOW3\MVC\Controller\ActionController {
    public function editAction(Post $post) {
        ...
    }
}

But what about the use case where you have checkboxes, each representing a particular object? It would be handy to get them autoinstantiated as well:

<input type="checkbox" name="tags[]" value="1" />
<input type="checkbox" name="tags[]" value="2" />
...

Is there a way to tell FLOW3 to auto-instantiate the $tags variable as an array of Tag objects? Something like:

public function setTagsAction(Post $post, /** @var Model\Tag */ array $tags) {
    $post->setTags($tags);
}

Source: (StackOverflow)

Best practices of building a website using node.js

I was wondering how one would go about developing a website from scratch with node.js. I understand how I could possibly do it, but I am interested in the best design practice.

I need this theoretical website to:

  1. Do a lot of AJAX
  2. Be very straightforward
  3. Be relatively small
  4. Connect to... let's say a MYSQL server

In PHP building a pretty small website was very straightforward - I set up php on apache and a mysql server and then do something like:

  • includes/db/ which has connect.php for connecting to the db, a file with common db related functions and so on
  • includes/layout/ which had stuff like footer.php, header.php, and other layout related stuff
  • includes/users/ to handle user related actions

Then php just let you build pages and include these files together to form a website - I could go something like:

<?php
   require_once('inclues/users/user_session.php');
   require_once('inclues/db/connect.php');
   require_once('inclues/design/header.php')
?>

Other php or html or related content relating to the page

<?php
   require_once('inclues/.../footer.php');
?>

I was wondering what might be similar in node.js - I am looking for a way to accomplish this which is as simple, fast and straightforward as possible.

If the answer is not simple, I would love a book recommendation, I don't mind reading.

I love event based programming, I really love javascript's abilities and I'm really excited about node.js. I want to learn how to develop this sort of stuff with it the right way from the start.


Source: (StackOverflow)

How to include view/partial specific styling in AngularJS

So, I used Yeoman to scaffold my new project and I LOVE using bower, grunt, and AutoReload, I never even realized how efficient I could be with this kind of dev environment. I always turned it down due to its complexity.

Anyway, that is beside the point. The one thing I'm having a small problem with is Angular.

What is the proper/accepted way to use separate stylesheets for the various views my application uses?

Currently I'm placing a link element in the view/partial's html at the top but I've been told this is bad practice even though all modern browsers support it but I can see why it's frowned upon.

The other possibility is placing the separate stylesheets in my index.html's head but I would like it to only load the stylesheet if its view is being loaded in the name of performance.

Is this bad practice since styling won't take effect until after the css is loaded form the server, leading to a quick flash of unformatted content in a slow browser? I have yet to witness this although I'm testing it locally.

Is there a way to load the CSS through the object passed to Angular's $routeProvider.when?

Thanks in advance!


Source: (StackOverflow)

How do I fetch a single model in Backbone?

I have a Clock model in Backbone:

var Clock = Backbone.Model.extend({});

I'm trying to get an instance of that that has the latest information from /clocks/123. Some things I've tried:

a "class"-level method

Clock.fetch(123)
// TypeError: Object function (){ ... } has no method 'fetch'

creating an instance and then calling fetch on it:

c = new Clock({id: 123})
c.fetch()
// Error: A 'url' property or function must be specified

a collection

I tried creating an AllClocks collection resource (even though I have no use for such a thing on the page):

var AllClocks = Backbone.Collection.extend({
  model: Clock,
  url: '/clocks/'
});
var allClocks = new AllClocks();
allClocks.fetch(123);
// returns everything from /clocks/

How do I just get one API-backed Clock?


Source: (StackOverflow)

How to do two-way filtering in angular.js?

One of the interesting things Angular.js can do is apply a filter to a particular databinding expression, which is a convenient way to apply, for example, culture-specific currency or date formatting of a model's properties. It is also nice to have computed properties on the scope. The problem is that neither of these features work with two-way databinding scenarios - only one-way databinding from the scope to the view. This seems to be a glaring omission in an otherwise excellent library - or am I missing something?

In KnockoutJS, I could create a read/write computed property, which allowed me to specify a pair of functions, one which is called to get the value of the property, and one which is called when the property is set. This allowed me to implement, for example, culture-aware input - letting the user type "$1.24" and parsing that into a float in the ViewModel, and have changes in the ViewModel reflected in the input.

The closest thing I could find similar to this is the use of $scope.$watch(propertyName, functionOrNGExpression); This allows me to have a function invoked when a property in the $scope changes. But this doesn't solve, for example, the culture-aware input problem. Notice the problems when I try to modify the $watched property within the $watch method itself:

$scope.$watch("property", function (newValue, oldValue) {
    $scope.outputMessage = "oldValue: " + oldValue + " newValue: " + newValue;
    $scope.property = Globalize.parseFloat(newValue);
});

(http://jsfiddle.net/gyZH8/2/)

The input element gets very confused when the user starts typing. I improved it by splitting the property into two properties, one for the unparsed value and one for the parsed value:

$scope.visibleProperty= 0.0;
$scope.hiddenProperty = 0.0;
$scope.$watch("visibleProperty", function (newValue, oldValue) {
    $scope.outputMessage = "oldValue: " + oldValue + " newValue: " + newValue;
    $scope.hiddenProperty = Globalize.parseFloat(newValue);
});

(http://jsfiddle.net/XkPNv/1/)

This was an improvement over the first version, but is a bit more verbose, and notice that there is still an issue of the parsedValue property of the scope changes (type something in the second input, which changes the parsedValue directly. notice the top input does not update). This might happen from a controller action or from loading data from a data service.

Is there some easier way to implement this scenario using Angular.js? Am I missing some functionality in the documentation?


Source: (StackOverflow)

Business logic in MVC

I have 2 questions:

Q1. Where exactly does "business logic" lie in the MVC pattern? I am confused between Model and Controller.

Q2. Is "business logic" the same as "business rules"? If not, what is the difference?

It would be great if you could explain with a small example.


Source: (StackOverflow)

Implementing MVC with Windows Forms

Where can I find a good example on how to completely implement the MVC pattern in Windows Forms?

I found many tutorials and code examples on various sites (for example, The Code Project and .NetHeaven), but many are more representative for the observer pattern than MVC. Since the application I want to develop is for a school project, I am reluctant to using frameworks like PureMVC or MVC#.


Source: (StackOverflow)

GUI not working after rewriting to MVC

I'm practicing MVC style programming. I have a Mastermind game in a single file, working fine (maybe apart of the fact that "Check" button is invisible at start).

http://paste.pocoo.org/show/226726/

But when I've rewritten it to model, view, controller files - and when I click on empty Pin (that should be updated, and repainted with new color) - noting happens. Can anybody see any problems here ? I've tried placing repaint() in different places, but it simply does not work at all :/

Main :

public class Main { 
    public static void main(String[] args){
        Model model = new Model();
        View view = new View("Mastermind", 400, 590, model);
        Controller controller = new Controller(model, view); 
        view.setVisible(true);
    }
}

Model :

import java.util.Random;

public class Model{
    static final int
    LINE = 5,
    SCORE = 10, OPTIONS = 20;
    Pin pins[][] = new Pin[21][LINE];
    int combination[] = new int[LINE];
    int curPin = 0;
    int turn = 1;
    Random generator = new Random();
    int repaintPin;
    boolean pinsRepaint=false;
    int pinsToRepaint;
    boolean isUpdate = true, isPlaying = true, isRowFull = false;
    static final int HIT_X[] = {270,290,310,290,310}, HIT_Y[] = {506,496,496,516,516};

    public Model(){

        for ( int i=0; i < SCORE; i++ ){
            for ( int j = 0; j < LINE; j++ ){
                pins[i][j] = new Pin(20,0);
                pins[i][j].setPosition(j*50+30,510-i*50);
                pins[i+SCORE][j] = new Pin(8,0);
                pins[i+SCORE][j].setPosition(HIT_X[j],HIT_Y[j]-i*50);
            }
        }
        for ( int i=0; i < LINE; i++ ){
            pins[OPTIONS][i] = new Pin( 20, i+2 );
            pins[OPTIONS][i].setPosition( 370,i * 50 + 56);
        }

    }

    void fillHole(int color) {
        pins[turn-1][curPin].setColor(color+1);
        pinsRepaint = true;
        pinsToRepaint = turn;
        curPin = (curPin+1) % LINE;
        if (curPin == 0){
            isRowFull = true;
        }
        pinsRepaint = false;
        pinsToRepaint = 0;
    }

    void check() {
        int junkPins[] = new int[LINE], junkCode[] = new int[LINE];
        int pinCount = 0, pico = 0;

        for ( int i = 0; i < LINE; i++ ) {
            junkPins[i] = pins[turn-1][i].getColor();
            junkCode[i] = combination[i];
        }
        for ( int i = 0; i < LINE; i++ ){
            if (junkPins[i]==junkCode[i]) {
                pins[turn+SCORE][pinCount].setColor(1);
                pinCount++;
                pico++;
                junkPins[i] = 98;
                junkCode[i] = 99;
            }
        }
        for ( int i = 0; i < LINE; i++ ){
            for ( int j = 0; j < LINE; j++ )
                if (junkPins[i]==junkCode[j]) {
                    pins[turn+SCORE][pinCount].setColor(2);
                    pinCount++;
                    junkPins[i] = 98;
                    junkCode[j] = 99;
                    j = LINE;
            }
        }
        pinsRepaint = true;
        pinsToRepaint = turn + SCORE;
        pinsRepaint = false;
        pinsToRepaint=0;

        if ( pico == LINE ){
            isPlaying = false;
        }
        else if ( turn >= 10 ){
                isPlaying = false;
        }
        else{
            curPin = 0;
            isRowFull = false;
            turn++;
        }
    }

    void combination() {
        for ( int i = 0; i < LINE; i++ ){
          combination[i] = generator.nextInt(6) + 1;
        }
    }
}

class Pin{
    private int color, X, Y, radius;

    public Pin(){
        X = 0; Y = 0; radius = 0; color = 0;
    }

    public Pin( int r,int c ){
        X = 0; Y = 0; radius = r; color = c;
    }

    public int getX(){
        return X;
    }

    public int getY(){
        return Y;
    }

    public int getRadius(){
        return radius;
    }

    public void setRadius(int r){
        radius = r;
    }

    public void setPosition( int x,int y ){
        this.X = x ;
        this.Y = y ;
    }
    public void setColor( int c ){
        color = c;
    }
    public int getColor() {
        return color;
    }
}

View:

import java.awt.*;
import javax.swing.*;

public class View extends Frame{  
    Model model;
    JButton checkAnswer;
    private JPanel button;
    private static final Color COLORS[] = {Color.black, Color.white, Color.red, Color.yellow, Color.green, Color.blue, new Color(7, 254, 250)};

    public View(String name, int w, int h, Model m){
        model = m;
        setTitle( name );
        setSize( w,h );
        setResizable( false );
        this.setLayout(new BorderLayout());

        button = new JPanel();
        button.setSize( new Dimension(400, 100));
        button.setVisible(true);
        checkAnswer = new JButton("Check");
        checkAnswer.setSize( new Dimension(200, 30));
        button.add( checkAnswer );
        this.add( button, BorderLayout.SOUTH);
        button.setVisible(true);
    }

    @Override
    public void paint( Graphics g ) {
        g.setColor( new Color(238, 238, 238));
        g.fillRect( 0,0,400,590);

        for ( int i=0; i < model.pins.length; i++ ) {
            paintPins(model.pins[i][0],g);
            paintPins(model.pins[i][1],g);
            paintPins(model.pins[i][2],g);
            paintPins(model.pins[i][3],g);
            paintPins(model.pins[i][4],g);
        }
    }

    @Override
    public void update( Graphics g ) {
        if ( model.isUpdate ) {
            paint(g);
        }
        else {
            model.isUpdate = true;
            paintPins(model.pins[model.repaintPin-1][0],g);
            paintPins(model.pins[model.repaintPin-1][1],g);
            paintPins(model.pins[model.repaintPin-1][2],g);
            paintPins(model.pins[model.repaintPin-1][3],g);
            paintPins(model.pins[model.repaintPin-1][4],g);
        }
    }

    void repaintPins( int pin ) {
        model.repaintPin = pin;
        model.isUpdate = false;
        repaint();
    }

    public void paintPins(Pin p, Graphics g ){
        int X = p.getX();
        int Y = p.getY();
        int color = p.getColor();
        int radius = p.getRadius();
        int x = X-radius;
        int y = Y-radius;

        if (color > 0){
            g.setColor( COLORS[color]);
            g.fillOval( x,y,2*radius,2*radius );
        }
        else{
            g.setColor( new Color(238, 238, 238) );
            g.drawOval( x,y,2*radius-1,2*radius-1 );
        }
        g.setColor( Color.black );
        g.drawOval( x,y,2*radius,2*radius );
    }
}

Controller:

import java.awt.*;
import java.awt.event.*;

public class Controller implements MouseListener, ActionListener { 
    private Model model;
    private View view;

    public Controller(Model m, View v){ 
        model = m;
        view = v;

        view.addWindowListener( new WindowAdapter(){
            public void windowClosing(WindowEvent e){
            System.exit(0);
        } });
        view.addMouseListener(this);
        view.checkAnswer.addActionListener(this);
        model.combination();
    }

    public void actionPerformed( ActionEvent e ) {
        if(e.getSource() == view.checkAnswer){
            if(model.isRowFull){
                model.check();
            }
        }
    }

    public void mousePressed(MouseEvent e) {
        Point mouse = new Point();

        mouse = e.getPoint();
        if (model.isPlaying){
            if (mouse.x > 350) {
                int button = 1 + (int)((mouse.y - 32) / 50);
                if ((button >= 1) && (button <= 5)){
                    model.fillHole(button);
                    if(model.pinsRepaint){
                        view.repaintPins( model.pinsToRepaint );
                    }
                }
            }
        }
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e)  {}
}

Source: (StackOverflow)

Can I get the name of the current controller in the view?

Is there a way to figure out what the current controller is from within the view?

For an example of why I would want to know this: if several controllers share the same layout, I may have a part in the layout ERB file where I want to highlight the current page's menu item based on the controller.

Maybe that is a bad approach. If so, what is the more preferred way to do this?

I'm interested to know about getting the name of the current controller either way, though.

(Obviously I could put something like @controller_name = 'users' in each controller; but that seems like the sort of thing Rails would've already done behind the scenes. So I'm just wondering if there's a built-in way.)


Source: (StackOverflow)

Unable to set data attribute using jQuery Data() API

I've got the following field on an MVC view:

@Html.TextBoxFor(model => model.Course.Title, new { data_helptext = "Old Text" })</span>

In a seperate js file, I want to set the data-helptext attribute to a string value. Here's my code:

alert($(targetField).data("helptext"));

$(targetField).data("helptext", "Testing 123");

The alert() call works fine, it shows the text "Old Text" in an alert dialog. However, the call to set the data-helptext attribute to "Testing 123" does not work. "Old Text" is still the attribute's current value.

Am I using the call to data() incorrectly? I've looked this up on the web, and I can't see what I'm doing wrong.

Here's the HTML markup:

<input data-helptext="Old Text" id="Course_Title" name="Course.Title" type="text" value="" />

Source: (StackOverflow)