Search Results

Search found 3321 results on 133 pages for 'patterns'.

Page 18/133 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Using IComparable<T> Interface

    - by Pawan_Mishra
    Level : Beginner to Intermediate C# language has constantly evolved over a constant period of time.Each new version introduced new features which changed the way we programmed and solved the problems. Whether it was introduction of generics in C# 2.0 , LINQ in C# 3.0 or concept of dynamic programming in C# 4.0 , each of them had or will have greater impact on our programming style.As a developer we don’t have much option but to evolve and redefine our self in this constantly changing environment...(read more)

    Read the article

  • Should pathfinder in A* hold closedSet and openedSet or each object should hold its sets?

    - by Patryk
    I am about to implement A* pathfinding algorithm and I wonder how should I implement this - from the point of view of architecture. I have the pathfinder as a class - I think I will instantiate only one object of this class (or maybe make it a Singleton - this is not so important). The hardest part for me is whether the closedSet and openedSet should be attached to objects that can find the path for them or should be stored in pathfinder class ? I am opened to any hints and critique whatsoever. What is the best practice considering pathfinding in terms of design ?

    Read the article

  • How to document/verify consistent layering?

    - by Morten
    I have recently moved to the dark side: I am now a CUSTOMER of software development -- mainly websites. With this new role comes new concerns. As a programmer i know how solid an application becomes when it is properly layered, and I want to use this knowledge in my new job. I don't want business logic in my presentation layer, and certainly not presentation stuff in my data layer. Thus, I want to be able to demand from my supllier that they document the level of layering, and how neat and consistent the layering is. The big question is: How is the level of layering documented to me as a customer, and is that a reasonable demmand for me to have, so I don't have to look in the code (I'm not supposed to do that anymore)?

    Read the article

  • High-Level Application Architecture Question

    - by Jesse Bunch
    So I'm really wanting to improve how I architect the software I code. I want to focus on maintainability and clean code. As you might guess, I've been reading a lot of resources on this topic and all it's doing is making it harder for me to settle on an architecture because I can never tell if my design is the one that the more experienced programmer would've chosen. So I have these requirements: I should connect to one vendor and download form submissions from their API. We'll call them the CompanyA. I should then map those submissions to a schema fit for submitting to another vendor for integration with the email service provider. We'll call them the CompanyB. I should then submit those responses to the ESP (CompanyB) and then instruct the ESP to send that submitter an email. So basically, I'm copying data from one web service to another and then performing an action at the latter web service. I've identified a couple high-level services: The service that downloads data from CompanyA. I called this the CompanyAIntegrator. The service that submits the data to CompanyB. I called this CompanyBIntegrator. So my questions are these: Is this a good design? I've tried to separate the concerns and am planning to use the facade pattern to make the integrators interchangeable if the vendors change in the future. Are my naming conventions accurate and meaningful to you (who knows nothing specific of the project)? Now that I have these services, where should I do the work of taking output from the CompanyAIntegrator and getting it in the format for input to the CompanyBIntegrator? Is this OK to be done in main()? Do you have any general pointers on how you'd code something like this? I imagine this scenario is common to us engineers---especially those working in agencies. Thanks for any help you can give. Learning how to architect well is really mind-cluttering.

    Read the article

  • Where and how to reference composite MVP components?

    - by Lea Hayes
    I am learning about the MVP (Model-View-Presenter) Passive View flavour of MVC. I intend to expose events from view interfaces rather than using the observer pattern to remove explicit coupling with presenter. Context: Windows Forms / Client-Side JavaScript. I am led to believe that the MVP (or indeed MVC in general) pattern can be applied at various levels of a user interface ranging from the main "Window" to an embedded "Text Field". For instance, the model to the text field is probably just a string whereas the model to the "Window" contains application specific view state (like a persons name which resides within the contained text field). Given a more complex scenario: Documentation viewer which contains: TOC navigation pane Document view Search pane Since each of these 4 user interface items are complex and can be reused elsewhere it makes sense to design these using MVP. Given that each of these user interface items comprises of 3 components; which component should be nested? where? who instantiates them? Idea #1 - Embed View inside View from Parent View public class DocumentationViewer : Form, IDocumentationViewerView { public DocumentationViewer() { ... // Unclear as to how model and presenter are injected... TocPane = new TocPaneView(); } protected ITocPaneView TocPane { get; private set; } } Idea #2 - Embed Presenter inside View from Parent View public class DocumentationViewer : Form, IDocumentationViewerView { public DocumentationViewer() { ... // This doesn't seem like view logic... var tocPaneModel = new TocPaneModel(); var tocPaneView = new TocPaneView(); TocPane = new TocPanePresenter(tocPaneModel, tocPaneView); } protected TocPanePresenter TocPane { get; private set; } } Idea #3 - Embed View inside View from Parent Presenter public class DocumentationViewer : Form, IDocumentationViewerView { ... // Part of IDocumentationViewerView: public ITocPaneView TocPane { get; set; } } public class DocumentationViewerPresenter { public DocumentationViewerPresenter(DocumentationViewerModel model, IDocumentationViewerView view) { ... var tocPaneView = new TocPaneView(); var tocPaneModel = new TocPaneModel(model.Toc); var tocPanePresenter = new TocPanePresenter(tocPaneModel, tocPaneView); view.TocPane = tocPaneView; } } Some better idea...

    Read the article

  • Advantages of Singleton Class over Static Class?

    Point 1)Singleton We can get the object of singleton and then pass to other methods.Static Class We can not pass static class to other methods as we pass objectsPoint 2) Singleton In future, it is easy to change the logic of of creating objects to some pooling mechanism. Static Class Very difficult to implement some pooling logic in case of static class. We would need to make that class as non-static and then make all the methods non-static methods, So entire your code needs to be changed.Point3:) Singleton Can Singletone class be inherited to subclass? Singleton class does not say any restriction of Inheritence. So we should be able to do this as long as subclass is also inheritence.There's nothing fundamentally wrong with subclassing a class that is intended to be a singleton. There are many reasons you might want to do it. and there are many ways to accomplish it. It depends on language you use.Static Class We can not inherit Static class to another Static class in C#. Think about it this way: you access static members via type name, like this: MyStaticType.MyStaticMember(); Were you to inherit from that class, you would have to access it via the new type name: MyNewType.MyStaticMember(); Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism. span.fullpost {display:none;}

    Read the article

  • A talk about observer pattern

    - by Martin
    As part of a university course I'm taking, I have to hold a 10 minute talk about the observer pattern. So far these are my points: What is it? (defenition) Polling is an alternative Polling VS Observer When Observer is better When Polling is better (taken from here) A statement that Mediator pattern is worth checking out. (I won't have time to cover it in 10 minutes) I would be happy to hear about: Any suggestions to add something? Another alternative (if exists)

    Read the article

  • Is it a "pattern smell" to put getters like "FullName" or "FormattedPhoneNumber" in your model?

    - by DanM
    I'm working on an ASP.NET MVC app, and I've been getting into the habit of putting what seem like helpful and convenient getters into my model/entity classes. For example: public class Member { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public string FullName { get { return FirstName + " " + LastName; } } public string FormattedPhoneNumber { get { return "(" + PhoneNumber.Substring(0, 3) + ") " + PhoneNumber.Substring(3, 3) + "-" + PhoneNumber.Substring(6); } } } I'm wondering people think about the FullName and FormattedPhoneNumber getters. They make it very easy to create standardized data formats throughout the app, and they seem to save a lot of repeated code, but it could definitely be argued that data format is something that should be handled in mapping from model to view-model. In fact, I was originally applying these data formats in my service layer where I do my mapping, but it was becoming a burden to constantly have to write formatters then apply them in many different places. E.g., I use "Full Name" in most views, and having to type something like model.FullName = MappingUtilities.GetFullName(entity.FirstName, entity.LastName); all over the place seemed a lot less elegant than just typing model.FullName = entity.FullName (or, if you use something like AutoMapper, potentially not typing anything at all). So, where do you draw the line when it comes to data formatting. Is it "okay" to do data formatting in your model or is that a "pattern smell"? Note: I definitely do not have any html in my model. I use html helpers for that. I'm strictly talking about formatting or combining data (and especially data that is frequently used).

    Read the article

  • Project structure: where to put business logic

    - by Mister Smith
    First of all, I'm not asking where does business logic belong. This has been asked before and most answers I've read agree in that it belongs in the model: Where to put business logic in MVC design? How much business logic should be allowed to exist in the controller layer? How accurate is "Business logic should be in a service, not in a model"? Why put the business logic in the model? What happens when I have multiple types of storage? However people disagree in the way this logic should be distributed across classes. There seem to exist three major currents of thought: Fat model with business logic inside entity classes. Anemic model and business logic in "Service" classes. It depends. I find all of them problematic. The first option is what most Fowlerites stick to. The problem with a fat model is that sometimes a business logic funtion is not only related to a class, and instead uses a bunch of other classes. If, for example, we are developing a web store, there should be a function that calcs an order's total. We could think of putting this function inside the Order class, but what actually happens is that the logic needs to use different classes, not only data contained in the Order class, but also in the User class, the Session class, and maybe the Tax class, Country class, or Giftcard, Payment, etc. Some of these classes could be composed inside the Order class, but some others not. Sorry if the example is not very good, but I hope you understand what I mean. Putting such a function inside the Order class would break the single responsibility principle, adding unnecesary dependences. The business logic would be scattered across entity classes, making it hard to find. The second option is the one I usually follow, but after many projects I'm still in doubt about how to name the class or classes holding the business logic. In my company we usually develop apps with offline capabilities. The user is able to perform entire transactions offline, so all validation and business rules should be implemented in the client, and then there's usually a background thread that syncs with the server. So we usually have the following classes/packages in every project: Data model (DTOs) Data Access Layer (Persistence) Web Services layer (Usually one class per WS, and one method per WS method). Now for the business logic, what is the standard approach? A single class holding all the logic? Multiple classes? (if so, what criteria is used to distribute the logic across them?). And how should we name them? FooManager? FooService? (I know the last one is common, but in our case it is bad naming because the WS layer usually has classes named FooWebService). The third option is probably the right one, but it is also devoid of any useful info. To sum up: I don't like the first approach, but I accept that I might have been unable to fully understand the Zen of it. So if you advocate for fat models as the only and universal solution you are welcome to post links explaining how to do it the right way. I'd like to know what is the standard design and naming conventions for the second approach in OO languages. Class names and package structure, in particular. It would also be helpful too if you could include links to Open Source projects showing how it is done. Thanks in advance.

    Read the article

  • Is there a pattern or best practice for passing a reference type to multiple classes vs a static class?

    - by Dave
    My .NET application creates HTML files, and as such, the structure looks like variable myData BuildHomePage() variable graph = new BuildGraphPage(myData) variable table = BuildTablePage(myData) BuildGraphPage and BuildTablePage both require access data, the myData object. In the above example, I've passed the myData object to 2 constructors. This is what I'm doing now, in my current project. The myData object, and it's properties are all readonly. The problem is, the number of pages which will require this object has grown. In the real project, there are currently 4, but the new spec is to have about 20. Passing this object to the constructor of each new object and assigning it to a field is a little time consuming, but not a hardship! This poses the question whether it's better practice to continue as I have, or to refactor and create a new static class for myData which can be referenced from any where in my project. I guess my abilities to use Google are poor, because I did try and find an appropriate pattern as I am sure this type of design must be common place but my results returned nothing. Is there a pattern which is suited, or do best practices lean towards one implementation over another.

    Read the article

  • Implementing a modern web application with Web API on top of old services

    - by Gaui
    My company has many WCF services which may or may not be replaced in the near future. The old web application is written in WebForms and communicates straight with these services via SOAP and returns DataTables. Now I am designing a new modern web application in a modern style, an AngularJS client which communicates with an ASP.NET Web API via JSON. The Web API then communicates with the WCF services via SOAP. In the future I want to let the Web API handle all requests and go straight to the database, but because the business logic implemented in the WCF services is complicated it's going to take some time to rewrite and replace it. Now to the problem: I'm trying to make it easy in the near future to replace the WCF services with some other data storage, e.g. another endpoint, database or whatever. I also want to make it easy to unit test the business logic. That's why I have structured the Web API with a repository layer and a service layer. The repository layer has a straight communication with the data storage (WCF service, database, or whatever) and the service layer then uses the repository (Dependency Injection) to get the data. It doesn't care where it gets the data from. Later on I can be in control and structure the data returned from the data storage (DataTable to POCO) and be able to test the logic in the service layer with some mock repository (using Dependency Injection). Below is some code to explain where I'm going with this. But my question is, does this all make sense? Am I making this overly complicated and could this be simplified in any way possible? Does this simplicity make this too complicated to maintain? My main goal is to make it as easy as possible to switch to another data storage later on, e.g. an ORM and be able to test the logic in the service layer. And because the majority of the business logic is implemented in these WCF services (and they return DataTables), I want to be in control of the data and the structure returned to the client. Any advice is greatly appreciated. Update 20/08/14 I created a repository factory, so services would all share repositories. Now it's easy to mock a repository, add it to the factory and create a provider using that factory. Any advice is much appreciated. I want to know if I'm making things more complicated than they should be. So it looks like this: 1. Repository Factory public class RepositoryFactory { private Dictionary<Type, IServiceRepository> repositories; public RepositoryFactory() { this.repositories = new Dictionary<Type, IServiceRepository>(); } public void AddRepository<T>(IServiceRepository repo) where T : class { if (this.repositories.ContainsKey(typeof(T))) { this.repositories.Remove(typeof(T)); } this.repositories.Add(typeof(T), repo); } public dynamic GetRepository<T>() { if (this.repositories.ContainsKey(typeof(T))) { return this.repositories[typeof(T)]; } throw new RepositoryNotFoundException("No repository found for " + typeof(T).Name); } } I'm not very fond of dynamic but I don't know how to retrieve that repository otherwise. 2. Repository and service // Service repository interface // All repository interfaces extend this public interface IServiceRepository { } // Invoice repository interface // Makes it easy to mock the repository later on public interface IInvoiceServiceRepository : IServiceRepository { List<Invoice> GetInvoices(); } // Invoice repository // Connects to some data storage to retrieve invoices public class InvoiceServiceRepository : IInvoiceServiceRepository { public List<Invoice> GetInvoices() { // Get the invoices from somewhere // This could be a WCF, a database, or whatever using(InvoiceServiceClient proxy = new InvoiceServiceClient()) { return proxy.GetInvoices(); } } } // Invoice service // Service that handles talking to a real or a mock repository public class InvoiceService { // Repository factory RepositoryFactory repoFactory; // Default constructor // Default connects to the real repository public InvoiceService(RepositoryFactory repo) { repoFactory = repo; } // Service function that gets all invoices from some repository (mock or real) public List<Invoice> GetInvoices() { // Query the repository return repoFactory.GetRepository<IInvoiceServiceRepository>().GetInvoices(); } }

    Read the article

  • Evolution of an Application: how to manage and improve core engine?

    - by Phil Carter
    The web application I work on has been live for a year now, but it's time for it to evolve and one of the ways in which it is evolving is into a multi-brand application - in this case several different companies using the application, different templates/content and some slight business logic changes between them. The problem I'm facing is implementing a best practice across the site where there are differences in business logic for each brand. These will mostly be very superficial, using a an alternative mailing list provider or capturing some extra data in a form. I don't want to have if(brand === x) { ... } else { ... } all over the site especially as most of what needs to be changed can be handled with extending the existing class. I've thought of several methods that could be used to instantiate the correct class, but I'm just not sure which is going to be best especially as some seem to lead to duplication of more code than should be necessary. Here's what I've considered: 1) Use a Static Loader similar to Zend_Loader which can take the class being requested, and has knowledge of the Brand and can then return the correct object. $class = App_Loader::getObject('User', $brand); 2) Factory classes. We use these in the application already for Products but we could utilise them here also to provide a transparent interface to the class. 3) Routing the page request to a specific brand controller. This however seems like it would duplicate a lot of code/logic. Is there a pattern or something else I should be considering to solve this problem? 4) How to manage a growing project that has multiple custom instances in production? Update This is a PHP application so the decisions on which class to load are made per request. There could be upwards of 100+ different 'brands' running.

    Read the article

  • DDD: Service or Repository

    - by tikhop
    I am developing an app in DDD manner. And I have a little problem with it. I have a Fare (airline fare) and FareRepository objects. And at some point I should load additional fare information and set this information to existing Fare. I guess that I need to create an Application Service (FareAdditionalInformationService) that will deal with obtaining data from the server and than update existing Fare. However, some people said me that it is necessary to use FareRepository for this problem. I don't know wich place is better for my problem Service or Repository.

    Read the article

  • Is this kind of design - a class for Operations On Object - correct?

    - by Mithir
    In our system we have many complex operations which involve many validations and DB activities. One of the main Business functionality could have been designed better. In short, there were no separation of layers, and the code would only work from the scenario in which it was first designed at, and now there were more scenarios (like requests from an API or from other devices) So I had to redesign. I found myself moving all the DB code to objects which acts like Business to DB objects, and I've put all the business logic in an Operator kind of a class, which I've implemented like this: First, I created an object which will hold all the information needed for the operation let's call it InformationObject. Then I created an OperatorObject which will take the InformationObject as a parameter and act on it. The OperatorObject should activate different objects and validate or check for existence or any scenario in which the business logic is compromised and then make the operation according to the information on the InformationObject. So my question is - Is this kind of implementation correct? PS, this Operator only works on a single Business-wise Operation.

    Read the article

  • Dapper and object validation/business rules enforcement

    - by Eugene
    This isn't really Dapper-specific, actually, as it relates to any XML-serializeable object.. but it came up when I was storing an object using Dapper. Anyways, say I have a user class. Normally, I'd do something like this: class User { public string SIN {get; private set;} public string DisplayName {get;set;} public User(string sin) { if (string.IsNullOrWhiteSpace(sin)) throw new ArgumentException("SIN must be specified"); this.SIN = sin; } } Since a SIN is required, I'd just create a constructor with a sin parameter, and make it read-only. However, with a Dapper (and probably any other ORM), I need to provide a parameterless constructor, and make all properties writeable. So now I have this: class User: IValidatableObject { public int Id { get; set; } public string SIN { get; set; } public string DisplayName { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { // implementation } } This seems.. can't really pick the word, a bad smell? A) I'm allowing to change properties that should not be changed ever after an object has been created (SIN, userid) B) Now I have to implement IValidatableObject or something like that to test those properties before updating them to db. So how do you go about it ?

    Read the article

  • Web Developer interview questions

    - by Baba
    I read an article today that listed some basic questions about web development: Describe how POST data was submitted to a server by a browser. Explain a number of HTTP status codes (except maybe 404 and 500). Explain SOLID or name a design pattern. Explain ways to improve a page load speed or user experience. The author says "if you can’t answer the questions above there are a lot of people who wouldn’t think of you as a Senior Web Developer." My questions are: How relevant are these questions in respect to real life web programming and scalability? How true is that statement? In other words, do you consider this knowledge a requirement to be considered a Senior Web Developer? I was able to answer all the questions, too easily it seemed, so I'm wondering whether it is effective to use these or similar questions to screen developers rather than asking them to write sample code.

    Read the article

  • Highly scalable and dynamic "rule-based" applications?

    - by Prof Plum
    For a large enterprise app, everyone knows that being able to adjust to change is one of the most important aspects of design. I use a rule-based approach a lot of the time to deal with changing business logic, with each rule being stored in a DB. This allows for easy changes to be made without diving into nasty details. Now since C# cannot Eval("foo(bar);") this is accomplished by using formatted strings stored in rows that are then processed in JavaScript at runtime. This works fine, however, it is less than elegant, and would not be the most enjoyable for anyone else to pick up on once it becomes legacy. Is there a more elegant solution to this? When you get into thousands of rules that change fairly frequently it becomes a real bear, but this cannot be that uncommon of a problem that someone has not thought of a better way to do this. Any suggestions? Is this current method defensible? What are the alternatives? Edit: Just to clarify, this is a large enterprise app, so no matter which solution works, there will be plenty of people constantly maintaining its rules and data (around 10). Also, The data changes frequently enough to say that some sort of centralized server system is basically a must.

    Read the article

  • Implementing MVC pattern in SWT application

    - by Pradeep Simha
    I am developing an SWT application (it's basically an Eclipse plugin, so I need to use SWT). Currently my design is as follows: Model: In model, I have POJOs which represents the actual fields in views. View: It is a dumb layer, it contains just UI and contains no logic (not even event handlers) Controller: It acts as a mediator b/w those two layers. Also it is responsible for creating view layer, handling events etc. Basically I have created all of the controls in view as a static like this public static Button btnLogin and in controller I have a code like this: public void createLoginView(Composite comp) { LoginFormView.createView(comp); //This createView method is in view layer ie LoginFormView LoginFormView.btnLogin.addSelectionListener(new SelectionListener() { //Code goes here }); } Similalrly I have done for other views and controls. So that in main class and other classes I am calling just createLoginView of controller. I am doing similar thing for other views. So my question, is what I am doing is correct? Is this design good? Or I should have followed any other approach. Since I am new to SWT and Eclipse plugin development (basically I am Java EE developer having 4+ years of exp). Any tips/pointers would be appreciated.

    Read the article

  • The Template Method Design Pattern using C# .Net

    - by nijhawan.saurabh
    First of all I'll just put this pattern in context and describe its intent as in the GOF book:   Template Method: Define the skeleton of an algorithm in an operation, deferring some steps to Subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the Algorithm's Structure.    Usage: When you are certain about the High Level steps involved in an Algorithm/Work flow you can use the Template Pattern which allows the Base Class to define the Sequence of the Steps but permits the Sub classes to alter the implementation of any/all steps.   Example in the .Net framework: The most common example is the Asp.Net Page Life Cycle. The Page Life Cycle has a few methods which are called in a sequence but we have the liberty to modify the functionality of any of the methods by overriding them.   Sample implementation of Template Method Pattern:   Let's see the class diagram first:            Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}   And here goes the code:EmailBase.cs     1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public abstract class EmailBase    10     {    11     12         public bool SendEmail()    13         {    14             if (CheckEmailAddress() == true) // Method1 in the sequence    15             {    16                 if (ValidateMessage() == true) // Method2 in the sequence    17                 {    18                     if (SendMail() == true) // Method3 in the sequence    19                     {    20                         return true;    21                     }    22                     else    23                     {    24                         return false;    25                     }    26     27                 }    28                 else    29                 {    30                     return false;    31                 }    32     33             }    34             else    35             {    36                 return false;    37     38             }    39     40     41         }    42     43         protected abstract bool CheckEmailAddress();    44         protected abstract bool ValidateMessage();    45         protected abstract bool SendMail();    46     47     48     }    49 }    50    EmailYahoo.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailYahoo:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : YahooEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : YahooEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : YahooEmail");    27             return true;    28         }    29     30     31     }    32 }    33   EmailGoogle.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailGoogle:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : GoogleEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : GoogleEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : GoogleEmail");    27             return true;    28         }    29     30     31     }    32 }    33   Program.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     class Program    10     {    11         static void Main(string[] args)    12         {    13             Console.WriteLine("Please choose an Email Account to send an Email:");    14             Console.WriteLine("Choose 1 for Google");    15             Console.WriteLine("Choose 2 for Yahoo");    16             string choice = Console.ReadLine();    17     18             if (choice == "1")    19             {    20                 EmailBase email = new EmailGoogle(); // Rather than newing it up here, you may use a factory to do so.    21                 email.SendEmail();    22     23             }    24             if (choice == "2")    25             {    26                 EmailBase email = new EmailYahoo(); // Rather than newing it up here, you may use a factory to do so.    27                 email.SendEmail();    28             }    29         }    30     }    31 }    32    Final Words: It's very obvious that why the Template Method Pattern is a popular pattern, everything at last revolves around Algorithms and if you are clear with the steps involved it makes real sense to delegate the duty of implementing the step's functionality to the sub classes. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}

    Read the article

  • Improvements to Joshua Bloch's Builder Design Pattern?

    - by Jason Fotinatos
    Back in 2007, I read an article about Joshua Blochs take on the "builder pattern" and how it could be modified to improve the overuse of constructors and setters, especially when an object has a large number of properties, most of which are optional. A brief summary of this design pattern is articled here [http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html]. I liked the idea, and have been using it since. The problem with it, while it is very clean and nice to use from the client perspective, implementing it can be a pain in the bum! There are so many different places in the object where a single property is reference, and thus creating the object, and adding a new property takes a lot of time. So...I had an idea. First, an example object in Joshua Bloch's style: Josh Bloch Style: public class OptionsJoshBlochStyle { private final String option1; private final int option2; // ...other options here <<<< public String getOption1() { return option1; } public int getOption2() { return option2; } public static class Builder { private String option1; private int option2; // other options here <<<<< public Builder option1(String option1) { this.option1 = option1; return this; } public Builder option2(int option2) { this.option2 = option2; return this; } public OptionsJoshBlochStyle build() { return new OptionsJoshBlochStyle(this); } } private OptionsJoshBlochStyle(Builder builder) { this.option1 = builder.option1; this.option2 = builder.option2; // other options here <<<<<< } public static void main(String[] args) { OptionsJoshBlochStyle optionsVariation1 = new OptionsJoshBlochStyle.Builder().option1("firefox").option2(1).build(); OptionsJoshBlochStyle optionsVariation2 = new OptionsJoshBlochStyle.Builder().option1("chrome").option2(2).build(); } } Now my "improved" version: public class Options { // note that these are not final private String option1; private int option2; // ...other options here public String getOption1() { return option1; } public int getOption2() { return option2; } public static class Builder { private final Options options = new Options(); public Builder option1(String option1) { this.options.option1 = option1; return this; } public Builder option2(int option2) { this.options.option2 = option2; return this; } public Options build() { return options; } } private Options() { } public static void main(String[] args) { Options optionsVariation1 = new Options.Builder().option1("firefox").option2(1).build(); Options optionsVariation2 = new Options.Builder().option1("chrome").option2(2).build(); } } As you can see in my "improved version", there are 2 less places in which we need to add code about any addition properties (or options, in this case)! The only negative that I can see is that the instance variables of the outer class are not able to be final. But, the class is still immutable without this. Is there really any downside to this improvement in maintainability? There has to be a reason which he repeated the properties within the nested class that I'm not seeing?

    Read the article

  • Builder Pattern: When to fail?

    - by skiwi
    When implementing the Builder Pattern, I often find myself confused with when to let building fail and I even manage to take different stands on the matter every few days. First some explanation: With failing early I mean that building an object should fail as soon as an invalid parameter is passed in. So inside the SomeObjectBuilder. With failing late I mean that building an object only can fail on the build() call that implicitely calls a constructor of the object to be built. Then some arguments: In favor of failing late: A builder class should be no more than a class that simply holds values. Moreover, it leads to less code duplication. In favor of failing early: A general approach in software programming is that you want to detect issues as early as possible and therefore the most logical place to check would be in the builder class' constructor, 'setters' and ultimately in the build method. What is the general concensus about this?

    Read the article

  • NCurses, scrolling of multiline items, "current item" pointer and "selected items"

    - by mjf
    I am looking for hints/ideas for the best (most effective) way on how to scroll multi-line items as well as emphasizing of the "current item" and "selected items" such as: 1 FOO ITEM 1 Foo sub-item 2 Foo sub-item 3 Foo sub-item 2 BAR ITEM 1 Bar sub-item 3 BAZ ITEM 1 Baz sub-item 2 Baz sub-item 4 RAB ITEM 5 ZZZ ITEM 1 Zzz sub-item 2 Zzz sub-item 3 Zzz sub-item 4 Zzz sub-item using NCurses (some combination of windows, sub-windows, pads, copywin? Uff! In fact, the lines could exceed the stdscr's width so that possibility to scroll left/right would be also nice - pads?)... The whole items (including the sub-items) are supposed to be emphasized as full-width window/pad areas. The "current item" (including it's set of lines) should be emphasized (i.e. using A_BOLD), selected set of items of choice (including the set of lines for each the selected item) should be emphasized in another way (i.e. using A_REVERSE). What would you choose to cope with it the most effective NCurses way? (The less redrawals/refreshes the better and terminal is supposed to have the ability to change it's size - such as XTerm running under "floating window" management.) Thank you for your ideas (or perhaps some piece of code where something similar is already solved - I was not able to find anything helpful on the Internet. I mean I am not going to copy/paste foreign code but programming NCurses properly is still somehow difficult to me). P.S.: Would you suggest to "smooth-scroll" +1/-1 screen line or rather "jump-scroll" +lines/-lines of the items? (I personally prefer the latter one.) Sincerely, -- mjf

    Read the article

  • Design pattern for isomorphic trees

    - by Peregring-lk
    I want to create a data structure to work with isomorphic tree. I don't search for a "algorithms" or methods to check if two or more trees are isomorphic each other. Just to create various trees with the same structure. Example: 2 - - - - - - - 'a' - - - - - - - 3.5 / \ / \ / \ 3 3 'f' 'y' 1.0 3.1 / \ / \ / \ 4 7 'e' 'f' 2.3 7.7 The first "layer" or tree is the "natural tree" (a tree with natural numbers), the second layer is the "character tree" and the third one is the "float tree". The data structure has a method or iterator to traverse the tree and to make diferent operations with its values. These operations could change the value of nodes, but never its structure (first I create the structure and then I configure the tree with its diferent layers). In case of that I add a new node, this would be applied to each layer. Which known design pattern fits with this description or is related with it?

    Read the article

  • What are the downsides to using dependency injection?

    - by kerry
    I recently came across an interesting question on stack overflow with some interesting reponses.  I like this post for three reasons. First, I am a big fan of dependency injection, it forces you to decouple your code, create cohesive interfaces, and should result in testable classes. Second, the author took the approach I usually do when trying to evaluate a technique or technology; suspend personal feelings and try to find some compelling arguments against it. Third, it proved that it is very difficult to come up with a compelling argument against dependency injection. What are the downsides to using dependency injection?

    Read the article

  • Command-Query-Separation and multithreading safe interfaces

    - by Tobias Langner
    I like the command query separation pattern (from OOSC / Eiffel - basically you either return a value or you change the state of the class - but not both). This makes reasoning about the class easier and it is easier to write exception safe classes. Now, with multi threading, I run into a major problem: the separation of the query and the command basically invalidates the result from the query as anything can happen between those 2. So my question is: how do you handle command query separation in an multi-threaded environment? Clarification example: A stack with command query separation would have the following methods: push (command) pop (command - but does not return a value) top (query - returns the value) empty (query) The problem here is - I can get empty as status, but then I can not rely on top really retrieving an element since between the call of empty and the call of top, the stack might have been emptied. Same goes for pop & top. If I get an item using top, I can not be sure that the item that I pop is the same. This can be solved using external locks - but that's not exactly what I call threadsafe design.

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >