fbpx

MVC OR MVVM – Take Your Pick

MVC OR MVVM – Take Your Pick

The architecture of an application is the most important thing when building the application coz the choice you make ensures how flexible is your application and how easy is to build, modify and test it while ensuring that the performance is intact. We being a developer always confused about MVC or MVVM – Take Your pick.

Introduction:-

MVC as we all know stands for Model View Controller is a very popular choice when it comes to the question of designing the architecture of the project. Before we go into the comparison and analyse of the pros and cons of both the architecture.

First let’s understand what are these two terms in layman words:

  1. MVC(Model View Controller): let’s assume an application to be a store. So first of all the view of an application is like the showroom where all the goods are in display, i.e all the interaction with the customer s take apace at the showroom level or the view level. Next, the controller is the salesman who interacts with the customer, heeds the needs and fetches them from their storage or the godown. The model is the godown where employees are working to fetch the required goods, manage it and hand it over to the salesman or the controller so that it can be handed over to the customer or the user.

Here the goods or the commodities are the program data.

The whole idea behind implementing the architectures are to add simplicity and tenacity to the application so that any modification in the application can be facilitated without disrupting the entire program of the application. In practise different types of MVC are used but we are not going into that. The above explanation may be over simplification of a huge topic such as MVC but the above description may be enough to get an idea as to what it is.

  1. MVVM (Model View View Model) :

    is an architectural pattern used in software engineering that originated from Microsoft. It is a derivative of the traditional MVC with the difference that the Controller layer is replaced with a layer which is a combination of both Model and View.  This type of architecture is super popular and perhaps tailor made when it comes to mobile application building. The main idea behind this is to separate business logic from its view (user interface). This enables designers and programming to work on a solution without conflict. Information is bound to views but no calculations or logic is found in the views. Making it cleaner and much easier to maintain. Here the model is dragged down to represent only the presentation level data that can be displayed. This is very helpful with the interactivity and the features of the application increasing each day dynamically. Some of the framework that support MVVM are  : Angular JS , Rails for Ruby,Xamarin, Silverlight,etc

Advantages of MVC :

  1. The MVC pattern is simple and makes it easier to test applications and manage their complexity by dividing the applications into the model, the view and the controller.
  2. The MVC framework is ideal for developers who want full control over the behaviour of an application, as it does not use view state or server-based forms.
  3. Due to the fact that it does not have support for view state, there will not be any automatic state management, reducing the page size, which allows for better performance.

Advantages of MVVM :

  1. Here the model does not know anything about the view or any other parts of the program as its interaction is limited to view model layer. The view is dumbed down and has no role except to present data and its interaction is limited to the view model layer.

1.This pattern is pretty good because you can test your view models.

  1. Developers can create unit tests for the view model and the model without using the view and the unit tests can exercise exactly the same functionality as used by the view.
  2. The MVVM pattern provides two-way communication between the pattern parts, whereas MVC is able only to provide one-way communication.

4.That testability from MVC would have 30%, with MVVM you could get to 70% and you could have UI tests for the rest.

Some other Names:

Viper: This architecture are basically targeted towards the mobile platform. The word VIPER is a backronym for View, Interactor, Presenter, Entity, and Routing. Clean Architecture divides an app’s logical structure into distinct layers of responsibility. This makes it easier to isolate dependencies (e.g. your database) and to test the interactions at the boundaries between layers:. It helps to target the problem of Massive View Controller problem in the iOS application where the view controller ends up doing a lot of stuffs. ensuring the VIPER architecture the developers can slimmer the chances of massive view controllers.

Main Parts of VIPER

         View: displays what it is told to by the Presenter and relays user input back to the Presenter.

                  Interactor: contains the business logic as specified by a use case.

                  Presenter: contains view logic for preparing content for display (as received from the Interactor) and for reacting to user inputs (by requesting new data from the Interactor).

Entity:- It contains basic model objects used by the Interactor.

                  Routing: contains navigation logic for describing which screens are shown in which order.

Conclusion:

The choice of the architecture is totally dependent on the developer but a good analysis of the project especially its requirements is essential. We will cover more topics related to the project architecture and performance enrichments of applications. Till then keep following our blog at Frugalis Minds

 

Related Posts :-

Spring Boot Profiling – Configure for Different Environments

Custom ClassLoaders In Java

Java Class Loaders and Internal Working

Spring Boot Profiling – Configure for Different Environments

Spring Boot Profiling – Configure for Different Environments :-

Spring Boot Profiling provides a way to segregate parts of your application configuration and make it only available in the certain environment.It is one of those concepts which we don’t use if we are working in development or just for learning purpose. Spring Boot Profiling is needed for applications which need’s to load different configurations for different environments Such as QA, DEV OR PROD.

In this Post, we will see how we use different database Url for different environments and let spring boot load the Url based on environment specified or profiling mentioned.



In order to demonstrate Spring Boot Profiling, we will create two different property files for prod and QA environments. I am using PostgreSQL for dev environment and MySQL for prod environment. Let us Check the Project structure below.

Project Structure:-

spring boot profiles

Let’s check property files for different environments, we are using different property files for different config in our application.Let’s configure database URL for those property files.




application.properties

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3308/profiling
spring.datasource.username=root
spring.datasource.password=root

spring.profiles.active=prod

This is the default properties for Spring Boot. You can see it has a property spring.profiles.active as a prod, this means that spring boot will look for the default property as application-prod.properties.The configuration written in the application-prod.properties is loaded by default if we don’t specify any profile while running my spring boot application.We need these types of configuration while creating any application .Let’s check this application here  Where we can use profiling .




We can also specify active profiles inapplication.properties and replace them using the command line switch.We can also specify multiple active profiles, for example:- spring.profiles.active=dev, prod in our properties file.

application-prod.properties

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/app2
spring.datasource.username=root
spring.datasource.password=root

application-dev.properties

spring.jpa.hibernate.ddl-auto=create

spring.datasource.url=jdbc:postgresql://localhost:5432/appointment
spring.datasource.username=postgres
spring.datasource.password=root
spring.datasource.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.driver.classname=org.postgresql.Driver

DemoApplication.java:-

package com.profiling.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

	@Value(value = "${spring.datasource.url}")
	String dbName;
	
	@Override
	public void run(String... arg0) throws Exception {
		// TODO Auto-generated method stub
		
		
		System.out.println("******************"+dbName+"************************");
	}
}

Here we are printing out the database URL which is getting loaded in Spring Boot Profiling.

Running the Application:-

Navigate to the Project directory and run mvn clean install .

Now type this command mvn spring-boot: run, once you run this maven command you will see something like this below:-

spring profiling

You can see our prod database Url is now loaded by default. Now let’s assume I am in development machine and want to run development database config, so I need to run my application in development mode. Please run following command line switch to switch to your dev profile.

spring boot profiling

output:-

Here the Postgresql database url must be loaded if everything is correct.

spring boot profiling

This is how we do profiling in a real-world application, spring also provides the Programmatic way of doing profiling. Please check out this link to find about Programmatic Way of Spring Boot Profiling.

Check this Book below to Learn More Basics Of Spring Boot .

It’s Suggested to do and apply configurations to deployment .

Related Links:-

Creating REST Service with Spring Boot

Spring MVC Basic Setup and Hello World
Custom ClassLoaders In Java
Overload Or Override Static Methods in Java

Custom ClassLoaders In Java

We are going to Write our Own Custom ClassLoaders in Java, but before we start on this topic.Let’s take a while to understand Why do We need Custom ClassLoaders?

We are going to check Simple Architecture of Class loaders In Java .

Why Custom ClassLoaders:-

As you know from my previous post JVM has its own ClassLoaders, but this classloader’s loads files from a local file system or a hard drive location. Here are Some of the Use Cases Where we need ClassLoader’s

  1. What if, Some of the Classes in your application is getting used for a finite period of time. How do we do Unloading of classes after a finite period of time? .This way it helps us for better memory management.
  2. Load classes from anywhere Classes can be loaded from anywhere, for example, Database, Networks, or even define it on the fly.

Steps Writing Custom ClassLoaders:-

  1. you need to extend your Custom ClassLoader from java.lang.ClassLoader.
  2. Override the loadClass() method of ClassLoader, this method is responsible for loading our class.
  3. If the Class is already loaded it returns that class
  4. If the class that is requested to load is not present it delegates to parent class loader.
  5. If Parent class loader is not able load the class, then loadClass() calls  findClass()  to find and load class
  6. The class to be loaded must have a public constructor with no arguments.

Custom ClassLoader Example:-

1.Project Structure :-

2. Create a Simple Class:- We create a simple class Frugalis.java, this is the class we load here using our custom ClassLoader.

Frugalis.Java

package test.frugalis;

public class Frugalis {

	public void printMyName(){
		System.out.println("Welcome Frugalis Minds");
	}
}

3. Custom ClassLoader :- We create Our custom ClassLoader which extends ClassLoader and override loadClass() .

package test.main;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {

	public MyClassLoader(ClassLoader parent) {
		super(parent);
	}

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		System.out.println("Class Loading Started for " + name);
		if (name.startsWith("test")) {
			return getClass(name);
		}
		return super.loadClass(name);
	}

	/**
	 * Loading of class from .class file
	 * happens here You Can modify logic of
	 * this method to load Class 
	 * from Network or any other source
	 * @param name
	 * @return
	 * @throws ClassNotFoundException
	 */
	private Class<?> getClass(String name) throws ClassNotFoundException {
		System.out.println("*********Inside getClass*********");

		String file = name.replace('.', File.separatorChar) + ".class";
		System.out.println("Name of File" + file);
		byte[] byteArr = null;
		try {
			// This loads the byte code data from the file
			byteArr = loadClassData(file);
			System.out.println("Size of byte array "+byteArr.length);
			Class<?> c = defineClass(name, byteArr, 0, byteArr.length);
			resolveClass(c);
			return c;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Loads a given file and converts
	 * it into a Byte Array
	 * @param name
	 * @return
	 * @throws IOException
	 */
	private byte[] loadClassData(String name) throws IOException {

		System.out.println("<<<<<<<<<Inside loadClassData>>>>>>");

		InputStream stream = getClass().getClassLoader().getResourceAsStream(
				name);
		int size = stream.available();
		byte buff[] = new byte[size];
		DataInputStream in = new DataInputStream(stream);
		// Reading the binary data
		in.readFully(buff);
		in.close();
		return buff;
	}

}

4. Running the Example:-

We create a Test.java and create an instance of our MyclassLoader, we load a binary class named as test.frugalis.Frugalis and invoke a method printMyName .

Test.java

package test.main;

import java.lang.reflect.InvocationTargetException;

public class Test {

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, Exception {

		MyClassLoader loader = new MyClassLoader(
	            Test.class.getClassLoader());
		
		System.out.println("loader name---- " +loader.getParent().getClass().getName());
		
		//This Loads the Class we must always
		//provide binary name of the class
		Class<?> clazz =
	            loader.loadClass("test.frugalis.Frugalis");
		
        System.out.println("Loaded class name: " + clazz.getName());

        //Create instance Of the Class and invoke the particular method
        Object instance = clazz.newInstance();
        
        clazz.getMethod("printMyName").invoke(instance);
	}
}

Output:-

loader name---- sun.misc.Launcher$AppClassLoader
Class Loading Started for test.frugalis.Frugalis
*********Inside getClass*********
Name of Filetest\frugalis\Frugalis.class
<<<<<<<<<Inside loadClassData>>>>>>
Size of byte array 519
Class Loading Started for java.lang.Object
Loaded class name: test.frugalis.Frugalis
Class Loading Started for java.lang.System
Class Loading Started for java.io.PrintStream
Welcome Frugalis Minds

5. Download Code :-  

This was an example of simple example of Custom ClassLoader. Please add your comments and suggestions .

Related Posts-

  1. Whats are  ClassLoaders and internal working ?