Which on is better? Date.now() or new Date() - meteor

Is there any pros or cons? (in case of storing date inside database)
In Meteor _id field doesn't represent insert time.
Also. I know that MongoDB expireAfterSeconds TTL doesn't work with Date.now()
Seems like new Date() is more universal and you can always make Date.now() from it.
Anything else? This question is more about use cases. So if you had problems with any, let us know

new Date() is a much more object-oriented way of passing information around. It is generally the preferred method.

Actually, they are semantically equivalent, although Date.now() is much faster.

Related

Redux: can I mutate state in reducer and pass new object of the same

I know that we are not suppose to mutate the state because, the app re-renders based on the fact if there has been changes in the reference in previous state and next State, but what id I do something like this
reducerFunction = (state, action) => {
state.value = action.value;
return {...state}
}
Here I am passing a new reference, so is there anything wrong with it which could happen because of state mutation
This will work but you are mutating older state and then creating new one and return it. This is not recommended. In some case this may be an issue if you need undo functionality.
Two problems that I can think of.
You would loose (or mess up) the undo history feature of redux. This comes in really handy sometimes, especially when you are dealing with lots of data.
You are assuming synchronous execution of the code. Redux (and JS in general) makes no such guarantees. In an application where you are updating the store with anything computer-generated (practically anything that is not user inputs) and reading it back somewhat quickly, this would mess up the state and you will have a Race Condition.
Generally, it is a good idea to follow the implementation guidelines to have your code run predictably. Sometimes there is error checking for things that are non-standard, simply because it might break the code. It can potentially be a security issue. I do it all the time when I write APIs.

Is GetHashCode just cargo-cult here?

HttpContext.Current.Items["ctx_" + HttpContext.Current.GetHashCode().ToString("x")]
I see this exact code all ... over ... the ... place but I must be overlooking something. It's common in responses to these posts to question the appropriateness of using HttpContext, but no one points out that GetHashCode is redundant and a fixed string will do.
What am I overlooking here?
EDIT: The question is, GetHashCode() will be the same for every HttpContext.Current, so why use GetHashCode() in the four links I provided? Some of them are posts with quite a bit of work put into them, so I feel like perhaps they are addressing some threading or context issue I'm overlooking. I don't see why just HttpContext.Current.Items["ctx_"] wouldn't do exactly the same.
This is horrible. For one, HttpContext.Current.Items is local to the current HttpContext anyway so need to attempt to make the keys "more unique". Second, depending on how this technique is used the keys will collide once in a while causing spurious, undebuggable failures.
If you need a unique key (maybe because you are developing a library), use a saner solution like Guid.NewGuid().ToString(). This is guaranteed to work and even simpler.
So to answer your question :)
It doesn't make much sense to use GetHashcode for creating key.
Authors of posts you gave links to probably wanted to create key that will be unique. But doing this doesn't stop other team member to use same key somewhere else in the code base.
I think it's better to just use handwritten long keys. Instead of
["ctx_" + HttpContext.Current.GetHashCode().ToString("x")]
just use
["object_context_key"]
or something like that. That way you know what it is exactly (and that may be usefull in for example post mortem debugging) and I also think that if you have to come up with some long key it is possible that it will be 'more unique' then the one with GetHashCode.

Which is faster? Loop over object properties or linq query?

Is this faster
var query = from prop in object.GetType().GetProperties()
where prop.Name == "Id"
select prop;
var singleProperty = query.SingleOrDefault();
//do stuff with singleProperty
than this?
var type = object.GetType();
foreach(var prop in type.GetProperties())
{
if(prop.Name == "Id")
{
//do stuff
}
}
The other way around? Or are they the same?
Why and how would you know?
Sorry to be overly direct in my question. I prefer the first one but I don't know why or if I should.
Thanks.
Technically, the first case may allocate more memory and do more processing to generate the final result than the second case because of the intermediate data and LINQ abstractions. But the amount of time and memory is so negligible in the grand scope of things, that you're way better off making your code the most readable than the most efficient for this scenario. It's probably a case of premature optimization.
Here are some references why the first may be slightly slower:
http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html
http://ox.no/posts/linq-vs-loop-a-performance-test
http://geekswithblogs.net/BlackRabbitCoder/archive/2010/04/23/c-linq-vs-foreach---round-1.aspx
The correct answer is: use Reflector to see what's being generated by the compiler.
That said, your LINQ query is using the same mechanism to retrieve the property list as your other snippet. It should technically be faster without involving the linq overhead. However, I'd expect the difference to be minimal (ie, unperceivable) , so this really comes down to a code readability and maintainability decision.
And I hate LINQ, so skip it.
Retrospective, one year later:
I've found that LINQ isn't the demon that I thought it was. I'm actually pretty impressed with its implementation, and spent quite a bit of time looking at the IL trying to find a legitimate reason not to like it.
That said: LINQ-to-objects is pretty slick. However, future generations working on projects with a database: don't use this as a reason to perform all of your queries on the client instead of letting your database server do what it's very, very good at.
They are the same in terms of performance because LINQ makes use of deferred execution. However, a trivially (and irrelevant) larger amount of memory may go into the LINQ option.
Therefore, they are (effectively) identical in performance and behaviour!
I would go with the LINQ version for readability because I like LINQ but to each their own.

Concise way of getting date from java.util.date

I'm trying to retrieve the date only from a java.util.date. I know I can set the time to 0 but I'm searching for a cleaner, more concise way if possible. Does this exist?
Thanks!
Krt_Malta
The cleaner way is to use Joda Time to start with, where there are separate concepts of LocalDate, LocalTime, LocalDateTime, DateTime, Instant etc.
You can translate between java.util.Date and the Joda types, but I would suggest you stick to using Joda for as much of the code as you can, and only translate when you really need to.
Sorry if you'd hoped to avoid an extra library - but Joda is so much better than the built-in API, it's well worth investing in the effort IMO. Note that within the Java types you'll need to determine which time zone you're interested in - java.util.Date defines an instant in time, which may occur in as many as three different dates around the world depending on your time zone.
Another option is the truncate method in the DateUtils library. You put in the date and the field up to which you are interested (in this case CALENDAR.DAY_OF_MONTH). The rest will be set to 0. Effectively:
DateUtils.truncate(Calendar.getInstance(), Calendar.DAY_OF_MONTH).getTime()
did the job.
More info about the method is at: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/time/DateUtils.html#truncate%28java.lang.Object,%20int%29

Why are getters prefixed with the word "get"?

Generally speaking, creating a fluid API is something that makes all programmers happy; Both for the creators who write the interface, and the consumers who program against it. Looking beyond conventions, why is it that we prefix all our getters with the word "get". Omitting it usually results in a more fluid, easy to read set of instructions, which ultimately leads to happiness (however small or passive). Consider this very simple example. (pseudo code)
Conventional:
person = new Person("Joey")
person.getName().toLower().print()
Alternative:
person = new Person("Joey")
person.name().toLower().print()
Of course this only applies to languages where getters/setters are the norm, but is not directed at any specific language. Were these conventions developed around technical limitations (disambiguation), or simply through the pursuit of a more explicit, intentional feeling type of interface, or perhaps this is just a case of trickle a down norm. What are your thoughts? And how would simple changes to these conventions impact your happiness / daily attitudes towards your craft (however minimal).
Thanks.
Because, in languages without Properties, name() is a function. Without some more information though, it's not necessarily specific about what it's doing (or what it's going to return).
Functions/Methods are also supposed to be Verbs because they are performing some action. name() obviously doesn't fit the bill because it tells you nothing about what action it is performing.
getName() lets you know without a doubt that the method is going to return a name.
In languages with Properties, the fact that something is a Property expresses the same meaning as having get or set attached to it. It merely makes things look a little neater.
The best answer I have ever heard for using the get/set prefixes is as such:
If you didn't use them, both the accessor and mutator (getter and setter) would have the same name; thus, they would be overloaded. Generally, you should only overload a method when each implementation of the method performs a similar function (but with different inputs).
In this case, you would have two methods with the same name that peformed very different functions, and that could be confusing to users of the API.
I always appreciate consistent get/set prefixing when working with a new API and its documentation. The automatic grouping of getters and setters when all functions are listed in their alphabetical order greatly helps to distinguish between simple data access and advanced functinality.
The same is true when using intellisense/auto completion within the IDE.
What about the case where a property is named after an verb?
object.action()
Does this get the type of action to be performed, or execute the action... Adding get/set/do removes the ambiguity which is always a good thing...
object.getAction()
object.setAction(action)
object.doAction()
In school we were taught to use get to distinguish methods from data structures. I never understood why the parens wouldn't be a tipoff. I'm of the personal opinion that overuse of get/set methods can be a horrendous time waster, and it's a phase I see a lot of object oriented programmers go through soon after they start.
I may not write much Objective-C, but since I learned it I've really come to love it's conventions. The very thing you are asking about is addressed by the language.
Here's a Smalltalk answer which I like most. One has to know a few rules about Smalltalk BTW.
fields are only accessible in the they are defined.If you dont write "accessors" you won't be able to do anything with them.
The convention there is having a Variable (let's anme it instVar1.
then you write a function instVar1 which just returns instVar1 and instVar: which sets
the value.
I like this convention much more than anything else. If you see a : somewhere you can bet it's some "setter" in one or the other way.
Custom.
Plus, in C++, if you return a reference, that provides potential information leakage into the class itself.

Resources