Latest Entries »

Do you remember the first time you did things which made your guardian angel sob? But you did it again, didn’t you? How does it feel? But when you get used to doing it over and over again, you never notice it at all right? Right.

I was told that eval is evil. But honestly, I was never told… I just have read it somewhere. Sigh, my conscience pulls me away from lying (again). Well, anyways, enough for the old-school Safeguard commercial, here goes my head’s brainstorm — or brainhurricane — for its being fast and direct-to-the-point-ish thingy.

I was working on a very small project with a very less time to work on it. By less time I mean less than four hours. Basically the project was some sort of a calculator, which has not-so-dynamic formulas which are inputted by the user. I was not able to find a good formula parser (provided that I did not have an adequate internet connection and the time constraint was forcing my hands to tap the keys), so I wrote my own. Here goes my code:

public double parseFormula(double value, String formula){
    String expression = formula.replaceAll("value", value + "");
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
    try {
        return Double.parseDouble(engine.eval(expression).toString());
    } catch(ScriptException exception) {
        exception.printStackTrace();
    }
    return 0;
}

They said eval() is evil especially if it’s in javascript, but the code is in Java, so I don’t need to worry. Or is it?..

I used a javascript engine for a Java program! Wait, what?! Oh, no, the evil thing is lurking… But I shouldn’t care anymore since it was just a very small project. The good thing is that it works! I did not think that the program will be modified in the future thus eval() was a necessary evil.

The statement above made me think – why are Evil Geniuses called Evil Geniuses? Is it possible they used eval()?

*insert part where Perry raids Heinz because of doing eval()*

To be honest, I don’t know how to write the title of this post since the ideas and theme I am going to write will not be fully unified. I’m just actually adding items to discuss when something with regards to what I need to write pops out of my sleepy brain. But for the love of potatoes, I’ll just write (type, actually) anything that I could think of.

First: Why does the word “potatoes” exist on the first paragraph?

Second: Should I continue typing provided that I don’t know if the next words could even make any sense?

Third: Why am I uneasy with other people’s generally agreed upon “best practices” on database design? Seriously, if the general circle of database creators follow these practices, I doubt if there wouldn’t be any problems down the line. There is no such thing as perfect program, so I could presume the imperfection of their system was due to their database structure. But nah, I must be sleepy. Don’t worry though, I will not force you to follow what my ideas are; this is just for my reference.

Here are the lists of the best practices that I am going to scrutinize for the sake of scrutiny:
Database Best Practices

Always have a PrimaryKey.
-Wait, what?! Given the fact that the column could never be used, the column consumes computer memory (and human memory as well) and that elephants could never jump, why in the world should a waste of electrons be added?!
-But to tell you frankly, I always have a primary key on my tables for the reason that I don’t know the answer to my question. It’s ironic that an iron cannot be ironed.

Use consistent column name suffixes and prefixes.
-It’s true that shit_Students table looks better than SouthHarmonInstituteOfTechnologyStudents for a very good reason, but Students is way better than the one with prefix for a very good reason. For example, the database schema will not only be used by S.H.I.T. for their system but will also be used by another school (presume we make a generic system), thus the prefix shit_ is useless and misleading. And if a new developer joins the team, and for some reason was not briefed on the project (which actually happened to me before), how would he know what shit_ stands for? Students as the table’s name is way okay-er since it’s readable and reusable.

Don’t use short column names.
-ID as a field name is discouraged by them. Oh, come on, would you want your primary key column for table TheTableWithNoName be TheTableWithNoNameID? ID as a field name is tempting and is oftentimes correct. For objects generated from database, one would prefer TheTableWithNoName.ID than TheTableWithNoName.TheTableWithNoNameID. For as long as the thing is understandable, and very understandable, it’s already understood. True story.
-The thing is, I can’t find a good long table name aside from TheTableWithNoName. Sorry, was too sleepy.

Fourth: I realized that my post is already long enough, I need to sleep.

Fifth: I have nothing more. Maybe next time when there will be a brainstorm (storm in my brain) i could write longer. Good night. :-)

Woke up early this morning, and by early I mean 3:00 am GMT +8:00, feeling the global warming. Darn, it was brownout again! I couldn’t blame NORECO (Negros Oriental Electric Cooperative, synonymous with brownout) because that’s what they’re good at.

But what the heck! They’re doing this over and over again, like in 2-hour intervals. No, I’m over-exaggerating — it’s just 1-hour interval of brownouts! The feeling of I-Know-What-Will-Happen-In-59-Minutes is always there every time the power is back. And that gut-feeling is seldom wrong.

The hotness earlier sent me into an epiphany: what if, because of the warmth due to brownouts, my skin gets burned, and I die? What if?! It’s not that I’m going to die soon or something, but what if?

But if I just died because of that lame fortuitous event, I am seriously going to hunt and haunt whoever ate the electrical wire. NORECO, that goes to you!

Back to my death: Well, I know the title says my last will and testament, but actually I don’t have any material things to bequeath, so as an alternative, here are the list of the things people should and shouldn’t do:

* No chanting of “prayers” on my wake as they may call it. Man, isn’t it annoying to hear those redundant phrases uttered by mouths who aren’t sincere enough to pray? I don’t know if there were horses, but those people’s mouths were running like they were on a horse race. If that happens to my wake, I would surely get up from the coffin and kindly ask them to be quiet because I am sleeping. Now, that would be fun!

* Drink coffee moderately. Well said.

* No gambling. Period. I said period. Why would anyone insist on gambling when the dead can’t join, eh?! A lame excuse: So they can remain awake. A good solution: Here, play my Guitar Hero, or watch a dirty movie.

* No crying. Please. (As I’m writing this part, I’m beginning to cry like a baby — with the very loud voice.) But the good part of not crying is no funny faces. Seriously. Have you seen your face cry so badly? I guess not, but try crying in front of the mirror like you lost your favorite tooth, and you’ll see what I mean.

Terms are subject to change without prior notice. By the way, I did mention about Guitar Hero, but actually I don’t have one, so you could just go with the dirty movie instead.

Darn, I totally forgot. You can’t watch any movie too because it would be brownout (expectedly). *sigh*

Those who have watched Wrong Turn movies, raise your hands. Anyone? I can’t see them. Higher please… Higher… Now we’re talking. Anyways, whether you have seen the movie or not, here’s how the stories went: people drove too far, went through wrong turns, and at the end, gotten killed by hillbillies. That’s horror.

Now, as developers, the first thing we need to secure is the safety of our users that they won’t go through wrong turns. Or they wouldn’t leave out site, so to speak.
Here’s something: They go to the sign-up page, at the bottom is the checkbox for “I have agreed…” and a link to the page about what the user has to agree upon. Some users just don’t read, but some really do. Now, for the latter, they click the link and get redirected to the specified page. They’ll likely to agree because they have to. But they don’t know where to go now. THEY’LL GET EATEN BY HILLBILLIES!!!

Protecting them via jQuery is painless. This is how I do it on the signup page. On the body, the code goes like this:

<p>
    This is the sign-up page body content.
    The one below is the checkbox.
</p>
<input type="checkbox" id="chkOk"></input>
I have read and accepted the
<a id="lnkTermsAndConditions" href="#">Terms and Conditions</a>
<script type="text/javascript">
    $("#lnkTermsAndConditions").click(function(){
        window.open("terms-and-conditions.html",
            "termsAndConditions",
            "width=450,height=300,resizable=yes,scrollbars=yes,toolbar=no" );
    });
</script>

and on the terms and conditions page:

<p>
    The terms and conditions should around here somewhere.
</p>
<input type="submit" id="btnSubmit" value="I Agree"></input>
<script type="text/javascript">
    $("#btnSubmit").click(function(){
        try {
            $("#chkOk", window.opener.document).attr("checked", "checked");
        } catch (exception) {}
        window.close();
    });
</script>

And of course, we need to put this on both page’s heads:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

What happens?

Users who do not read the Terms and Conditions page just checks the checkbox. No problem. But users who scrutinize such terms and conditions click the link, a pop-up window appears, the page is read until the bottom, and a button saying “I Agree” is clicked, the checkbox on the window opener page is checked, and that popup window closes. Ta da! The users are back on the right track.

So that’s how we could at least prevent our site’s users from starring in a scary movie. Off for another movie marathon!

Howdy, Singleton!

Funny how one of my favorite authors and my daughter have the same name: Erich.

And since I have started with names, I will continue this post with the awesomely-named OOP Design Pattern – Singleton.

Well, I haven’t mentioned that one of the books Erich (Gamma, the author) co-authored, with three other awesome people, was “Design Patterns: Elements of Reusable Object-Oriented Software” and it contains a topic on the Singleton pattern, coincidentally. Or not.

Anywho, here’s my little recipe in C#.Net 4.0:

public sealed class Singleton {
    private Singleton() { }

    private static readonly object lockObject = new object();
    private static Singleton instance = null;
    public static Singleton Instance {
        get {
            lock (lockObject) {
                return instance ?? (instance = new Singleton());
            }
        }
    }
}

Ingredients:

  • A private constructor – so the class could not be instantiated in any other way except through using the Instance property.
  • A private static object as a lock object – this way, the instance is created/called thread-safely
  • A private static instance of the class initialized to null – it will be created only when needed. That’s lazy. That’s me.
  • Of course, the main spice, the public static property which returns the needed instance.

Preparation:

  1. On the public static instance property, apply the lock before returning the initialized instance;
  2. Before returning, check if the private instance is null, and if so, initialize it once and for all.
  3. Return the initialized instance, then let cool for 3 minutes.

For those who wondered why no code checks if instance is null, there is this thing called Null Coalesce. For those who already know about it, I know you know better. =)

Serving Suggestion:

Singleton singleton = Singleton.Instance;

Therefore I conclude that the conclusion is up to my readers.

Random Linq Extensions

A random thought just popped out from my brain: “What if we need something randomly from random items?”
Well, it makes no sense, but what makes sense is the far-out follow-up question in my head:
“How can we get a random item from an IEnumerable of items?”
So in order to answer that random question, I made a class with extension methods for Linq which gets a random item from a specified IEnumerable. So here it goes:


using System;
using System.Collections.Generic;
using System.Linq;

namespace Ynnorj.Extensions {

    public static class LinqExtensions {

        public static Random random = null;
        public static Random Random {
           get { return random ?? (random = new Random()); }
        }

        public static bool IsNullOrEmpty<TSource>(this IEnumerable<TSource> source) {
            return source == null || !source.Any();
        }

        public static TSource SelectRandom<TSource>
            (this IEnumerable<TSource> source) {
            TSource? result = !source.IsNullOrEmpty() 
                ? source.ElementAt(Random.Next(source.Count())) 
                : null;
            return result.Value;
        }

        public static TResult SelectRandom<TSource, TResult>
            (this IEnumerable<TSource> source, Func<TSource, TResult> selector) {
            TResult? result = !source.IsNullOrEmpty() 
                ? source.Select(selector).SelectRandom() 
                : null;
            return result.Value;
        }
    }
}

I don’t have any compiler here, but this is just a random answer anyways. I might need to update the code if this does not compile as soon as I get to a development machine. (lol)
By the way, did I mention that the random word for the day is “random“?

Follow

Get every new post delivered to your Inbox.