Search Results

Search found 32130 results on 1286 pages for 'method chaining'.

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

  • Naming Suggestions For A Function Providing Method Chaining In A Different Way

    - by sid3k
    I've coded an experimental function which makes passed objects chainable by using high order functions. It's name is "chain" for now, and here is a usage example; chain("Hello World") (print) // evaluates print function by passing "Hello World" object. (console.log,"Optional","Parameters") (returnfrom) // returns "Hello World" It looks lispy but behaves very different since it's coded in a C based language, I don't know if there is a name for this idiom and I couldn't any name more suitable than "chain". Any ideas, suggestions?

    Read the article

  • Naming Suggestions For A Function Providing Chaining In A Different Way

    - by sid3k
    I've coded an experimental function which makes passed objects chainable by using high order functions. It's name is "chain" for now, and here is a usage example; chain("Hello World") (print) // evaluates print function by passing "Hello World" object. (console.log,"Optional","Parameters") (returnfrom) // returns "Hello World" It looks lispy but behaves very different since it's coded in a C based language, I don't know if there is a name for this idiom and I couldn't any name more suitable than "chain". Any ideas, suggestions?

    Read the article

  • LINQ method chaining and granular error handling

    - by Clafou
    I have a method which can be written pretty neatly through method chaining: return viewer.ServerReport.GetParameters() .Single(p => p.Name == Convention.Ssrs.RegionParamName) .ValidValues .Select(v => v.Value); However I'd like to be able to do some checks at each point as I wish to provide helpful diagnostics information if any of the chained methods returns unexpected results. To achieve this, I need to break up all my chaining and follow each call with an if block. It makes the code a lot less readable. Ideally I'd like to be able to weave in some chained method calls which would allow me to handle unexpected outcomes at each point (e.g. throw a meaningful exception such as new ConventionException("The report contains no parameter") if the first method returns an empty collection). Can anyone suggest a simple way to achieve such a thing?

    Read the article

  • Method chaining and exceptions in C#

    - by devoured elysium
    If I have a method chain like the following: var abc = new ABC(); abc.method1() .method2() .methodThrowsException() .method3() ; assuming I've defined method1(), method2() and method3() as public ABC method1() { return this; } and methodThrowsException() as public ABC method3() { throw new ArgumentException(); } When running the code, is it possible to know which specific line of code has thrown the Exception, or will it just consider all the method chaining as just one line? I've done a simple test and it seems it considers them all as just one line but Method Chaining says Putting methods on separate lines also makes debugging easier as error messages and debugger control is usually on a line by line basis. Am I missing something, or does that just not apply to C#? Thanks

    Read the article

  • Can Eclipse generate method-chaining setters

    - by Chris R
    I'd like to generate method-chaining setters (setters that return the object being set), like so: public MyObject setField (Object value) { this.field = value; return this; } This makes it easier to do one-liner instantiations, which I find easier to read: myMethod (new MyObject ().setField (someValue).setOtherField (someOtherValue)); Can Eclipse's templates be modified to do this? I've changed the content to include return this; but the signature is not changed.

    Read the article

  • C++ method chaining including class constructor

    - by jena
    Hello, I'm trying to implement method chaining in C++, which turns out to be quite easy if the constructor call of a class is a separate statement, e.g: Foo foo; foo.bar().baz(); But as soon as the constructor call becomes part of the method chain, the compiler complains about expecting ";" in place of "." immediately after the constructor call: Foo foo().bar().baz(); I'm wondering now if this is actually possible in C++. Here is my test class: class Foo { public: Foo() { } Foo& bar() { return *this; } Foo& baz() { return *this; } }; I also found an example for "fluent interfaces" in C++ (http://en.wikipedia.org/wiki/Fluent_interface#C.2B.2B) which seems to be exactly what I'm searching for. However, I get the same compiler error for that code. Thanks in advance for any hint. Best, Jean

    Read the article

  • Creating a dynamic proxy generator with c# – Part 4 – Calling the base method

    - by SeanMcAlinden
    Creating a dynamic proxy generator with c# – Part 1 – Creating the Assembly builder, Module builder and caching mechanism Creating a dynamic proxy generator with c# – Part 2 – Interceptor Design Creating a dynamic proxy generator with c# – Part 3 – Creating the constructors   The plan for calling the base methods from the proxy is to create a private method for each overridden proxy method, this will allow the proxy to use a delegate to simply invoke the private method when required. Quite a few helper classes have been created to make this possible so as usual I would suggest download or viewing the code at http://rapidioc.codeplex.com/. In this post I’m just going to cover the main points for when creating methods. Getting the methods to override The first two notable methods are for getting the methods. private static MethodInfo[] GetMethodsToOverride<TBase>() where TBase : class {     return typeof(TBase).GetMethods().Where(x =>         !methodsToIgnore.Contains(x.Name) &&                              (x.Attributes & MethodAttributes.Final) == 0)         .ToArray(); } private static StringCollection GetMethodsToIgnore() {     return new StringCollection()     {         "ToString",         "GetHashCode",         "Equals",         "GetType"     }; } The GetMethodsToIgnore method string collection contains an array of methods that I don’t want to override. In the GetMethodsToOverride method, you’ll notice a binary AND which is basically saying not to include any methods marked final i.e. not virtual. Creating the MethodInfo for calling the base method This method should hopefully be fairly easy to follow, it’s only function is to create a MethodInfo which points to the correct base method, and with the correct parameters. private static MethodInfo CreateCallBaseMethodInfo<TBase>(MethodInfo method) where TBase : class {     Type[] baseMethodParameterTypes = ParameterHelper.GetParameterTypes(method, method.GetParameters());       return typeof(TBase).GetMethod(        method.Name,        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,        null,        baseMethodParameterTypes,        null     ); }   /// <summary> /// Get the parameter types. /// </summary> /// <param name="method">The method.</param> /// <param name="parameters">The parameters.</param> public static Type[] GetParameterTypes(MethodInfo method, ParameterInfo[] parameters) {     Type[] parameterTypesList = Type.EmptyTypes;       if (parameters.Length > 0)     {         parameterTypesList = CreateParametersList(parameters);     }     return parameterTypesList; }   Creating the new private methods for calling the base method The following method outline how I’ve created the private methods for calling the base class method. private static MethodBuilder CreateCallBaseMethodBuilder(TypeBuilder typeBuilder, MethodInfo method) {     string callBaseSuffix = "GetBaseMethod";       if (method.IsGenericMethod || method.IsGenericMethodDefinition)     {                         return MethodHelper.SetUpGenericMethod             (                 typeBuilder,                 method,                 method.Name + callBaseSuffix,                 MethodAttributes.Private | MethodAttributes.HideBySig             );     }     else     {         return MethodHelper.SetupNonGenericMethod             (                 typeBuilder,                 method,                 method.Name + callBaseSuffix,                 MethodAttributes.Private | MethodAttributes.HideBySig             );     } } The CreateCallBaseMethodBuilder is the entry point method for creating the call base method. I’ve added a suffix to the base classes method name to keep it unique. Non Generic Methods Creating a non generic method is fairly simple public static MethodBuilder SetupNonGenericMethod(     TypeBuilder typeBuilder,     MethodInfo method,     string methodName,     MethodAttributes methodAttributes) {     ParameterInfo[] parameters = method.GetParameters();       Type[] parameterTypes = ParameterHelper.GetParameterTypes(method, parameters);       Type returnType = method.ReturnType;       MethodBuilder methodBuilder = CreateMethodBuilder         (             typeBuilder,             method,             methodName,             methodAttributes,             parameterTypes,             returnType         );       ParameterHelper.SetUpParameters(parameterTypes, parameters, methodBuilder);       return methodBuilder; }   private static MethodBuilder CreateMethodBuilder (     TypeBuilder typeBuilder,     MethodInfo method,     string methodName,     MethodAttributes methodAttributes,     Type[] parameterTypes,     Type returnType ) { MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName, methodAttributes, returnType, parameterTypes); return methodBuilder; } As you can see, you simply have to declare a method builder, get the parameter types, and set the method attributes you want.   Generic Methods Creating generic methods takes a little bit more work. /// <summary> /// Sets up generic method. /// </summary> /// <param name="typeBuilder">The type builder.</param> /// <param name="method">The method.</param> /// <param name="methodName">Name of the method.</param> /// <param name="methodAttributes">The method attributes.</param> public static MethodBuilder SetUpGenericMethod     (         TypeBuilder typeBuilder,         MethodInfo method,         string methodName,         MethodAttributes methodAttributes     ) {     ParameterInfo[] parameters = method.GetParameters();       Type[] parameterTypes = ParameterHelper.GetParameterTypes(method, parameters);       MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName,         methodAttributes);       Type[] genericArguments = method.GetGenericArguments();       GenericTypeParameterBuilder[] genericTypeParameters =         GetGenericTypeParameters(methodBuilder, genericArguments);       ParameterHelper.SetUpParameterConstraints(parameterTypes, genericTypeParameters);       SetUpReturnType(method, methodBuilder, genericTypeParameters);       if (method.IsGenericMethod)     {         methodBuilder.MakeGenericMethod(genericArguments);     }       ParameterHelper.SetUpParameters(parameterTypes, parameters, methodBuilder);       return methodBuilder; }   private static GenericTypeParameterBuilder[] GetGenericTypeParameters     (         MethodBuilder methodBuilder,         Type[] genericArguments     ) {     return methodBuilder.DefineGenericParameters(GenericsHelper.GetArgumentNames(genericArguments)); }   private static void SetUpReturnType(MethodInfo method, MethodBuilder methodBuilder, GenericTypeParameterBuilder[] genericTypeParameters) {     if (method.IsGenericMethodDefinition)     {         SetUpGenericDefinitionReturnType(method, methodBuilder, genericTypeParameters);     }     else     {         methodBuilder.SetReturnType(method.ReturnType);     } }   private static void SetUpGenericDefinitionReturnType(MethodInfo method, MethodBuilder methodBuilder, GenericTypeParameterBuilder[] genericTypeParameters) {     if (method.ReturnType == null)     {         methodBuilder.SetReturnType(typeof(void));     }     else if (method.ReturnType.IsGenericType)     {         methodBuilder.SetReturnType(genericTypeParameters.Where             (x => x.Name == method.ReturnType.Name).First());     }     else     {         methodBuilder.SetReturnType(method.ReturnType);     }             } Ok, there are a few helper methods missing, basically there is way to much code to put in this post, take a look at the code at http://rapidioc.codeplex.com/ to follow it through completely. Basically though, when dealing with generics there is extra work to do in terms of getting the generic argument types setting up any generic parameter constraints setting up the return type setting up the method as a generic All of the information is easy to get via reflection from the MethodInfo.   Emitting the new private method Emitting the new private method is relatively simple as it’s only function is calling the base method and returning a result if the return type is not void. ILGenerator il = privateMethodBuilder.GetILGenerator();   EmitCallBaseMethod(method, callBaseMethod, il);   private static void EmitCallBaseMethod(MethodInfo method, MethodInfo callBaseMethod, ILGenerator il) {     int privateParameterCount = method.GetParameters().Length;       il.Emit(OpCodes.Ldarg_0);       if (privateParameterCount > 0)     {         for (int arg = 0; arg < privateParameterCount; arg++)         {             il.Emit(OpCodes.Ldarg_S, arg + 1);         }     }       il.Emit(OpCodes.Call, callBaseMethod);       il.Emit(OpCodes.Ret); } So in the main method building method, an ILGenerator is created from the method builder. The ILGenerator performs the following actions: Load the class (this) onto the stack using the hidden argument Ldarg_0. Create an argument on the stack for each of the method parameters (starting at 1 because 0 is the hidden argument) Call the base method using the Opcodes.Call code and the MethodInfo we created earlier. Call return on the method   Conclusion Now we have the private methods prepared for calling the base method, we have reached the last of the relatively easy part of the proxy building. Hopefully, it hasn’t been too hard to follow so far, there is a lot of code so I haven’t been able to post it all so please check it out at http://rapidioc.codeplex.com/. The next section should be up fairly soon, it’s going to cover creating the delegates for calling the private methods created in this post.   Kind Regards, Sean.

    Read the article

  • what's the point of method overloading?

    - by David
    I am following a textbook in which I have just come across method overloading. It briefly described method overloading as: when the same method name is used with different parameters its called method overloading. From what I've learned so far in OOP is that if I want different behaviors from an object via methods, I should use different method names that best indicate the behavior, so why should I bother with method overloading in the first place?

    Read the article

  • When using method chaining, do I reuse the object or create one?

    - by MainMa
    When using method chaining like: var car = new Car().OfBrand(Brand.Ford).OfModel(12345).PaintedIn(Color.Silver).Create(); there may be two approaches: Reuse the same object, like this: public Car PaintedIn(Color color) { this.Color = color; return this; } Create a new object of type Car at every step, like this: public Car PaintedIn(Color color) { var car = new Car(this); // Clone the current object. car.Color = color; // Assign the values to the clone, not the original object. return car; } Is the first one wrong or it's rather a personal choice of the developer? I believe that he first approach may quickly cause the intuitive/misleading code. Example: // Create a car with neither color, nor model. var mercedes = new Car().OfBrand(Brand.MercedesBenz).PaintedIn(NeutralColor); // Create several cars based on the neutral car. var yellowCar = mercedes.PaintedIn(Color.Yellow).Create(); var specificModel = mercedes.OfModel(99).Create(); // Would `specificModel` car be yellow or of neutral color? How would you guess that if // `yellowCar` were in a separate method called somewhere else in code? Any thoughts?

    Read the article

  • How to implement exception chaining in PHP

    - by Josef Sábl
    Constructor for PHP's exception has third parameter, documentation says: $previous: The previous exception used for the exception chaining. But I can't make it work. My code looks like this: try { throw new Exception('Exception 1', 1001); } catch (Exception $ex) { throw new Exception('Exception 2', 1002, $ex); } I expect Exception 2 to be thrown and I expect that it will have Exception 1 attached. But all I get is: Fatal error: Wrong parameters for Exception([string $exception [, long $code ]]) in ... What am I doing wrong?

    Read the article

  • C++ input chaining in C#

    - by Monty
    I am trying to learn C# coming from C++. I am writing just some basic console stuff to get a feel for it and was wondering if it is possible to do simple chaining of inputs in C#. For example in C++: cout<<"Enter two numbers: "; cin >> int1 >> int2; You could then just input 3 5 and hit enter and the values will be fine. In C# however I have to split it up(as far as I can tell) like this: Console.Write("Enter the first number: "; int1 = (char)Console.Read(); Console.Writeline(""); Console.Write("Enter the second number: "; int2 = (char)Console.Read(); Maybe I am just missing something.

    Read the article

  • trouble chaining proxies

    - by proxy error
    trouble chaining proxies hows it going? i am having trouble chaining proxies. i open terminal, run nano /etc/proxychains.conf i add the list like this [ProxyList] add proxy here ... meanwile defaults set to "tor" socks4 127.0.0.1 9050 socks5 59.21.114.99 5577 i open a new tab, run proxychains firefox all i get is this ProxyChains-3.1 (http://proxychains.sf.net) firefox opens but when i google my ip address it is not what it says in the list pleaqse help

    Read the article

  • constructor function's object literal returns toString() method but no other method

    - by JohnMerlino
    I'm very confused with javascript methods defined in objects and the "this" keyword. In the below example, the toString() method is invoked when Mammal object instantiated: function Mammal(name){ this.name=name; this.toString = function(){ return '[Mammal "'+this.name+'"]'; } } var someAnimal = new Mammal('Mr. Biggles'); alert('someAnimal is '+someAnimal); Despite the fact that the toString() method is not invoked on the object someAnimal like this: alert('someAnimal is '+someAnimal.toString()); It still returns 'someAnimal is [Mammal "Mr. Biggles"]' . That doesn't make sense to me because the toString() function is not being called anywhere. Then to add even more confusion, if I change the toString() method to a method I make up such as random(): function Mammal(name){ this.name=name; this.random = function(){ return Math.floor(Math.random() * 15); } } var someAnimal = new Mammal('Mr. Biggles'); alert(someAnimal); It completely ignores the random method (despite the fact that it is defined the same way was the toString() method was) and returns: [object object] Another issue I'm having trouble understanding with inheritance is the value of "this". For example, in the below example function person(w,h){ width.width = w; width.height = h; } function man(w,h,s) { person.call(this, w, h); this.sex = s; } "this" keyword is being send to the person object clearly. However, does "this" refer to the subclass (man) or the super class (person) when the person object receives it? Thanks for clearing up any of the confusion I have with inheritance and object literals in javascript.

    Read the article

  • alias_attribute and creating and method with the original attribute name causes a loop

    - by Tiago
    Im trying to dynamically create a method chain in one attribute in my model. By now I have this function: def create_filtered_attribute(attribute_name) alias_attribute "#{attribute_name}_without_filter", attribute_name define_method "#{attribute_name}" do filter_words(self.send("#{attribute_name}_without_filter")) end end so I receive a string with the attribute name, alias it for '*_without_filter*' (alias_method or alias_method_chain fails here, because the attribute isnt there when the class is created), and I create a new method with the attribute name, where I filter its contents. But somehow, when I call *"#{attribute_name}_without_filter"* it calls my new method (i think because the alias_attribute some how), and the program goes into a stack loop. Can someone please enlighten me on this.

    Read the article

  • PHP OOP: Method Chaining

    - by Isis
    I have the following code, <?php class Templater { static $params = array(); public static function assign($name, $value) { self::$params[] = array($name => $value); } public static function draw() { self::$params; } } $test = Templater::assign('key', 'value'); $test = Templater::draw(); print_r($test); How can I alter this script so I could use this? $test = Templater::assign('key', 'value')->assign('key2', 'value2')->draw(); print_r($test);

    Read the article

  • jQuery:Problem in Chaining the events.

    - by Shyju
    I have the following javascript function which will load data from a server page to the div This is working fine with the FadeIn/FadeOut effects function ShowModels(manuId) { var div = $("#rightcol"); div.fadeOut('slow',function() { div.load("../Lib/handlers/ModelLookup.aspx?mode=bymanu&mid="+manuId, { symbol: $("#txtSymbol" ).val() }, function() { $(this).fadeIn(); }); }); } Now i want to Show a Loading Message till the div loads the contents from the server page I tried this.But its not working.Can any one help me to debug this ? Thanks in advance function ShowModels(manuId) { var div = $("#rightcol"); var strLoadingMsg="<img src='loading.gif'/><h3>Loading...</h3>"; div.fadeOut('slow',function() { div.load(strLoadingMsg,function(){ div.load("../Lib/handlers/ModelLookup.aspx?mode=bymanu&mid="+manuId, { symbol: $("#txtSymbol" ).val() }, function() { $(this).fadeIn(); }); }); }); } My ultimate requirement is to FadeOut the current content.Show the Loading message.Show the Data coming from server with a FadeIn effect

    Read the article

  • Override ActiveRecord#save, Method Alias? Trying to mixin functionality into save method...

    - by viatropos
    Here's the situation: I have a User model, and two modules for authentication: Oauth and Openid. Both of them override ActiveRecord#save, and have a fair share of implementation logic. Given that I can tell when the user is trying to login via Oauth vs. Openid, but that both of them have overridden save, how do "finally" override save such that I can conditionally call one of the modules' implementations of it? Here is the base structure of what I'm describing: module UsesOauth def self.included(base) base.class_eval do def save puts "Saving with Oauth!" end def save_with_oauth save end end end end module UsesOpenid def self.included(base) base.class_eval do def save puts "Saving with OpenID!" end def save_with_openid save end end end end module Sequencer def save if using_oauth? save_with_oauth elsif using_openid? save_with_openid else super end end end class User < ActiveRecord::Base include UsesOauth include UsesOpenid include Sequencer end I was thinking about using alias_method like so, but that got too complicated, because I might have 1 or 2 more similar modules. I also tried using those save_with_oauth methods (shown above), which almost works. The only thing that's missing is that I also need to call ActiveRecord::Base#save (the super method), so something like this: def save_with_oauth # do this and that super.save # the rest end But I'm not allowed to do that in ruby. Any ideas for a clever solution to this?

    Read the article

  • When should a method of a class return the same instance after modifying itself?

    - by modiX
    I have a class that has three methods A(), B() and C(). Those methods modify the own instance. While the methods have to return an instance when the instance is a separate copy (just as Clone()), I got a free choice to return void or the same instance (return this;) when modifying the same instance in the method and not returning any other value. When deciding for returning the same modified instance, I can do neat method chains like obj.A().B().C();. Would this be the only reason for doing so? Is it even okay to modify the own instance and return it, too? Or should it only return a copy and leave the original object as before? Because when returning the same modified instance the user would maybe admit the returned value is a copy, otherwise it would not be returned? If it's okay, what's the best way to clarify such things on the method?

    Read the article

  • Why does Java's invokevirtual need to resolve the called method's compile-time class?

    - by Chris
    Consider this simple Java class: class MyClass { public void bar(MyClass c) { c.foo(); } } I want to discuss what happens on the line c.foo(). At the bytecode level, the meat of c.foo() will be the invokevirtual opcode, and, according to the documentation for invokevirtual, more or less the following will happen: Look up the foo method defined in compile-time class MyClass. (This involves first resolving MyClass.) Do some checks, including: Verify that c is not an initialization method, and verify that calling MyClass.foo wouldn't violate any protected modifiers. Figure out which method to actually call. In particular, look up c's runtime type. If that type has foo(), call that method and return. If not, look up c's runtime type's superclass; if that type has foo, call that method and return. If not, look up c's runtime type's superclass's superclass; if that type has foo, call that method and return. Etc.. If no suitable method can be found, then error. Step #3 alone seems adequate for figuring out which method to call and verifying that said method has the correct argument/return types. So my question is why step #1 gets performed in the first place. Possible answers seem to be: You don't have enough information to perform step #3 until step #1 is complete. (This seems implausible at first glance, so please explain.) The linking or access modifier checks done in #1 and #2 are essential to prevent certain bad things from happening, and those checks must be performed based on the compile-time type, rather than the run-time type hierarchy. (Please explain.)

    Read the article

  • Static method , Abstract method , Interface method comparision ?

    - by programmerist
    When i choose these methods? i can not decide which one i must prefer or when will i use one of them?which one give best performance? First Type Usage public abstract class _AccessorForSQL { public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType); public virtual bool Update(); public virtual bool Delete(); public virtual DataSet Select(); } class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } Second Type Usage Also i can write it below codes: public class GenAccessor { public Static bool Save() { } public Static bool Update() { } public Static bool Delete() { } } Third Type Usage Also i can write it below codes: public interface IAccessorForSQL { bool Delete(); bool Save(string sp, ListDictionary ld, CommandType cmdType); DataSet Select(); bool Update(); } public class _AccessorForSQL : IAccessorForSQL { private DataSet ds; private DataTable dt; public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType) { } } } I can use first one below usage: GenAccessor gen = New GenAccessor(); gen.Save(); I can use second one below usage: GenAccessor.Save(); Which one do you prefer? When will i use them? which time i need override method ? which time i need static method?

    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

  • Ajax method within a added method in jQuery validator

    - by nikospkrk
    Hi, I'm kind of stuck with this pretty simple (I'm sure) jQuery/Javascript issue. Here's the code : jQuery.validator.addMethod("emailExists", function(value, element, param) { var email = value || ''; var valid = 0; $.ajax({ type: "POST", url: param, data: "email=" + email, success: function(msg) { if (msg != '' && msg) { valid = 0; } else { valid = 1; } } }); return valid; }, "* Email address already registered, please login."); This function is called where a user type his email address in a registration form, and everything seems to work perfectly, except that my valid variable returned isn't updated, whereas when I use an alert box it is properly done! It looks like it return the value before the AJAX is done, any idea? Cheers, Nicolas.

    Read the article

  • C# String.format extension method

    - by Paul Roe
    With the addtion of Extension methods to C# we've seen a lot of them crop up in our group. One debate revolves around extension methods like this one: public static class StringExt { /// <summary> /// Shortcut for string.Format. /// </summary> /// <param name="str"></param> /// <param name="args"></param> /// <returns></returns> public static string Format(this string str, params object[] args) { if (str == null) return null; return string.Format(str, args); } } Does this extension method break any programming best practices that you can name? Would you use it anyway, if not why? If I renamed the function to "F" but left the xml comments would that be epic fail or just a wonderful savings of keystrokes?

    Read the article

  • Why setter method when getter method enough in PHP OOP

    - by phphunger
    I am practicing OOP with PHP, and I am struck at setter and getter methods. I can directly access the class properties and methods with getter method then what's the use of setter method? See my example. <?php class MyClass{ public $classVar = "Its a class variable"; public function Getter(){ return $this -> classVar; } } $obj = new MyClass; echo $obj -> Getter(); ?>

    Read the article

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