In PHP I could have this situation:
<?php
class Person {
public $firstName;
public $lastName;
function __construct($firstName, $lastName)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
function __toString()
{
return "{$this->firstName} {$this->lastName}";
}
}
echo new Person("Adam", "Cameron"); // Adam Cameron
(runnable demo)
I could have sworn there was an equivalent in CFML, eg:
// Person.cfc
component {
function init(id, firstName, lastName){
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
function toString(){
return "#this.firstName# #this.lastName#";
}
}
// test.cfm
writeOutput(new Person("Adam", "Cameron"));
I thought it was new to CF11 or CF2016.
But this dun't work. I know I can do customer serialisers, but that's not a good fit here.
I also know I can effect the same thing in various other ways, but that's not the question here. I am specifically asking about being able to implement a toString method or some such to just be able to specify how to represent an object as a string.
Am I mis-remembering CFML, or am I doing something wrong?
I believe you are thinking of the conversion functions implemented in Lucee...
http://docs.lucee.org/guides/Various/TIPS/TIPS-implicit-conversions.html
_toBoolean()
_toDate
_toNumeric
_toString
To the best of my knowledge, ColdFusion does not have this.
Related
I am working on a very simple program, looking like this:
public class WicketApplication extends WebApplication implements Comparable<Object>{
private List<Person> persons = Arrays.asList(
new Person("Mikkel", "20-02-91", 60169803),
new Person("Jonas", "02-04-90", 86946512),
new Person("Steffen", "15-07-90", 12684358),
new Person("Rasmus", "08-12-93", 13842652),
new Person("Michael", "10-10-65", 97642851));
/**
* #see org.apache.wicket.Application#getHomePage()
*/
#Override
public Class<? extends WebPage> getHomePage() {
return SimpleView.class;
}
public static WicketApplication get() {
return (WicketApplication) Application.get();
}
/**
* #return #see org.apache.wicket.Application#init()
*/
public List<Person> getPersons() {
return persons;
}
public List<Person> getSortedList(){
return Collections.sort(persons);
//This won't work before implementing comparator i know, but how??
}
#Override
public void init() {
super.init();
// add your configuration here
}
#Override
public int compareTo(Object o) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
That was the class where i just put my people into a list.
public class SimpleView extends SimpleViewPage {
public SimpleView() {
ListView persons = new ListView("persons", getPersons()) {
#Override
protected void populateItem(ListItem item) {
Person person = (Person) item.getModelObject();
item.add(new Label("name", person.getName()));
item.add(new Label("birthdate", person.getBirthdate()));
item.add(new Label("phone", person.getPhone()));
}
};
add(persons);
add(new Label("size", "Number of people " + getPersons().size()));
}
}
And here is what i do with the people.
Basicly i want the program to show a table with all the data(this already works).
Now i want to be able to sort them. But i can't for the life of me figure it out. I'm still rather new at programming, and i want to have a button below my table that can sort on name, bday or phone number. Was thinking about trying to Comparable, but can't remember it that well, and not sure how it works with Wicket..
Thanks for the help in advance :)
What you need is the DataView component, which provides all the support you need for sorting (and paging, should you require it later on).
Here's a working example, if you click on the "Source Code" link in the top right corner, you can see that most of the things you want from a sortable table work out of the box. All you need is to create a suitable data provider.
If you use DataView with a SortableDataProvider, you don't need to worry about writing your own dynamic Comparator. (Which is not a terribly hard task itself, but it's easy to get it wrong.)
Is it a good idea to override setters and getters of properties in domain class? Assume we have a domain class with name property and capitalizedName where we store clean up name:
class Person {
String name
String capitalizedName
String setName(String name){
this.name = name
this.searchName = name.replaceAll("[^A-Za-z0-9 ]", "").trim().toUpperCase()
}
}
If I override setter and in a unit test try to use dynamic finder:
Person.findByName('Whatever')
I got
java.lang.IllegalArgumentException: Property [name] is not a valid property of class [com.test.Person]
But in runtime it works pretty fine.
Can I modify getters and setters of a domain class? What is the best way to achieve behaviour as I described above?
A setter should have a return type of void
void setName(String name){
this.name = name
this.searchName = name.trim().replaceAll("[^A-Za-z0-9 ]", "").replaceAll(" +", " ").toUpperCase()
}
Since a while now I'm implementing services whenever possible with ServiceStack (or WebAPI) instead of WCF.
What I want to do now is sending an interface (-name) to the server and get a class-implementation back. Maybe that's confusing, so I'll give you an example:
My service-client has multiple operations - like "check form":
The logic for checking this form is not implemented. What it has is an interface called IFormChecker with methods like NameIsValid(string firstName, string middleName, string lastName).
Instead of sending the whole form-data to the server for validation, the client will request the implementation of IFormChecker from the server.
I know that's possible with WCF, but I have no idea how to do that with ServiceStack.
If that's possible, what's the way to go? I checked the documentation, but I'm not really wiser.
It seams like there's no "magic trick" or anything.
I have to serialize/deserialize the class "old-fashion way".
If you're interested, here's the solution:
I created a "Root"-Interface, in this example it is IModule.
This IModule contains only 1 property, called Name.
It is a string and only there for convenience:
The IFormChecker from the example would be derived from this interface:
My client knows the value of this Name-property and of course the interface itself.
It will now fire the Name-value to the server, which will return the serialized class.
All I have to do is:
var module = ModuleImplementations.FirstOrDefault(x => x.Name == name);
if(module == null) throw new SomeException();
return module.Serialize();
client-wise I can deserialize it and cast it to the interface. That's it.
Here's my ModuleSerialization-Class:
public static class ModuleSerialization
{
public static string Serialize(this IModule m)
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, m);
return Convert.ToBase64String(ms.ToArray());
}
}
public static T Deserialize<T>(string serialized) where T : class, IModule
{
var ba = Convert.FromBase64String(serialized);
using (var s = new MemoryStream(ba))
{
var bf = new BinaryFormatter();
return bf.Deserialize(s) as T;
}
}
}
Cheers!
I am using NSubstitute for my Unit tests. I need to check that a object is send to a void method inside the method I am testing. I only need to check that the object is sent with one of the properties being a certain value.
eg.
///The object in question
public class Person
{
public string Name { get; set; }
public string Surname{get;set;}
}
Two simple methods
public void NameStartsWithA(Person person)
{
//do something to person when name starts with A
}
public void NameStartsWithB(Person person)
{
//do something to person when name starts with B
}
The method i am writing the test for.
public void MethodBeingTested()
{
var person = new Person() {Name = "Adrian",Surname="SomeSurname"};
if(person.Name.StartsWith("A"))
NameStartsWithA(person);
else
NameStartsWithB(person);
}
If the person name starts with an A, I need to check, using NSubstitute that the "NameStartsWithA" was called with a name that starts with an A.
My Unit Test so far looks something like this
_someService.Received().NameStartsWithA(new Person(){Name="Adrian",Surname=Arg.Any<string>()});
But Nsubstitute says the function was never called, but when I do the same test with "RecievedArgumentsAny()" then it passes.
Hope this example helps you in understanding what I am trying to accomplish.
got this to work. Posting the code.
_someService.Received().NameStartsWith(Arg.Is<Person>(p => p.Name.Startswith== "A"));
hopes this will help someone in the future.
I am very curious about the possibility of providing immutability for java beans (by beans here I mean classes with an empty constructor providing getters and setters for members). Clearly these classes are not immutable and where they are used to transport values from the data layer this seems like a real problem.
One approach to this problem has been mentioned here in StackOverflow called "Immutable object pattern in C#" where the object is frozen once fully built. I have an alternative approach and would really like to hear people's opinions on it.
The pattern involves two classes Immutable and Mutable where Mutable and Immutable both implement an interface which provides non-mutating bean methods.
For example
public interface DateBean {
public Date getDate();
public DateBean getImmutableInstance();
public DateBean getMutableInstance();
}
public class ImmutableDate implements DateBean {
private Date date;
ImmutableDate(Date date) {
this.date = new Date(date.getTime());
}
public Date getDate() {
return new Date(date.getTime());
}
public DateBean getImmutableInstance() {
return this;
}
public DateBean getMutableInstance() {
MutableDate dateBean = new MutableDate();
dateBean.setDate(getDate());
return dateBean;
}
}
public class MutableDate implements DateBean {
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public DateBean getImmutableInstance() {
return new ImmutableDate(this.date);
}
public DateBean getMutableInstance() {
MutableDate dateBean = new MutableDate();
dateBean.setDate(getDate());
return dateBean;
}
}
This approach allows the bean to be constructed using reflection (by the usual conventions) and also allows us to convert to an immutable variant at the nearest opportunity. Unfortunately there is clearly a large amount of boilerplate per bean.
I am very interested to hear other people's approach to this issue. (My apologies for not providing a good question, which can be answered rather than discussed :)
Some comments (not necessarily problems):
The Date class is itself mutable so you are correctly copying it to protect immutability, but personally I prefer to convert to long in the constructor and return a new Date(longValue) in the getter.
Both your getWhateverInstance() methods return DateBean which will necessitate casting, it might be an idea to change the interface to return the specific type instead.
Having said all that I would be inclined to just have two classes one mutable and one immutable, sharing a common (i.e. get only) interface if appropriate. If you think there will be a lot of conversion back and forth then add a copy constructor to both classes.
I prefer immutable classes to declare fields as final to make the compiler enforce immutability as well.
e.g.
public interface DateBean {
public Date getDate();
}
public class ImmutableDate implements DateBean {
private final long date;
ImmutableDate(long date) {
this.date = date;
}
ImmutableDate(Date date) {
this(date.getTime());
}
ImmutableDate(DateBean bean) {
this(bean.getDate());
}
public Date getDate() {
return new Date(date);
}
}
public class MutableDate implements DateBean {
private long date;
MutableDate() {}
MutableDate(long date) {
this.date = date;
}
MutableDate(Date date) {
this(date.getTime());
}
MutableDate(DateBean bean) {
this(bean.getDate());
}
public Date getDate() {
return new Date(date);
}
public void setDate(Date date) {
this.date = date.getTime();
}
}
I think I'd use the delegation pattern - make an ImmutableDate class with a single DateBean member that must be specified in the constructor:
public class ImmutableDate implements DateBean
{
private DateBean delegate;
public ImmutableDate(DateBean d)
{
this.delegate = d;
}
public Date getDate()
{
return delegate.getDate();
}
}
If ever I need to force immutability on a DateBean d, I just new ImmutableDate(d) on it. I could have been smart and made sure I didn't delegate the delegate, but you get the idea. That avoids the issue of a client trying to cast it into something mutable. This is much like the JDK does with Collections.unmodifiableMap() etc. (in those cases, however, the mutation functions still have to be implemented, and are coded to throw a runtime exception. Much easier if you have a base interface without the mutators).
Yet again it is tedious boilerplate code but it is the sort of thing that a good IDE like Eclipse can auto-generate for you with just a few mouse clicks.
If it's the sort of thing you end up doing to a lot of domain objects, you might want to consider using dynamic proxies or maybe even AOP. It would be relatively easy then to build a proxy for any object, delegating all the get methods, and trapping or ignoring the set methods as appropriate.
I use interfaces and casting to control the mutability of beans. I don't see a good reason to complicate my domain objects with methods like getImmutableInstance() and getMutableInstance().
Why not just make use of inheritance and abstraction? e.g.
public interface User{
long getId();
String getName();
int getAge();
}
public interface MutableUser extends User{
void setName(String name);
void setAge(int age);
}
Here's what the client of the code will be doing:
public void validateUser(User user){
if(user.getName() == null) ...
}
public void updateUserAge(MutableUser user, int age){
user.setAge(age);
}
Does it answer your question?
yc