Using GET and POST vs getter and setter methods (URLS) - html

As a trained programmer, I have been taught, repeatedly to use getter and setter methods to control the access and modification of class variables. This is how you're told to do it in Java, Python, C++ and pretty much every other modern language under the sun. However, when I started learning about web development, this seemed cast aside. Instead, we're told to use one URL with GET and POST calls, which seems really odd.
So imagine I have a Person object and I want to update their age. In the non-HTTP world, you're supposed to have a method called <PersonObject>.getAge() and another method called <PersonObject>.setAge(int newAge). But say, instead, you've got a webserver that holds user profile information. According to HTTP conventions, you'd have a URL like '/account/age'. To get their age, you'd request that URL with a 'GET', and to set their age, you'd request that URL with a 'POST' and somehow (form, JSON, URL-arg, etc.) send the new value along.
The HTTP method just feels awkward. To me, that's analogous to changing the non-HTTP version to one method called age, and you'd get their age with <PersonObject>.age('GET'), and set their age with <PersonObject>.age(newAge, 'SET'). Why is it done that way?
Why not have one URL called '/account/getAge' and another called '/account/setAge'?

What you are refering to is a RESTful API. While not required (you could just use getters and setters) it is indeed considered good practice. This however does not meen you have to change the code of your data objects. I always use getters and setters for my business logic in the models layer.
What you are talking to through the HTTP request are the controllers however, and they rarely use getters and setters (I suppose I do not need to explain the MVC design pattern to an experienced programmer). You should never directly access your models through HTTP (how about authentication and error handling and stuff...)
If you have some spare time I would advise you to have a look at this screencast, which I found very useful.

You certainly could have separate URLs if you like, but getters and setters can share names in the original context of your question anyway because of overloading.
class Person {
private age;
public age() {
return this.age;
}
public age(int age) {
this.age = age;
}
}
So if it helps you, you can think of it like that.

Related

session-specific info to comet's "onEvent" method

I have two questions about using the Comet feature with Glassfish. I'm
pretty new at this, so if there's an easy answer or some documentation
I should read please let me know! Thanks.
I'm building a system that has multiple microcontrollers sending data
to a central DB. Users view the data via their browsers ... in formats
(metric vs. English, say) of their own choosing. The display needs to
be updated without user action. It looks like Glassfish + Comet should
be perfect. And so I started with Oracle's "hidden_Comet" example, and
that works great.
So question #1 is this: how can one get session-specific information
into the "onEvent" method?
As context, here's the code; it’s straight from the Oracle example:
private class CounterHandler implements CometHandler<HttpServletResponse> {
private HttpServletResponse response;
public void onEvent(CometEvent event) throws IOException
{
if (CometEvent.NOTIFY == event.getType())
{
PrintWriter writer = response.getWriter();
writer.write("<script type='text/javascript'>");
[... etc. Here is where I need to pass some session-specific
info to the JavaScript]
event.getCometContext().resumeCometHandler(this);
}
}
It would seem that session attributes would be perfect, but it looks
like you can't get the 'session' variable from the "HttpServletResponse".
I thought about using cookies, but they seem to be accessible only with
HttpServletRequest, not "...Response", and, as above, only ‘response’
is available in the “onEvent” method.
So question #1 is: how do you do this?
Question #2 is: is this just the wrong way to attack this problem and is
there a better way?
I'm not sure I understand the data structures and control flow of Comet very well yet, but it seems that this works:
Add a constructor to "class CounterHandler" and pass in the 'session' variable from 'doGet()' where "new CounterHandler" is called. Specifically, change:
CometHandler handler = new CometHandler();
to
HttpSession session = request.getSession();
CometHandler handler = new CometHandler(session);
Have the constructor save the session variable in a class instance variable. And then the "onEvent()" method has access to session attributes. And Bob's your uncle.
(It seems straightforward enough ... well, now.)

Question on class implementation with interface

I have created the following classes for sharing images. They implement an interface, but I need a way of switching between them with user interaction. I've done it the following way:
As you can see, service 1 and service 2 implement iSharingServices, and inherit from PolimorphSharing.
PolimorphSharing is simply and an abstract class that implements the methods I want public from Service 1 and Service 2. Those methods will then be overridden on the Service 1 and Service 2.
Because I need a way to switch the service in runtime, I've created a gateway class that inherits from PolimorphSharing. I can then call it the following way:
private var sharingService:PolimorphSharing = new SharingServicesGW('svc1').createService();
This all works flawlessly, and I can now switch between services with no problem whatsoever. However, I feel there's something wrong about it, so I would like to ask you guys for some advice on how to better implement this.
Any opinions here would be appreciated. I feel like I'm kind of implementing the factory pattern here the hard way.
UPDATE:
Just adding some more insight to this. Basically the idea here is for my client to be able to upload images with various different public sharing services such as imageshack, imgur etc. I want my client to be able to select the service in which the image is to be published to (hence the "switching between them with user interaction" bit of the question.
The method that does the uploading bit, is requestShareImage(), processResults() simply turns whatever gets returned to a unique format, so my client can read off it always the same way. getObject() is my accessor, and onIOError will handle exceptions with any of the public API's
Thanks all in advance,
SharingServicesGW IS a factory. However, there's no need for it to - and it shouldn't - inherit from PolimorphSharing. Also you're doing it a bit skewed. The client should be using objects of the interface type, not the abstract type.
Your interface should be defining the public API, not your abstract base class. In fact in AS3 interfaces can only define public members, while pseudo abstract classes can enforce implementation of protected members.
-- EDIT --
here's a UML diagram of how I would do it

Resolve parameters with a custom class

I have a Domain Specific Language, and I would like to register objects that can be instantiated inside.
For instance a class that can do httprequests.
[IoC("HttpRequest", typeof(DslScriptObject), IoCAttribute.IoCLifestyleType.Transient)]
internal class WebRequestDslObj : DslScriptObject
{
[DslNew]
public WebRequestDslObj() : this(null, null)
{}
[DslNew]
public WebRequestDslObj([DslParam("uri")]string uristring, [DslOptionalParam("contenttype")] string contenttype) : this(uristring, null)
{}
}
I then have a class that maps types from my dsl datatypes to c# datatypes (I have them as an IList if that makes any difference), and this works ok, if I do not use Castle to instantiate the object.
But as soon as I want to use IoC to autoregister the various types, then I dont know what to do about the constructors. I have tried to look at setting a CustomComponentActivator, but I got stuck at not being able to find any good example or documentation. Is that a viable path to take? (and will I be able to get around the funny special case for null parameters?)
Anyone have an example of where I can start?
So what are you trying to do with Windsor, because I'm not sure I see where you're going with it...
If you want to affect how component gets register in Windsor, for example rename parameters, you can write custom ComponentModel construction contributor to do it.

How to separate data validation from my simple domain objects (POCOs)?

This question is language agnostic but I am a C# guy so I use the term POCO to mean an object that only preforms data storage, usually using getter and setter fields.
I just reworked my Domain Model to be super-duper POCO and am left with a couple of concerns regarding how to ensure that the property values make sense witin the domain.
For example, the EndDate of a Service should not exceed the EndDate of the Contract that Service is under. However, it seems like a violation of SOLID to put the check into the Service.EndDate setter, not to mention that as the number of validations that need to be done grows my POCO classes will become cluttered.
I have some solutions (will post in answers), but they have their disadvantages and am wondering what are some favorite approaches to solving this dilemma?
I think you're starting off with a bad assumption, ie, that you should have objects that do nothing but store data, and have no methods but accessors. The whole point of having objects is to encapsulate data and behaviors. If you have a thing that's just, basically, a struct, what behaviors are you encapsulating?
I always hear people argument for a "Validate" or "IsValid" method.
Personally I think this may work, but with most DDD projects you usually end up
with multiple validations that are allowable depending on the specific state of the object.
So I prefer "IsValidForNewContract", "IsValidForTermination" or similar, because I believe most projects end up with multiple such validators/states per class. That also means I get no interface, but I can write aggregated validators that read very well reflect the business conditions I am asserting.
I really do believe the generic solutions in this case very often take focus away from what's important - what the code is doing - for a very minor gain in technical elegance (the interface, delegate or whatever). Just vote me down for it ;)
A colleague of mine came up with an idea that worked out pretty well. We never came up with a great name for it but we called it Inspector/Judge.
The Inspector would look at an object and tell you all of the rules it violated. The Judge would decide what to do about it. This separation let us do a couple of things. It let us put all the rules in one place (Inspector) but we could have multiple Judges and choose the Judge by the context.
One example of the use of multiple Judges revolves around the rule that said a Customer must have an Address. This was a standard three tier app. In the UI tier the Judge would produce something that the UI could use to indicate the fields that had to be filled in. The UI Judge did not throw exceptions. In the service layer there was another Judge. If it found a Customer without an Address during Save it would throw an exception. At that point you really have to stop things from proceeding.
We also had Judges that were more strict as the state of the objects changed. It was an insurance application and during the Quoting process a Policy was allowed to be saved in an incomplete state. But once that Policy was ready to be made Active a lot of things had to be set. So the Quoting Judge on the service side was not as strict as the Activation Judge. Yet the rules used in the Inspector were still the same so you could still tell what wasn't complete even if you decided not to do anything about it.
One solution is to have each object's DataAccessObject take a list of Validators. When Save is called it preforms a check against each validator:
public class ServiceEndDateValidator : IValidator<Service> {
public void Check(Service s) {
if(s.EndDate > s.Contract.EndDate)
throw new InvalidOperationException();
}
}
public class ServiceDao : IDao<Service> {
IValidator<Service> _validators;
public ServiceDao(IEnumerable<IValidator<Service>> validators) {_validators = validators;}
public void Save(Service s) {
foreach(var v in _validators)
v.Check(service);
// Go on to save
}
}
The benefit, is very clear SoC, the disadvantage is that we don't get the check until Save() is called.
In the past I have usually delegated validation to a service unto its own, such as a ValidationService. This in principle still ad hears to the philosophy of DDD.
Internally this would contain a collection of Validators and a very simple set of public methods such as Validate() which could return a collection of error object.
Very simply, something like this in C#
public class ValidationService<T>
{
private IList<IValidator> _validators;
public IList<Error> Validate(T objectToValidate)
{
foreach(IValidator validator in _validators)
{
yield return validator.Validate(objectToValidate);
}
}
}
Validators could either be added within a default constructor or injected via some other class such as a ValidationServiceFactory.
I think that would probably be the best place for the logic, actually, but that's just me. You could have some kind of IsValid method that checks all of the conditions too and returns true/false, maybe some kind of ErrorMessages collection but that's an iffy topic since the error messages aren't really a part of the Domain Model. I'm a little biased as I've done some work with RoR and that's essentially what its models do.
Another possibility is to have each of my classes implement
public interface Validatable<T> {
public event Action<T> RequiresValidation;
}
And have each setter for each class raise the event before setting (maybe I could achieve this via attributes).
The advantage is real-time validation checking. But messier code and it is unclear who should be doing the attaching.
Here's another possibility. Validation is done through a proxy or decorator on the Domain object:
public class ServiceValidationProxy : Service {
public override DateTime EndDate {
get {return EndDate;}
set {
if(value > Contract.EndDate)
throw new InvalidOperationexception();
base.EndDate = value;
}
}
}
Advantage: Instant validation. Can easily be configured via an IoC.
Disadvantage: If a proxy, validated properties must be virtual, if a decorator all domain models must be interface-based. The validation classes will end up a bit heavyweight - proxys have to inherit the class and decorators have to implement all the methods. Naming and organization might get confusing.

Fluent Interfaces - Method Chaining

Method chaining is the only way I know to build fluent interfaces.
Here's an example in C#:
John john = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
Assert.IsNotNull(john);
[Test]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;
IInvoice invoice = new InvoiceBuilder()
.IssuedOn(now)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
.Generate();
Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}
So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?
The core idea behind building a fluent interface is one of readability - someone reading the code should be able to understand what is being achieved without having to dig into the implementation to clarify details.
In modern OO languages such as C#, VB.NET and Java, method chaining is one way that this is achieved, but it's not the only technique - two others are factory classes and named parameters.
Note also that these techniques are not mutually exclusive - the goal is to maximize readabilty of the code, not purity of approach.
Method Chaining
The key insight behind method chaining is to never have a method that returns void, but to always return some object, or more often, some interface, that allows for further calls to be made.
You don't need to necessarily return the same object on which the method was called - that is, you don't always need to "return this;".
One useful design technique is to create an inner class - I always suffix these with "Expression" - that exposes the fluent API, allowing for configuration of another class.
This has two advantages - it keeps the fluent API in one place, isolated from the main functionality of the class, and (because it's an inner class) it can tinker with the innards of the main class in ways that other classes cannot.
You may want to use a series of interfaces, to control which methods are available to the developer at a given point in time.
Factory Classes
Sometimes you want to build up a series of related objects - examples include the NHibernate Criteria API, Rhino.Mocks expectation constraints and NUnit 2.4's new syntax.
In both of these cases, you have the actual objects you are storing, but to make them easier to create there are factory classes providing static methods to manufacture the instances you require.
For example, in NUnit 2.4 you can write:
Assert.That( result, Is.EqualTo(4));
The "Is" class is a static class full of factory methods that create constraints for evaluation by NUnit.
In fact, to allow for rounding errors and other imprecision of floating point numbers, you can specify a precision for the test:
Assert.That( result, Is.EqualTo(4.0).Within(0.01));
(Advance apologies - my syntax may be off.)
Named Parameters
In languages that support them (including Smalltalk, and C# 4.0) named parameters provide a way to include additional "syntax" in a method call, improving readability.
Consider a hypothetical Save() method that takes a file name, and permissions to apply to the file after saving:
myDocument.Save("sampleFile.txt", FilePermissions.ReadOnly);
with named parameters, this method could look like this:
myDocument.Save(file:"SampleFile.txt", permissions:FilePermissions.ReadOnly);
or, more fluently:
myDocument.Save(toFile:"SampleFile.txt", withPermissions:FilePermissions.ReadOnly);
You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.
For example in C#:
public class JohnBuilder
{
public JohnBuilder AddSmartCode(string s)
{
// do something
return this;
}
public JohnBuilder WithfluentInterface(string s)
{
// do something
return this;
}
public JohnBuilder ButHow(string s)
{
// do something
return this;
}
}
Usage:
John = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
AFAIK, the term fluent interface does not specify a specific technology or framework, but rather a design pattern. Wikipedia does have an extensive example of fluent interfaces in C♯.
In a simple setter method, you do not return void but this. That way, you can chain all of the statements on that object which behave like that. Here is a quick example based on your original question:
public class JohnBuilder
{
private IList<string> languages = new List<string>();
private IList<string> fluentInterfaces = new List<string>();
private string butHow = string.Empty;
public JohnBuilder AddSmartCode(string language)
{
this.languages.Add(language);
return this;
}
public JohnBuilder WithFluentInterface(string fluentInterface)
{
this.fluentInterfaces.Add(fluentInterface);
return this;
}
public JohnBuilder ButHow(string butHow)
{
this.butHow = butHow;
return this;
}
}
public static class MyProgram
{
public static void Main(string[] args)
{
JohnBuilder johnBuilder = new JohnBuilder().AddSmartCode("c#").WithFluentInterface("Please").ButHow("Dunno");
}
}
Sometime ago I had the same doubts you are having now. I've done some research and now I'm writing a series of blog posts about techinics of designing a fluent interface.
Check it out at:
Guidelines to Fluent Interface design in C# part 1
I have a section there about Chaining X Nesting that can be interesting to you.
In the following posts I will talk about it in a deeper way.
Best regards,
André Vianna
Fluent interface is achieved in object oriented programming by always returning from your methods the same interface that contains the method. Consequently you can achieve this effect in java, javascript and your other favorite object oriented languages, regardless of version.
I have found this technique easiest to accomplish through the use of interfaces:
public interface IFoo
{
IFoo SetBar(string s);
IFoo DoStuff();
IFoo SetColor(Color c);
}
In this way, any concrete class that implements the interface, gets the fluent method chaining capabilities. FWIW.. I wrote the above code in C# 1.1
You will find this technique littered throughout the jQuery API
A couple of things come to mind that are possible in .Net 3.5/C# 3.0:
If an object doesn't implement a fluent interface, you could use Extension Methods to chain your calls.
You might be able to use the object initialization to simulate fluent, but this only works at instantiation time and would only work for single argument methods (where the property is only a setter). This seems hackish to me, but the there it is.
Personally, I don't see anything wrong with using function chaining if you are implementing a builder object. If the builder object has chaining methods, it keeps the object you are creating clean. Just a thought.
This is how I've built my so called fluent interfaces or my only forary into it
Tokenizer<Bid> tkn = new Tokenizer<Bid>();
tkn.Add(Token.LambdaToken<Bid>("<YourFullName>", b => Util.CurrentUser.FullName))
.Add(Token.LambdaToken<Bid>("<WalkthroughDate>",
b => b.WalkThroughDate.ToShortDateString()))
.Add(Token.LambdaToken<Bid>("<ContactFullName>", b => b.Contact.FullName))
.Cache("Bid")
.SetPattern(#"<\w+>");
My example required .net 3.5 but that's only cause of my lambda's. As Brad pointed out you can do this in any version of .net. Although I think lambda's make for more interesting possibilities such as this.
======
Some other good examples are nHibernate's Criteria API, there is also a fluent nhibernate extension for configuring nhibernate but I've never used it
Dynamic keyword in C# 4.0 will make it possible to write dynamic style builders. Take a look at following article about JSON object construction.