Search Results

Search found 877 results on 36 pages for 'loose coupling'.

Page 1/36 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How does dependecy injection increase coupling?

    - by B?????
    On the Wikipedia page on dependency injection, the disadvantages section tells us this: Dependency injection increases coupling by requiring the user of a subsystem to provide for the needs of that subsystem. with a link to an article against dependency injection. Dependency injection makes a class use the interface instead of the concrete implementation. That should result in decreased coupling, no? What am I missing? How is dependency injection increasing coupling between classes?

    Read the article

  • How dependecy injection increases coupling?

    - by B?????
    Reading wiki page on Dependency injection, the disadvantages section tells this : Dependency injection increases coupling by requiring the user of a subsystem to provide for the needs of that subsystem. with a link to an article against DI. What DI does is that it makes a class use the interface instead of the concrete implementation. That should be decreased coupling, no? So, what am I missing? How is dependency injection increasing coupling between classes?

    Read the article

  • Low coupling processing big quantities of data

    - by vitalik
    Usually I achieve low coupling by creating classes that exchange lists, sets, and maps between them. Now I am developing a batch application and I can't put all the data inside a data structure because there isn't enough memory. I have to read and process one chunk of data and then going to the next one. So having low coupling is much more difficult because I have to check somewhere if there is still data to read, etc. What I am using now is: Source - Process - Persist The classes that process have to ask to the Source classes if there are more rows to read. What are the best practices and or useful patterns in such situations? I hope I am explaining myself, if not tell me.

    Read the article

  • Loose Coupling in Object Oriented Design

    - by m3th0dman
    I am trying to learn GRASP and I found this explained (here on page 3) about Low Coupling and I was very surprised when I found this: Consider the method addTrack for an Album class, two possible methods are: addTrack( Track t ) and addTrack( int no, String title, double duration ) Which method reduces coupling? The second one does, since the class using the Album class does not have to know a Track class. In general, parameters to methods should use base types (int, char ...) and classes from the java.* packages. I tend to diasgree with this; I believe addTrack(Track t) is better than addTrack(int no, String title, double duration) due to various reasons: It is always better for a method to as fewer parameters as possible (according to Uncle Bob's Clean Code none or one preferably, 2 in some cases and 3 in special cases; more than 3 needs refactoring - these are of course recommendations not holly rules). If addTrack is a method of an interface, and the requirements need that a Track should have more information (say year or genre) then the interface needs to be changed and so that the method should supports another parameter. Encapsulation is broke; if addTrack is in an interface, then it should not know the internals of the Track. It is actually more coupled in the second way, with many parameters. Suppose the no parameter needs to be changed from int to long because there are more than MAX_INT tracks (or for whatever reason); then both the Track and the method need to be changed while if the method would be addTrack(Track track) only the Track would be changed. All the 4 arguments are actually connected with each other, and some of them are consequences from others. Which approach is better?

    Read the article

  • Is this high coupling?

    - by Bono
    Question I'm currently working a on an assignment for school. The assignment is to create a puzzle/calculator program in which you learn how to work with different datastructures (such as Stacks). We have generate infix math strings suchs as "1 + 2 * 3 - 4" and then turn them in to postfix math strings such as "1 2 + 3 * 4 -". In my book the author creates a special class for converting the infix notation to postfix. I was planning on using this but whilst I was about to implement it I was wondering if the following is what you would call "high coupling". I have read something about this (nothing that is taught in the book or anything) and was wondering about the aspect (since I still have to grasp it). Problem I have created a PuzzleGenerator class which generates the infix notation of the puzzle (or math string, whatever you want to call it) when it's instantiated. I was going to make a method getAnswer() in which I would instantiate the InToPost class (the class from the book) to convert the infix to postfox notation and then calculate the answer. But whilst doing this I thought: "Is using the InToPost class inside this method a form a high coupling, and would it be better to place this in a different method?" (such as a "convertPostfixToInfix" method, inside the PuzzleGenerator class) Thanks in advance.

    Read the article

  • Service layer coupling

    - by Justin
    I am working on writing a service layer for an order system in php. It's the typical scenario, you have an Order that can have multiple Line Items. So lets say a request is received to store a line item with pictures and comments. I might receive a json request such as { 'type': 'Bike', 'color': 'Red', 'commentIds': [3193,3194] 'attachmentIds': [123,413] } My idea was to have a Service_LineItem_Bike class that knows how to take the json data and store an entity for a bike. My question is, the Service_LineItem class now needs to fetch comments and file attachments, and store the relationships. Service_LineItem seems like it should interact with a Service_Comment and a Service_FileUpload. Should instances of these two other services be instantiated and passed to the Service_LineItem constructor,or set by getters and setters? Dependency injection seems like the right solution, allowing a service access to a 'service fetching helper' seems wrong, and this should stay at the application level. I am using Doctrine 2 as a ORM, and I can technically write a dql query inside Service_LineItem to fetch the comments and file uploads necessary for the association, but this seems like it would have a tighter coupling, rather then leaving this up to the right service object.

    Read the article

  • Loose Coupling and UX Patterns for Applications Integrations

    - by ultan o'broin
    I love that software architecture phrase loose coupling. There’s even a whole book about it. And, if you’re involved in enterprise methodology you’ll know just know important loose coupling is to the smart development of applications integrations too. Whether you are integrating offerings from the Oracle partner ecosystem with Fusion apps or applications coexistence scenarios, loose coupling enables the development of scalable, reliable, flexible solutions, with no second-guessing of technology. Another great book Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions tells us about loose coupling benefits of reducing the assumptions that integration parties (components, applications, services, programs, users) make about each other when they exchange information. Eliminating assumptions applies to UI development too. The days of assuming it’s enough to hard code a UI with linking libraries called code on a desktop PC for an office worker are over. The book predates PaaS development and SaaS deployments, and was written when web services and APIs were emerging. Yet it calls out how using middleware as an assumptions-dissolving technology “glue" is central to applications integration. Realizing integration design through a set of middleware messaging patterns (messaging in the sense of asynchronously communicating data) that enable developers to meet the typical business requirements of enterprises requiring integrated functionality is very Fusion-like. User experience developers can benefit from the loose coupling approach too. User expectations and work styles change all the time, and development is now about integrating SaaS through PaaS. Cloud computing offers a virtual pivot where a single source of truth (customer or employee data, for example) can be experienced through different UIs (desktop, simplified, or mobile), each optimized for the context of the user’s world of work and task completion. Smart enterprise applications developers, partners, and customers use design patterns for user experience integration benefits too. The Oracle Applications UX design patterns (and supporting guidelines) enable loose coupling of the optimized UI requirements from code. Developers can get on with the job of creating integrations through web services, APIs and SOA without having to figure out design problems about how UIs should work. Adding the already user proven UX design patterns (and supporting guidelines to your toolkit means ADF and other developers can easily offer much more than just functionality and be super productive too. Great looking application integration touchpoints can be built with our design patterns and guidelines too for a seamless applications UX. One of Oracle’s partners, Innowave Technologies used loose coupling architecture and our UX design patterns to create an integration for a customer that was scalable, cost effective, fast to develop and kept users productive while paving a roadmap for customers to keep pace with the latest UX designs over time. Innowave CEO Basheer Khan, a Fusion User Experience Advocate explains how to do it on the Usable Apps blog.

    Read the article

  • Coupling between controller and view

    - by cheez
    The litmus test for me for a good MVC implementation is how easy it is to swap out the view. I've always done this really badly due to being lazy but now I want to do it right. This is in C++ but it should apply equally to non-desktop applications, if I am to believe the hype. Here is one example: the application controller has to check some URL for existence in the background. It may connect to the "URL available" event (using Boost Signals) as follows: BackgroundUrlCheckerThread(Controller & controller) { // ... signalUrlAvailable.connect( boost::bind(&Controller::urlAvailable,&controller,_1)) } So what does Controller::urlAvailable look like? Here is one possibility: void Controller::urlAvailable(Url url) { if(!view->askUser("URL available, wanna download it?")) return; else // Download the url in a new thread, repeat } This, to me, seems like a gross coupling of the view and the controller. Such a coupling makes it impossible to implement the view when using the web (coroutines aside.) Another possibility: void Controller::urlAvailable(Url url) { urlAvailableSignal(url); // Now, any view interested can do what it wants } I'm partial to the latter but it appears that if I do this there will be: 40 billion such signals. The application controller can get huge for a non-trivial application A very real possibility that a given view accidentally ignores some signals (APIs can inform you at link-time, but signals/slots are run-time) Thanks in advance.

    Read the article

  • How to avoid coupling when using regions in Composite WPF

    - by emddudley
    I have an application designed using Microsoft's Composite Application Library. My shell has several regions defined so that I can inject content from separate modules. I'm looking for a design pattern that will reduce the coupling that these regions introduce. In all examples I have seen, regions are defined and accessed using a string in a static class in the infrastructure project.: <ItemsControl cal:RegionManager.RegionName="{x:Static inf:RegionNames.TabRegion}"> public static class RegionNames { public const string TabRegion = "TabRegion"; } This introduces an dependency on the shell from the infrastructure project, because the infrastructure project is now defining some of the shell's capabilities. The CAL RegionManager throws an exception if you attempt to access a region which is not defined, so I must ensure that the infrastructure and shell projects are kept in sync. Is there a way to isolate the shell's regions so that they are defined only within the shell (no region names in the infrastructure project)? Is there a way to make regions optional, so that shells can be swapped out even if they don't have all the same regions? (An example: One shell has menu and toolbar regions, another only has the menu... modules should be able to inject into the toolbar if it's available, without failing when it's not)

    Read the article

  • Coupling/Cohesion

    - by user559142
    Hi All, Whilst there are many good examples on this forum that contain examples of coupling and cohesion, I am struggling to apply it to my code fully. I can identify parts in my code that may need changing. Would any Java experts be able to take a look at my code and explain to me what aspects are good and bad. I don't mind changing it myself at all. It's just that many people seem to disagree with each other and I'm finding it hard to actually understand what principles to follow... package familytree; /** * * @author David */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here KeyboardInput in = new KeyboardInput(); FamilyTree familyTree = new FamilyTree(in, System.out); familyTree.start(); } } package familytree; import java.io.PrintStream; /** * * @author David */ public class FamilyTree { /** * @param args the command line arguments */ private static final int DISPLAY_FAMILY_MEMBERS = 1; private static final int ADD_FAMILY_MEMBER = 2; private static final int REMOVE_FAMILY_MEMBER = 3; private static final int EDIT_FAMILY_MEMBER = 4; private static final int SAVE_FAMILY_TREE = 5; private static final int LOAD_FAMILY_TREE = 6; private static final int DISPLAY_ANCESTORS = 7; private static final int DISPLAY_DESCENDANTS = 8; private static final int QUIT = 9; private KeyboardInput in; private Family family; private PrintStream out; public FamilyTree(KeyboardInput in, PrintStream out) { this.in = in; this.out = out; family = new Family(); } public void start() { out.println("\nWelcome to the Family Tree Builder"); //enterUserDetails(); initialise(); while (true) { displayFamilyTreeMenu(); out.print("\nEnter Choice: "); int option = in.readInteger(); if (option > 0 && option <= 8) { if (quit(option)) { break; } executeOption(option); } else { out.println("Invalid Choice!"); } } } //good private void displayFamilyTreeMenu() { out.println("\nFamily Tree Menu"); out.println(DISPLAY_FAMILY_MEMBERS + ". Display Family Members"); out.println(ADD_FAMILY_MEMBER + ". Add Family Member"); out.println(REMOVE_FAMILY_MEMBER + ". Remove Family Member"); out.println(EDIT_FAMILY_MEMBER + ". Edit Family Member"); out.println(SAVE_FAMILY_TREE + ". Save Family Tree"); out.println(LOAD_FAMILY_TREE + ". Load Family Tree"); out.println(DISPLAY_ANCESTORS + ". Display Ancestors"); out.println(DISPLAY_DESCENDANTS + ". Display Descendants"); out.println(QUIT + ". Quit"); } //good private boolean quit(int opt) { return (opt == QUIT) ? true : false; } //good private void executeOption(int choice) { switch (choice) { case DISPLAY_FAMILY_MEMBERS: displayFamilyMembers(); break; case ADD_FAMILY_MEMBER: addFamilyMember(); break; case REMOVE_FAMILY_MEMBER: break; case EDIT_FAMILY_MEMBER: break; case SAVE_FAMILY_TREE: break; case LOAD_FAMILY_TREE: break; case DISPLAY_ANCESTORS: displayAncestors(); break; case DISPLAY_DESCENDANTS: displayDescendants(); break; default: out.println("Not a valid option! Try again."); break; } } //for selecting family member for editing adding nodes etc private void displayFamilyMembers() { out.println("\nDisplay Family Members"); int count = 0; for (FamilyMember member : family.getFamilyMembers()) { out.println(); if (count + 1 < 10) { out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName()); out.println(" " + member.getDob()); out.println(" Generation: " + member.getGeneration()); } else { out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName()); out.println(" " + member.getDob()); out.println(" Generation: " + member.getGeneration()); } count++; } } private int selectRelative() { out.println("\nSelect Relative"); out.println("1. Add Parents"); out.println("2. Add Child"); out.println("3. Add Partner"); out.println("4. Add Sibling"); out.print("\nEnter Choice: "); int choice = in.readInteger(); if (choice > 0 && choice < 5) { return choice; } return (-1); } private void addFamilyMember() { int memberIndex = selectMember(); if (memberIndex >= 0) { FamilyMember member = family.getFamilyMember(memberIndex); int relative = selectRelative(); if (relative > 0) { out.println("\nAdd Member"); //if choice is valid switch (relative) { case 1: //adding parents if (member.getFather() == null) { FamilyMember mum, dad; out.println("Enter Mothers Details"); mum = addMember(relative, "Female"); out.println("\nEnter Fathers Details"); dad = addMember(relative, "Male"); member.linkParent(mum); member.linkParent(dad); mum.linkPartner(dad); mum.setGeneration(member.getGeneration() - 1); dad.setGeneration(member.getGeneration() - 1); sortGenerations(); } else { out.println(member.getFirstName() + " " + member.getLastName() + " already has parents."); } break; case 2: //adding child if (member.getPartner() == null) { FamilyMember partner; if (member.getGender().equals("Male")) { out.println("Enter Mothers Details"); partner = addMember(1, "Female"); } else { out.println("Enter Fathers Details"); partner = addMember(1, "Male"); } //create partner member.linkPartner(partner); partner.setGeneration(member.getGeneration()); out.println(); } out.println("Enter Childs Details"); FamilyMember child = addMember(relative, ""); child.linkParent(member); child.linkParent(member.getPartner()); child.setGeneration(member.getGeneration() + 1); sortGenerations(); break; case 3: //adding partner if (member.getPartner() == null) { out.println("Enter Partners Details"); FamilyMember partner = addMember(relative, ""); member.linkPartner(partner); partner.setGeneration(member.getGeneration()); } else { out.println(member.getFirstName() + " " + member.getLastName() + " already has a partner."); } break; case 4: //adding sibling FamilyMember mum, dad; if (member.getFather() == null) { out.println("Enter Mothers Details"); mum = addMember(1, "Female"); out.println("\nEnter Fathers Details"); dad = addMember(1, "Male"); member.linkParent(mum); member.linkParent(dad); mum.linkPartner(dad); mum.setGeneration(member.getGeneration() - 1); dad.setGeneration(member.getGeneration() - 1); sortGenerations(); out.println("\nEnter Siblings Details"); } else { out.println("Enter Siblings Details"); } FamilyMember sibling = addMember(relative, ""); //create mum and dad mum = member.getMother(); dad = member.getFather(); sibling.linkParent(mum); sibling.linkParent(dad); sibling.setGeneration(member.getGeneration()); break; } } else { out.println("Invalid Option!"); } } else { out.println("Invalid Option!"); } } private int selectMember() { displayFamilyMembers(); out.print("\nSelect Member: "); int choice = in.readInteger(); if (choice > 0 && choice <= family.getFamilyMembers().size()) { return (choice - 1); } return -1; } private FamilyMember addMember(int option, String gender) { out.print("Enter First Name: "); String fName = formatString(in.readString().trim()); out.print("Enter Last Name: "); String lName = formatString(in.readString().trim()); if (option != 1) { //if not adding parents out.println("Select Gender"); out.println("1. Male"); out.println("2. Female"); out.print("Enter Choice: "); int gOpt = in.readInteger(); if (gOpt == 1) { gender = "Male"; } else if (gOpt == 2) { gender = "Female"; } else { out.println("Invalid Choice"); return null; } } String dob = enterDateOfBirth(); lName = formatString(lName); FamilyMember f = family.getFamilyMember(family.addMember(fName, lName, gender, dob)); f.setIndex(family.getFamilyMembers().size() - 1); return (f); } private String formatString(String s){ String firstLetter = s.substring(0, 1); String remainingLetters = s.substring(1, s.length()); s = firstLetter.toUpperCase() + remainingLetters.toLowerCase(); return s; } private String enterDateOfBirth(){ out.print("Enter Year Of Birth (0 - 2011): "); String y = in.readString(); out.print("Enter Month Of Birth (1-12): "); String m = in.readString(); if (Integer.parseInt(m) < 10) { m = "0" + m; } m += "-"; out.print("Enter Date of Birth (1-31): "); String d = in.readString(); if (Integer.parseInt(d) < 10) { d = "0" + d; } d += "-"; String dob = d + m + y; while(!DateValidator.isValid(dob)){ out.println("Invalid Date. Try Again:"); dob = enterDateOfBirth(); } return (dob); } private void displayAncestors() { out.print("\nDisplay Ancestors For Which Member: "); int choice = selectMember(); if (choice >= 0) { FamilyMember node = family.getFamilyMember(choice ); FamilyMember ms = findRootNode(node, 0, 2, -1); FamilyMember fs = findRootNode(node, 1, 2, -1); out.println("\nPrint Ancestors"); out.println("\nMothers Side"); printDescendants(ms, node, ms.getGeneration()); out.println("\nFathers Side"); printDescendants(fs, node, fs.getGeneration()); } else { out.println("Invalid Option!"); } } private void displayDescendants() { out.print("\nDisplay Descendants For Which Member: "); int choice = selectMember(); if (choice >= 0) { FamilyMember node = family.getFamilyMember(choice); out.println("\nPrint Descendants"); printDescendants(node, null, 0); } else { out.println("Invalid Option!"); } } private FamilyMember findRootNode(FamilyMember node, int parent, int numGenerations, int count) { FamilyMember root; count++; if (node.hasParents() && count < numGenerations) { if (parent == 0) { node = node.getMother(); root = findRootNode(node, 1, numGenerations, count); } else { node = node.getFather(); root = findRootNode(node, 1, numGenerations, count); } return root; } return node; } private int findHighestLeafGeneration(FamilyMember node) { int gen = node.getGeneration(); for (int i = 0; i < node.getChildren().size(); i++) { int highestChild = findHighestLeafGeneration(node.getChild(i)); if (highestChild > gen) { gen = highestChild; } } return gen; } private void printDescendants(FamilyMember root, FamilyMember node, int gen) { out.print((root.getGeneration() + 1) + " " + root.getFullName()); out.print(" [" + root.getDob() + "] "); if (root.getPartner() != null) { out.print("+Partner: " + root.getPartner().getFullName() + " [" + root.getPartner().getDob() + "] "); } if (root == node) { out.print("*"); } out.println(); if (!root.getChildren().isEmpty() && root != node) { for (int i = 0; i < root.getChildren().size(); i++) { for (int j = 0; j < root.getChild(i).getGeneration() - gen; j++) { out.print(" "); } printDescendants(root.getChild(i), node, gen); } } else { return; } } //retrieve highest generation public int getRootGeneration(){ int min = family.getFamilyMember(0).getGeneration(); for(int i = 0; i < family.getFamilyMembers().size(); i++){ min = Math.min(min, family.getFamilyMember(i).getGeneration()); } return Math.abs(min); } public void sortGenerations(){ int amount = getRootGeneration(); for (FamilyMember member : family.getFamilyMembers()) { member.setGeneration(member.getGeneration() + amount); } } //test method - temporary private void initialise() { family.addMember("Bilbo", "Baggins", "Male", "23-06-1920"); } } package familytree; import java.util.ArrayList; import java.util.Date; /** * * @author David */ public class Family { //family members private ArrayList<FamilyMember> family; //create Family public Family() { family = new ArrayList<FamilyMember>(); } //add member to the family public int addMember(String f, String l, String g, String d) { family.add(new FamilyMember(f, l, g, d)); return family.size()-1; } //remove member from family public void removeMember(int index) { family.remove(index); } public FamilyMember getFamilyMember(int index) { return family.get(index); } //return family public ArrayList <FamilyMember> getFamilyMembers() { return family; } public void changeFirstName(int index, String f) { family.get(index).setFirstName(f);//change to setfirstname and others } public void changeLastName(int index, String l) { family.get(index).setLastName(l); } public void changeAge(int index, int a) { family.get(index).setAge(a); } public void changeDOB() { //implement } } package familytree; import java.util.ArrayList; import java.util.Collections; /** * * @author David */ public class FamilyMember extends Person { private FamilyMember mother; private FamilyMember father; private FamilyMember partner; private ArrayList<FamilyMember> children; private int generation; private int index; //initialise family member public FamilyMember(String f, String l, String g, String d) { super(f, l, g, d); mother = null; father = null; partner = null; children = new ArrayList<FamilyMember>(); generation = 0; index = -1; } public void linkParent(FamilyMember parent) { if (parent.getGender().equals("Female")) { this.setMother(parent); } else { this.setFather(parent); } parent.addChild(this); } public void linkPartner(FamilyMember partner) { partner.setPartner(this); this.setPartner(partner); } public boolean hasParents() { if (this.getMother() == null && this.getFather() == null) { return false; } return true; } public FamilyMember getMother() { return mother; } public FamilyMember getFather() { return father; } public FamilyMember getPartner() { return partner; } public FamilyMember getChild(int index) { return children.get(index); } public int getGeneration() { return generation; } public int getIndex() { return index; } public ArrayList<FamilyMember> getChildren() { return children; } public void setMother(FamilyMember f) { mother = f; } public void setFather(FamilyMember f) { father = f; } public void setPartner(FamilyMember f) { partner = f; } public void addChild(FamilyMember f) { children.add(f); //add child if(children.size() > 1){ //sort in ascending order Collections.sort(children, new DateComparator()); } } public void addChildAt(FamilyMember f, int index) { children.set(index, f); } public void setGeneration(int g) { generation = g; } public void setIndex(int i){ index = i; } } package familytree; /** * * @author David */ public class Person{ private String fName; private String lName; private String gender; private int age; private String dob; public Person(String fName, String lName, String gender, String dob){ this.fName = fName; this.lName = lName; this.gender = gender; this.dob = dob; } public String getFullName(){ return (this.fName + " " + this.lName); } public String getFirstName(){ return (fName); } public String getLastName(){ return (lName); } public String getGender(){ return (gender); } public String getDob(){ return dob; } public int getAge(){ return age; } public void setFirstName(String fName){ this.fName = fName; } public void setLastName(String lName){ this.lName = lName; } public void setGender(String gender){ this.gender = gender; } public void setAge(int age){ this.age = age; } }

    Read the article

  • How to Implement Loose Coupling with a SOA Architecture

    - by Brian
    I've been doing a lot of research lately about SOA and ESB's etc. I'm working on redesigning some legacy systems at work now and would like to build it with more of a SOA architecture than it currently has. We use these services in about 5 of our websites and one of the biggest problems we have right now with our legacy system is that almost all the time when we make bug fixes or updates we need to re-deploy our 5 websites which can be a quite time consuming process. My goal is to make the interfaces between services loosely coupled so that changes can be made without having to re-deploy all the dependent services and websites. I need the ability to extend an already existing service interface without breaking or updating any of its dependencies. Have any of you encountered this problem before? How did you solve it?

    Read the article

  • Semantic coupling vs. large class

    - by user106587
    I have hardware I communicate with via TCP. This hardware accepts ~40 different commands/requests with about 20 different responses. I've created a HardwareProxy class which has a TcpClient to send and receive data. I didn't like the idea of having 40 different methods to send the commands/requests, so I started down the path of having a single SendCommand method which takes an ICommand and returns an IResponse, this results in 40 different SpecificCommand classes. The problem is this requires semantic coupling, i.e. the method that invokes SendCommand receives an IResponse which it has to downcast to SpecificResponse, I use a future map which I believe ensures the appropriate SpecificResponse, but I get the impression this code smells. Besides the semantic coupling, ICommand and IResponse are essentially empty abstract classes (Marker Interfaces) and this seems suspicious to me. If I go with the 40 methods I don't think I have broken the single responisbility principle as the responsibility of the HardwareProxy class is to act as the hardware, which has all of these commands. This route is just ugly, plus I'd like to have Asynchronous versions, so there'd be about 80 methods. Is it better to bite the bullet and have a large class, accept the coupling and MarkerInterfaces for a smaller soultuion, or am I missing a better way? Thanks.

    Read the article

  • Avoiding coupling

    - by Seralize
    It is also true that a system may become so coupled, where each class is dependent on other classes that depend on other classes, that it is no longer possible to make a change in one place without having a ripple effect and having to make subsequent changes in many places.[1] This is why using an interface or an abstract class can be valuable in any object-oriented software project. Quote from Wikipedia Starting from scratch I'm starting from scratch with a project that I recently finished because I found the code to be too tightly coupled and hard to refactor, even when using MVC. I will be using MVC on my new project aswell but want to try and avoid the pitfalls this time, hopefully with your help. Project summary My issue is that I really wish to keep the Controller as clean as possible, but it seems like I can't do this. The basic idea of the program is that the user picks wordlists which is sent to the game engine. It will pick random words from the lists until there are none left. Problem at hand My main problem is that the game will have 'modes', and need to check the input in different ways through a method called checkWord(), but exactly where to put this and how to abstract it properly is a challenge to me. I'm new to design patterns, so not sure whether there exist any might fit my problem. My own attempt at abstraction Here is what I've gotten so far after hours of 'refactoring' the design plans, and I know it's long, but it's the best I could do to try and give you an overview (Note: As this is the sketch, anything is subject to change, all help and advice is very welcome. Also note the marked coupling points): Wordlist class Wordlist { // Basic CRUD etc. here! // Other sample methods: public function wordlistCount($user_id) {} // Returns count of how many wordlists a user has public function getAll($user_id) {} // Returns all wordlists of a user } Word class Word { // Basic CRUD etc. here! // Other sample methods: public function wordCount($wordlist_id) {} // Returns count of words in a wordlist public function getAll($wordlist_id) {} // Returns all words from a wordlist public function getWordInfo($word_id) {} // Returns information about a word } Wordpicker class Wordpicker { // The class needs to know which words and wordlists to exclude protected $_used_words = array(); protected $_used_wordlists = array(); // Wordlists to pick words from protected $_wordlists = array(); /* Public Methods */ public function setWordlists($wordlists = array()) {} public function setUsedWords($used_words = array()) {} public function setUsedWordlists($used_wordlists = array()) {} public function getRandomWord() {} // COUPLING POINT! Will most likely need to communicate with both the Wordlist and Word classes /* Protected Methods */ protected function _checkAvailableWordlists() {} // COUPLING POINT! Might need to check if wordlists are deleted etc. protected function _checkAvailableWords() {} // COUPLING POINT! Method needs to get all words in a wordlist from the Word class } Game class Game { protected $_session_id; // The ID of a game session which gets stored in the database along with game details protected $_game_info = array(); // Game instantiation public function __construct($user_id) { if (! $this->_session_id = $this->_gameExists($user_id)) { // New game } else { // Resume game } } // This is the method I tried to make flexible by using abstract classes etc. // Does it even belong in this class at all? public function checkWord($answer, $native_word, $translation) {} // This method checks the answer against the native word / translation word, depending on game mode public function getGameInfo() {} // Returns information about a game session, or creates it if it does not exist public function deleteSession($session_id) {} // Deletes a game session from the database // Methods dealing with game session information protected function _gameExists($user_id) {} protected function _getProgress($session_id) {} protected function _updateProgress($game_info = array()) {} } The Game /* CONTROLLER */ /* "Guess the word" page */ // User input $game_type = $_POST['game_type']; // Chosen with radio buttons etc. $wordlists = $_POST['wordlists']; // Chosen with checkboxes etc. // Starts a new game or resumes one from the database $game = new Game($_SESSION['user_id']); $game_info = $game->getGameInfo(); // Instantiates a new Wordpicker $wordpicker = new Wordpicker(); $wordpicker->setWordlists((isset($game_info['wordlists'])) ? $game_info['wordlists'] : $wordlists); $wordpicker->setUsedWordlists((isset($game_info['used_wordlists'])) ? $game_info['used_wordlists'] : NULL); $wordpicker->setUsedWords((isset($game_info['used_words'])) ? $game_info['used_words'] : NULL); // Fetches an available word if (! $word_id = $wordpicker->getRandomWord()) { // No more words left - game over! $game->deleteSession($game_info['id']); redirect(); } else { // Presents word details to the user $word = new Word(); $word_info = $word->getWordInfo($word_id); } The Bit to Finish /* CONTROLLER */ /* "Check the answer" page */ // ?????????????????? ( http://pastebin.com/cc6MtLTR ) Make sure you toggle the 'Layout Width' to the right for a better view. Thanks in advance. Questions To which extent should objects be loosely coupled? If object A needs info from object B, how is it supposed to get this without losing too much cohesion? As suggested in the comments, models should hold all business logic. However, as objects should be independent, where to glue them together? Should the model contain some sort of "index" or "client" area which connects the dots? Edit: So basically what I should do for a start is to make a new model which I can more easily call with oneliners such as $model->doAction(); // Lots of code in here which uses classes! How about the method for checking words? Should it be it's own object? I'm not sure where I should put it as it's pretty much part of the 'game'. But on another hand, I could just leave out the 'abstraction and OOPness' and make it a method of the 'client model' which will be encapsulated from the controller anyway. Very unsure about this.

    Read the article

  • Refactor: Sequential Coupling => Template Method

    Another colleague brought me present today - the blog post. Thank you. You were right!We will do some refactoring which will lead us from Anti-Pattern to Pattern. From Sequential Coupling to Template Method. And as I see it could be very common way to refactor bad code that represents mentioned anti

    Read the article

  • How to reduce tight coupling between two data sources

    - by fstuijt
    I'm having some trouble finding a proper solution to the following architecture problem. In our setting (sketched below) we have 2 data sources, where data source A is the primary source for items of type Foo. A secondary data source exists which can be used to retrieve additional information on a Foo; however this information does not always exist. Furthermore, data source A can be used to retrieve items of type Bar. However, each Bar refers to a Foo. The difficulty here is that each Bar should refer to a Foo which, if available, also contains the information as augmented by data source B. My question is: how to remove the tight coupling between data source A and B?

    Read the article

  • Making OR/M loosely coupled and abstracted away from other layers.

    - by Genuine
    Hi all. In an n-tier architecture, the best place to put an object-relational mapping (OR/M) code is in the data access layer. For example, database queries and updates can be delegated to a tool like NHibernate. Yet, I'd like to keep all references to NHibernate within the data access layer and abstract dependencies away from the layers below or above it. That way, I can swap or plug in another OR/M tool (e.g. Entity Framework) or some approach (e.g. plain vanilla stored procedure calls, mock objects) without causing compile-time errors or a major overhaul of the entire application. Testability is an added bonus. Could someone please suggest a wrapper (i.e. an interface or base class) or approach that would keep OR/M loosely coupled and contained in 1 layer? Or point me to resources that would help? Thanks.

    Read the article

  • ASP.Net layered communication

    - by Chris Klepeis
    Hi, We're developing a layered web application. The specs: 3 layers, data layer, business layer, ui layer. Programmed in C# Data Layer uses the entity framework Currently we plan on having the data layer return IEnumerable<T> to the business layer via linq 2 entities, and the business layer will return data to the ui layer. Since the ui layer has no knowledge of the existance of the data layer, how would it handle a result of IEnumerable passed to it from the BLL, where T is defined in the data layer? Are there any GOOD example out there on how to do this. Please note that I'm extremely new to factories / interfaces / abstraction to loosely couple layers. I saw the question here http://stackoverflow.com/questions/917457/passing-data-in-an-ntier-application and it was recommended to have the entity layer shared amongst all layers... however I do not want the other layers to be able to query the database.

    Read the article

  • What code smell best describes this code?

    - by Paul Stovell
    Suppose you have this code in a class: private DataContext _context; public Customer[] GetCustomers() { GetContext(); return _context.Customers.ToArray(); } public Order[] GetOrders() { GetContext(); return _context.Customers.ToArray(); } // For the sake of this example, a new DataContext is *required* // for every public method call private void GetContext() { if (_context != null) { _context.Dispose(); } _context = new DataContext(); } This code isn't thread-safe - if two calls to GetOrders/GetCustomers are made at the same time from different threads, they may end up using the same context, or the context could be disposed while being used. Even if this bug didn't exist, however, it still "smells" like bad code. A much better design would be for GetContext to always return a new instance of DataContext and to get rid of the private field, and to dispose of the instance when done. Changing from an inappropriate private field to a local variable feels like a better solution. I've looked over the code smell lists and can't find one that describes this. In the past I've thought of it as temporal coupling, but the Wikipedia description suggests that's not the term: Temporal coupling When two actions are bundled together into one module just because they happen to occur at the same time. This page discusses temporal coupling, but the example is the public API of a class, while my question is about the internal design. Does this smell have a name? Or is it simply "buggy code"?

    Read the article

  • ASP.Net MVC - What replaces events to support loose coupling?

    - by James
    What feature(s) of ASP.Net MVC can replace the way events can be used in Webforms to support loosely coupled components. For example, take a simple pager control: A page number is clicked Pager fires off a "PageChange" event with the new page number This subscribing page/control received the event and handles initiating a call to fetch and bind new data. What tools are available in ASP.Net MVC to support Loose coupling Component re-usability Separation of logic for a single page/view (such a very complex "portal" type page).

    Read the article

  • Best Design Pattern for Coupling User Interface Components and Data Structures

    - by szahn
    I have a windows desktop application with a tree view. Due to lack of a sound data-binding solution for a tree view, I've implemented my own layer of abstraction on it to bind nodes to my own data structure. The requirements are as follows: Populate a tree view with nodes that resemble fields in a data structure. When a node is clicked, display the appropriate control to modify the value of that property in the instance of the data structure. The tree view is populated with instances of custom TreeNode classes that inherit from TreeNode. The responsibility of each custom TreeNode class is to (1) format the node text to represent the name and value of the associated field in my data structure, (2) return the control used to modify the property value, (3) get the value of the field in the control (3) set the field's value from the control. My custom TreeNode implementation has a property called "Control" which retrieves the proper custom control in the form of the base control. The control instance is stored in the custom node and instantiated upon first retrieval. So each, custom node has an associated custom control which extends a base abstract control class. Example TreeNode implementation: //The Tree Node Base Class public abstract class TreeViewNodeBase : TreeNode { public abstract CustomControlBase Control { get; } public TreeViewNodeBase(ExtractionField field) { UpdateControl(field); } public virtual void UpdateControl(ExtractionField field) { Control.UpdateControl(field); UpdateCaption(FormatValueForCaption()); } public virtual void SaveChanges(ExtractionField field) { Control.SaveChanges(field); UpdateCaption(FormatValueForCaption()); } public virtual string FormatValueForCaption() { return Control.FormatValueForCaption(); } public virtual void UpdateCaption(string newValue) { this.Text = Caption; this.LongText = newValue; } } //The tree node implementation class public class ExtractionTypeNode : TreeViewNodeBase { private CustomDropDownControl control; public override CustomControlBase Control { get { if (control == null) { control = new CustomDropDownControl(); control.label1.Text = Caption; control.comboBox1.Items.Clear(); control.comboBox1.Items.AddRange( Enum.GetNames( typeof(ExtractionField.ExtractionType))); } return control; } } public ExtractionTypeNode(ExtractionField field) : base(field) { } } //The custom control base class public abstract class CustomControlBase : UserControl { public abstract void UpdateControl(ExtractionField field); public abstract void SaveChanges(ExtractionField field); public abstract string FormatValueForCaption(); } //The custom control generic implementation (view) public partial class CustomDropDownControl : CustomControlBase { public CustomDropDownControl() { InitializeComponent(); } public override void UpdateControl(ExtractionField field) { //Nothing to do here } public override void SaveChanges(ExtractionField field) { //Nothing to do here } public override string FormatValueForCaption() { //Nothing to do here return string.Empty; } } //The custom control specific implementation public class FieldExtractionTypeControl : CustomDropDownControl { public override void UpdateControl(ExtractionField field) { comboBox1.SelectedIndex = comboBox1.FindStringExact(field.Extraction.ToString()); } public override void SaveChanges(ExtractionField field) { field.Extraction = (ExtractionField.ExtractionType) Enum.Parse(typeof(ExtractionField.ExtractionType), comboBox1.SelectedItem.ToString()); } public override string FormatValueForCaption() { return string.Empty; } The problem is that I have "generic" controls which inherit from CustomControlBase. These are just "views" with no logic. Then I have specific controls that inherit from the generic controls. I don't have any functions or business logic in the generic controls because the specific controls should govern how data is associated with the data structure. What is the best design pattern for this?

    Read the article

  • Low coupling and tight cohesion

    - by hidayat
    Of course it depends on the situation. But when a lower lever object or system communicate with an higher level system, should callbacks or events be preferred to keeping a pointer to higher level object? For example, we have a world class that has a member variable vector<monster> monsters. When the monster class is going to communicate with the world class, should I prefer using a callback function then or should I have a pointer to the world class inside the monster class?

    Read the article

  • Should programming languages be strict or loose?

    - by Ralph
    In Python and JavaScript, semi-colons are optional. In PHP, quotes around array-keys are optional ($_GET[key] vs $_GET['key']), although if you omit them it will first look for a constant by that name. It also allows 2 different styles for blocks (colon, or brace delimited). I'm creating a programming language now, and I'm trying to decide how strict I should make it. There are a lot of cases where extra characters aren't really necessary and can be unambiguously interpreted due to priorities, but I'm wondering if I should still enforce them or not to encourage good programming habits. What do you think?

    Read the article

  • Should I use structure from a core library graphic toolkit in my domain?

    - by Laurent Bourgault-Roy
    In java (and many other programming language), there are often structure to deal with graphic element : Colour, Shape, etc. Those are most often in a UI toolkit and thus have a relatively strong coupling with UI element. Now, in the domain of my application, we often deal with colour, shape, etc, to display statistic information on an element. Right now all we do with it is display/save those element with little or no behaviour. Would it make sense to avoid "reinventing the wheel" and directly use the structures in java.awt.* or should I make my own element and avoid a coupling to this toolkit? Its not like those element are going away anytime soon (they are part of the core java library after all), but at the same time it feel weird to import java.awt.* server side. I have no problem using java.util.List everywhere. Should I feel different about those class? What would be the "recommended" practice in that case?

    Read the article

  • Loose typing not applied to objects

    - by TecBrat
    I have very little experience working with classes and object. I work in a loosely typed language, PHP. I was working with a SimpleXML object and ran into a problem where I was trying to do math with an element of that object like $results->ProductDetail->{'Net'.$i}; If I echoed that value, I'd get 0.53 but when I tried to do math with it, it was converted to 0 Is there a reason that a loosely typed language would not recognize that as a float and handle it as such? Why would "echo" handle it as a string but the math fail to convert it? Example: $xml='<?xml version="1.0" encoding="UTF-8" ?>'; $xml.='<Test> <Item> <Price>0.53</Price> </Item> </Test>'; $result=simplexml_load_string($xml); var_dump($result->Item->Price); echo '<br>'; echo $result->Item->Price; echo '<br>'; echo 1+$result->Item->Price; echo '<br>'; echo 1+(float)$result->Item->Price; Output: object(SimpleXMLElement)#4 (1) { [0]=> string(4) "0.53" } 0.53 1 1.53

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >