MVC and MVCS : Software Engineering

MVC and MVCS : Software Engineering

In previous article Architectural vs Design Patterns: Software Engineering we discussed in detail about what architectural and design patterns are and how they are different from each other. In this article we are going to discuss legendary and famous MVC and its extension MVCS architectural patterns.

MVC stands for Model View Controller

MVCS stands for Model View Controller Service

Model: This layer is responsible for storing and retrieving application data. Data Access Objects and Data Access Layer resides in Model layer of application. This layer has nothing to do with business logic or representation of data to the user. It only cares about how to store data and how to retrieve it when needed.

You can think of Model as a store keeper. You just go to store keeper, hand him a box and say please keep it save. Now you don't care how he saved it, he might have a cabin under his shelf or may be a secure locker, it his job to store it and keep it save. Now second day you go to store keeper and ask for box. He will give you your box. You have no idea how box was saved or how it is retrieved. It is store keeper's responsibility not your's. What is the purpose of box? Its your responsibility, not store keeper's.

View: This layer is responsible for interaction with user. This is front end of application that might have different fields for data entry, tables for representation of information, animations etc. This layer has nothing to do what is the purpose of given data, It just receive data, validate it according to system policies and if every thing is fine then data is passed to next layer. Note that this layer validates policies like if user name has no digit in it and have no illegal characters and have specified length, It does not validate according to rules like if user has already exist or banned form registration, this is job of next layer not view layer. View just validate according to policies and pass data to next layer and display result according to whatever response it receives.

Think of View as a sales person. Once you are willing to buy, sales person hands you over to the cashier.

Controller: This is the core of application and all business rules resides in this layer. All calculations performed in this layer. All important decisions taken in this layer. All business objects lives and manipulates in this layer. This layer receives data from view, validates it against business rules, manipulates it, generate results and give it to view if required. It uses model layer for storing and retrieving data. All core functionality resides in this layer.

Think of Controller as a production manager.

Service: This is another (optional) layer that resides in between model and controller in large scale systems. The purpose is to keep your controllers nice and clean. All business tasks are performed by intended services and controllers just use different services to produce intended results. Note that services don't call each other directly but a controller takes data from one service and give it to other. Controller controls services and services know how to do their job thus they provide an abstraction to the controller.

Think of Service as In-charge of some task to be done.

So, that was a brief discussion about MVCS (Model View Controller Service). There is no major difference between MVC and MVCS just MVCS is a bit cleaner than MVC. So I prefer it in most cases.

When designing your system, make sure it is highly decoupled. The Model and View should be 'plug and play'. You don't like a database? Changing it should have no effect on rest of your application. Your controllers should not know either they are used for web or simple desktop base front end. Similarly Services and controllers should also decoupled. Change in anything require minimum of change in rest of your application. You can use dependency Injection (providing dependencies at run time) to achieve this. It is a bit tricky but a life saving practice.

MVCS Demo Application

Now lets create a simple java application demonstrating MVCS. Our application ask for name and save it and display all names entered by user. Create a basic java based application. Application's package hierarchy would be:

First Create Controller Interface:

public interface NameController {
	boolean save(String name);
	List<String> findAllNames();
}

Now to implement controller methods, we need a service that can be used to save and retrieve names. The service Interface would be:

public interface NameService {
	public boolean save(String name);
	public List<String> findAllNames();
}

The service implementation would be:

public class NameServiceImpl implements NameService{

	
	private NamePersistence namePersistence;
	
	public NameServiceImpl(NamePersistence namePersistence){
		this.namePersistence = namePersistence;
	}
	
	@Override
	public boolean save(String name) {
		return namePersistence.save(name);
	}

	@Override
	public List<String> findAllNames() {
		return namePersistence.findAllNames();
	}
	
	
	/*
	 * This interface will served as data access layer for this service
	 * In this way we can make sure our service doesn't depend upon 
     * ?under laying model since any under laying model implementing this
     *? interface can be used as data access layer 
	 */
	public interface NamePersistence{
		boolean save(String name);
		List<String> findAllNames();
	}

}

You can see NamePersistence is injected in this service. This would allow decoupled data access layer.

Now the controller implementation would be:

public class NameControllerImpl implements NameController{
	
	private NameService nameService;
	
	public NameControllerImpl(NameService nameService){
		this.nameService = nameService;
	}

	@Override
	public boolean save(String name) {
		return nameService.save(name);
	}

	@Override
	public List<String> findAllNames() {
		return nameService.findAllNames();
	}

}

This is all for our core application. You can see NameService is injected to our controller and any view can use our controller interface and use our application. On the other hand controller has no idea about view. Similarly any model implementing 'NamePersistence' interface can be used and controller has no idea weather data is coming from some database or some file or memory.

Now our Model would be:

public class DataAccessLayer implements NamePersistence {

	private List<String> storedNames = new ArrayList<>();
	
	@Override
	public boolean save(String name) {
		int countBeforeInsertion = storedNames.size();
		storedNames.add(name);
		int countAfterInsertion = storedNames.size();
		if(countAfterInsertion > countBeforeInsertion){
			return true;
		}
		return false;
	}


	@Override
	public List<String> findAllNames() {
		return storedNames;
	}
	
}

And our View would Be:

public class NameView {

	NameController nameController;

	public NameView(NameController nameController) {
		this.nameController = nameController;
	}

	public void prompt() {
		Scanner scanner = new Scanner(System.in);
		while (true) {
			System.out.print("Enter name (quit for quit): ");
			String name = scanner.nextLine();
			if(!Validator.isValid(name)){
				System.out.println("Invalid name! \n\n\n\n\n");
				continue;
			}

			if (name.equalsIgnoreCase("quit")) {
				System.out.println("*********-:End:-**********");
				break;
			}
			
			nameController.save(name);
			
			
			System.out.println("********** -:Names:- **********");
			for (String nameInList : nameController.findAllNames()) {
				System.out.println(nameInList);
			}
			
			System.out.print("\n\n\n\n\n");
		}
		scanner.close();
	}
}

You can see our controller is injected to this view, you can create another view, inject controller and can replace this view entirely without effecting any other thing in program.

Finally our Application class is used to bootstrap our application and run:

public class Application {
	
	
	public static void main(String[] args){
		initApp();
	}
	
	
	private static void initApp(){
		NamePersistence namePersistence = new DataAccessLayer();
		NameService nameService = new NameServiceImpl(namePersistence);
		NameController nameController = new NameControllerImpl(nameService);
		NameView view = new NameView(nameController);
		view.prompt();
	}

}

This was our discussion about MVC and MVCS.

Click here to download Sample Project

If you have any question, suggestion or feedback please feel free to mention in comment section. If you like this article please share it with your friends too. I would love to have your feed back.

Happy coding !!

Lavanya Manivannan

Senior Manager - Software Engineering at Walmart Global Tech

6 年

Excellent documentation

回复
Muhammad Sulman

PSE @ NXB | PHP | JS | React | Laravel

8 年

very nice keep it up

回复

要查看或添加评论,请登录

Muhammad Asher Toqeer的更多文章

  • Modern Java as Data-Oriented Language

    Modern Java as Data-Oriented Language

    Java, at its core, is an Object Oriented Language. But, Object Oriented Programming alone can't solve all of the…

  • Spring Framework Brief Overview

    Spring Framework Brief Overview

    History Spring is a framework for Java Enterprise Application Development. It started in 2003, at that time Java offers…

  • Java Modules Introduction

    Java Modules Introduction

    Classes are the basic unit of a program in Java. Packages are used to manage classes and modulesare used to manage…

  • Handling Mistakes as a Developer

    Handling Mistakes as a Developer

    This article is based on "A Pragmatic Philosophy" from the book: "The Pragmatic Programmer". Mistakes are Inevitable.

  • Java 8 Functional Programming Simplified

    Java 8 Functional Programming Simplified

    This article will explain Java 8 functional programming related concepts, i.e Lambda expressions, Functional…

  • 3 Years being a Software Engineer, Here are some things I have learned

    3 Years being a Software Engineer, Here are some things I have learned

    Life is a journey, so as your carrier and like every other journey, your carrier teaches you a lot of things. Here are…

    2 条评论
  • Architectural vs Design Patterns: Software Engineering

    Architectural vs Design Patterns: Software Engineering

    Software design patterns are some proven ways to solve a reoccurring problem faced by programmers. These are general…

    2 条评论
  • Variable Names, Some tips

    Variable Names, Some tips

    Variables can be your best friend, or your worst enemy and that depends on You. If you are not careful and just…

    2 条评论
  • Meaningful Class Names

    Meaningful Class Names

    This article is about naming classes, mainly it is about "how to meaningfully name your classes" remember in…

    3 条评论
  • Function Names, do it right

    Function Names, do it right

    In programming, naming identifiers (class, method, variable names) is one of the most crucial part of writing code. If…

    7 条评论

社区洞察

其他会员也浏览了