Thursday, June 14, 2012

Display Code More Readable On Blog Or Website

For technical blogger, it is very common to put to some source code snippet on the website. A lot of times, we just cut and paste the code directly on the website as HTML and wish everything is going to look just right. But imagine of using Arial font size 14 for all your code, it might not look as nice and readable as you may expect like the way you been coding all day long. Lets look at the original code like this,

CREATE TABLE dbo.MainTable
(
ID bigint IDENTITY NOT NULL,
DateCreate Date NOT NULL,
UserName nvarchar(50) NOT NULL
);

CREATE TABLE dbo.SubTable
(
ID bigint IDENTITY NOT NULL,
MainID bigint NOT NULL,
ShortDescription nvarchar(100) NOT NULL
);

SELECT MT.ID, MT.DateCreate, MT.UserName, ST.ShortDescription
FROM dbo.MainTable MT INNER JOIN
dbo.SubTable ON MT.ID = ST.MainID
WHERE MT.UserName = 'AwesomeUser'
ORDER BY MT.DateCreate DESC;

It's a bit hard to read here. Now, lets put <code> wrap around it.

CREATE TABLE dbo.MainTable
(
ID bigint IDENTITY NOT NULL,
DateCreate Date NOT NULL,
UserName nvarchar(50) NOT NULL
);

CREATE TABLE dbo.SubTable
(
ID bigint IDENTITY NOT NULL,
MainID bigint NOT NULL,
ShortDescription nvarchar(100) NOT NULL
);

SELECT MT.ID, MT.DateCreate, MT.UserName, ST.ShortDescription
FROM dbo.MainTable MT INNER JOIN
dbo.SubTable ON MT.ID = ST.MainID
WHERE MT.UserName = 'AwesomeUser'
ORDER BY MT.DateCreate DESC;


Looks pretty good. I think we could do better, lets use some syntax highlighter,

CREATE TABLE dbo.MainTable
(
 ID bigint IDENTITY NOT NULL,
 DateCreate Date NOT NULL,
 UserName nvarchar(50) NOT NULL
);

CREATE TABLE dbo.SubTable
(
 ID bigint IDENTITY NOT NULL,
 MainID bigint NOT NULL,
 ShortDescription nvarchar(100) NOT NULL
);

SELECT MT.ID, MT.DateCreate, MT.UserName, ST.ShortDescription
FROM dbo.MainTable MT INNER JOIN
   dbo.SubTable ON MT.ID = ST.MainID
WHERE MT.UserName = 'AwesomeUser'
ORDER BY MT.DateCreate DESC;

I don't know about you, but this look awesome to me (it may not show the syntax highlighting in your RSS reader) . It shows a similar appearance like what the regular coder familiar with. To me, it is much more readable. If you like what syntax highlighter that is being used here, follow this link for the instructions.



No comments:

Post a Comment